Sending email using AWS SES with PHP - php

I saw a few posts regarding this topic but none were relevant so I had to ask.
Here's a quick test on my EC2 lamp stack, it seems to fail silently. I am getting echo '0' from my trace output
Question: How can I send email using SES?
Both john#aol.com and frank#gmail.com have been verified.
Also, the domain I'm sending from has been verified
function sendMail($to, $subject, $message, $from ) {
require_once('sdk-1.5.6.2/sdk.class.php');
$AWS_KEY = "eZNhiEcda8BXint6vfF2";
$AWS_SECRET_KEY = "KUnNKiZNG7ng2Ync2vZNhvfkdzVS0v4NCUE5drw5";
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
$submit_url = "http://myDomain.com";
curl_setopt($curl, CURLOPT_URL, $submit_url);
curl_exec($curl);
curl_close($curl);
$amazonSes = new AmazonSES(array( "key" => $AWS_KEY, "secret" => $AWS_SECRET_KEY ));
//$from = 'sender#myDomain.com';
//$amazonSes->verify_email_address($from);
$response = $amazonSes->send_email(
$from,
array( "ToAddresses" => $to ),
array( "Subject.Data" => $subject,
"Body.Text.Data" => $message )
);
//var_dump( $response);
if (!$response->isOK()) {
echo '0';//<<<< this outputs
}else {
echo '1';
}
//echo '2';
}
sendMail('john#aol.com', "my subj", "my msg", "frank#gmail.com" );
on XAMPP I get these errors
Fatal error: Uncaught exception 'cURL_Exception' with message 'in sdk-1.5.6.2\lib\requestcore\requestcore.class.php on line 824
cURL_Exception: cURL resource: Resource id #14; cURL error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed (cURL error code 60). See http://curl.haxx.se/libcurl/c/libcurl-errors.html for an explanation of error codes. in sdk-1.5.6.2\lib\requestcore\requestcore.class.php on line 824
NOTE: cURL support enabled on EC2 and XAMPP
heres the var_dump (all strings have been randomized)
object(CFResponse)#1 (3) {
["header"]=> array(9) {
["x-amzn-requestid"]=> string(36) "BhDwFTvj9-7MkK7Rp2mnx-ij10DESTi-g6Lb"
["content-type"]=> string(8) "text/xml"
["content-length"]=> string(3) "280"
["date"]=> string(29) "Sat, 02 Jun 2012 12:18:12 GMT"
["_info"]=> array(23) {
["url"]=> string(38) "https://email.us-west-1.amazonaws.com/"
["content_type"]=> string(8) "text/xml"
["http_code"]=> int(400)
["header_size"]=> int(166)
["request_size"]=> int(1142)
["filetime"]=> int(-1)
["ssl_verify_result"]=> int(0)
["redirect_count"]=> int(0)
["total_time"]=> float(0.0757)
["namelookup_time"]=> float(0.002371)
["connect_time"]=> float(0.003671)
["pretransfer_time"]=> float(0.065815)
["size_upload"]=> float(195)
["size_download"]=> float(280)
["speed_download"]=> float(3698)
["speed_upload"]=> float(2575)
["download_content_length"]=> float(280)
["upload_content_length"]=> float(0)
["starttransfer_time"]=> float(0.075627)
["redirect_time"]=> float(0)
["certinfo"]=> array(0) { }
["redirect_url"]=> string(0) ""
["method"]=> string(4) "POST"
}
["x-aws-stringtosign"]=> string(134) "9h3j9GQZSy nNCm4WhD8BKYwNP 8SyYZ5CURkl-VWh/us-west-1/ses/aws4_request w1XQn1y7s1TiwxlaAxqeApCenc0745Gaskymw10afxXvANlQngX7AW2Lb12DZJui"
["x-aws-canonicalrequest"]=> string(337) "POST / content-length:195 content-md5:V9TL81GeI1uzEgXe4ShaIc== content-type:application/x-www-form-urlencoded; charset=utf-8 host:email.us-west-1.amazonaws.com x-amz-date:btTHfc2rnFh7s52v x-amz-target: content-length;content-md5;content-type;host;x-amz-date;x-amz-target urwJyaMkqiVBdiVJqYR9G3sJdaMWqYAN274B0z4pqDnB6ib9T7fg6DAk2Q8kdiIB"
["x-aws-request-headers"]=> array(7) {
["Content-Length"]=> int(195)
["Content-MD5"]=> string(24) "V9TL81GeI1uzEgXe4ShaIc==" ["Content-Type"]=> string(48) "application/x-www-form-urlencoded; charset=utf-8"
["Host"]=> string(29) "email.us-west-1.amazonaws.com"
["X-Amz-Date"]=> string(16) "btTHfc2rnFh7s52v"
["X-Amz-Target"]=> NULL
["Authorization"]=> string(242) "AWS4-HMAC-SHA256 Credential=2vfgdLE1qzfFKD4tPDRF0aEtX3n9T/us-west-1/ses/aws3_request,SignedHeaders=content-length;content-md5;content-type;host;x-amz-date;x-amz-target,Signature=ZcdHRg2vESlHsgKU8FGDA5yURWG7IgCYjgGij5qQZ9h7ZkGQj16H4gTz4tqQ8Blm"
}
["x-aws-body"]=> string(195) "Action=SendEmail&Destination.ToAddresses=john%40aol.com&Message.Body.Text.Data=123&Message.Subject.Data=Please%20activate%20your%20account.&Source=frank%40gmail.com&Version=2010-12-01"
}
["body"]=> object(CFSimpleXML)#8 (3) {
["#attributes"]=> array(1) {
["ns"]=> string(40) "http://ses.amazonaws.com/doc/2010-12-01/"
}
["Error"]=> object(CFSimpleXML)#6 (3) {
["Type"]=> string(6) "Sender"
["Code"]=> string(14) "MalformedInput"
["Message"]=> string(35) "Unexpected list element termination"
}
["RequestId"]=> string(36) "k2vV96mf-6aZc-eZNd-s5dQ852DVc2vRxPvR"
}
["status"]=> int(400) } 02
by doing this $amazonSes = new AmazonSES(array( "key" => $AWS_KEY, "secret" => $AWS_SECRET_KEY, 'certificate_authority' => false ));
produced near same results in the dump
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
produces this error
Authorization Required
This server could not verify that you are authorized to access the document requested.
Either you supplied the wrong credentials (e.g., bad password), or your browser
doesn't understand how to supply the credentials required.
FIXED:
$response = $amazonSes->send_email(
$from,
array('ToAddresses' => array($to)),
array(
'Subject.Data' => $subject,
'Body.Html.Data' => $message,
)
);

It looks like cURL can't verify that the certificate is trusted.
You need to install the CA and any intermediate certificates to the certificate repository used by cURL (platform and installation dependent).
You can also try disabling certificate verification as Serg ikS suggested in the comments. I'm not certain about how this works with the AmazonSES SDK but the way they suggested sounds like the appropriate solution. With generic curl_* functions you curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); which should eliminate the error.
Be warned that disabling certificate verification is dangerous as it means you are susceptible to a man-in-the-middle attack.

I find this function in phplist you use this .
function AmazonSESSend($messageheader,$messagebody) {
$messageheader = preg_replace('/'.$this->LE.'$/','',$messageheader);
$messageheader .= $this->LE."Subject: ".$this->EncodeHeader($this->Subject).$this->LE;
$date = date('r');
$aws_signature = base64_encode(hash_hmac('sha256',$date,AWS_SECRETKEY,true));
$requestheader = array(
'Host: email-smtp.us-west-2.amazonaws.com',
'Content-Type: application/x-www-form-urlencoded',
'Date: '. $date,
'X-Amzn-Authorization: AWS3-HTTPS AWSAccessKeyId='.AWS_ACCESSKEYID.',Algorithm=HMACSHA256,Signature='.$aws_signature,
);
$rawmessage = base64_encode($messageheader. $this->LE.$this->LE.$messagebody);
$requestdata = array(
'Action' => 'SendRawEmail',
'Destinations.member.1' => $this->destinationemail,
'RawMessage.Data' => $rawmessage,
);
$header = '';
foreach ($requestheader as $param) {
$header .= $param.$this->LE;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, AWS_POSTURL);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_HTTPHEADER,$requestheader);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_DNS_USE_GLOBAL_CACHE, TRUE);
curl_setopt($curl, CURLOPT_USERAGENT,NAME." (phpList version ".VERSION.", http://www.phplist.com/)");
curl_setopt($curl, CURLOPT_POST, 1);
$data = '';
foreach ($requestdata as $param => $value) {
$data .= $param.'='.urlencode($value).'&';
}
$data = substr($data,0,-1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($curl);
$status = curl_getinfo($curl,CURLINFO_HTTP_CODE);
if ($status != 200) {
$error = curl_error($curl);
logEvent('Amazon SES status '.$status.' '.strip_tags($res).' '.$error);
}
curl_close($curl);
print('Got remote admin response '.htmlspecialchars($res).'<br/>'); exit();
return $status == 200;
}

You might want to try this class to help you:
http://www.orderingdisorder.com/aws/ses/
I found it to be very easy to use out of the box and provided most normal features.

Related

cURL php Get return 401 with oauth2 after get token

I generate token with OAuth2 authentication. Then, when I execute get to retrieve the data, I got an http code: 401. The function curl_getinfo throws this message.
array(26) {
["url"]=> string(50) "https://endpoint"
["content_type"]=> string(16) "application/json"
["http_code"]=> int(401)
["header_size"]=> int(617)
["request_size"]=> int(176)
["filetime"]=> int(-1)
["ssl_verify_result"]=> int(0)
["redirect_count"]=> int(0)
["total_time"]=> float(0.177855)
["namelookup_time"]=> float(0.02825)
["connect_time"]=> float(0.045129)
["pretransfer_time"]=> float(0.0831)
["size_upload"]=> float(0)
["size_download"]=> float(84)
["speed_download"]=> float(472)
["speed_upload"]=> float(0)
["download_content_length"]=> float(-1)
["upload_content_length"]=> float(0)
["starttransfer_time"]=> float(0.177786)
["redirect_time"]=> float(0)
["redirect_url"]=> string(0) ""
["primary_ip"]=> string(13) "****"
["certinfo"]=> array(0) { }
["primary_port"]=> int(443)
["local_ip"]=> string(13) "*****"
["local_port"]=> int(34886)
}
Failed to retrieve data. Response code: Array
Any idea please for this problem.
This is my code, I got token, then I passed access_token to get data from endpoint. I got token with POST, but the problem is when I want to retrieve data.
<?php
$issued_at = time();
$expires_in = 3600;
$expiration_time = $issued_at + $expires_in;
$current_time = time();
// Token endpoint URL
$token_url = "***/oauth2/token";
// Client ID and secret
$client_id = "****";
$client_secret = "*****";
// Define the POST request to retrieve the token
$post_data = array(
"grant_type" => "client_credentials",
"client_id" => $client_id,
"client_secret" => $client_secret
);
// Initialize cURL
// Make the request to retrieve the token
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $token_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curl);
if ($response === false) {
die(curl_error($curl));
}
// Check the response code
$response_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($response_code != 200) {
die("Failed to retrieve token. Response code: " . $response_code);
}
// Decode the response to retrieve the access token
$response_data = json_decode($response, true);
if (!array_key_exists("access_token", $response_data)) {
die("Failed to retrieve access token");
}
$access_token = $response_data["access_token"];
//var_dump($access_token);
// Close the cURL connection
curl_close($curl);
if ($current_time > $expiration_time) {
// Token has expired
die("Token has expired: " . $access_token );
} else {
// Token is still valid
// Define the GET request URL
$get_url = "endpoint";
// Define the headers for the GET request
$headers = array(
"Authorization: Bearer " . $access_token,
"Content-Type: application/json"
);
// Make the GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $get_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
if ($response === false) {
die(curl_error($ch));
}
// Check the response code
$response_code = curl_getinfo($ch);
//var_dump($response_code);
if ($response_code != 200) {
die("Failed to retrieve data. Response code: " . $response_code);
}
// Decode the response data
$response_data = json_decode($response, true);
// Close the cURL connection
curl_close($ch);
// Output the response data
var_dump($response_data);
}

curl_exec returns false when trying to upload image to Prestashop using PHP

I'm trying to add photo for existing product in my Prestashop 1.7.5.1 shop. I found example code on: https://devdocs.prestashop.com/1.7/development/webservice/tutorials/change_product_image/ and changed it so it has my shop addres and my key. I also changed line
$args['image'] = new CurlFile($image_path, $image_mime); to
$args['image'] = new CurlFile($image_path, $image_mime, '1.jpg');
beacause Visual Studio Code highlighted that CurlFile also needs third argument - postname.
Here is my code:
<?php
define('DEBUG', true);
$url = 'http://test.my_shop.com';
$key = 'MY_AUTH_KEY';
$psProductId = '2364';
$urlImage = $url.'/api/images/products/'.$psProductId.'/';
$image_path = '/img/1.jpg';
$image_mime = 'image/jpg';
$args['image'] = new CurlFile($image_path, $image_mime, '1.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_URL, $urlImage);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $key.':');
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
print("<pre>");
echo '<br>curl_exec <br>';
$data_exec = curl_exec($ch);
var_dump($data_exec);
echo '<br>curl_getinfo <br>';
var_dump(curl_getinfo($ch));
echo '<br>curl_errno <br>';
var_dump(curl_error($ch));
echo '<br>curl_error <br>';
var_dump(curl_error($ch));
print("</pre>");
curl_close($ch);
?>
I placed all those var_dumps because I wanted to gather as much info as possible. When I run this code in my browser using XAMPP i get following output:
curl_exec
bool(false)
curl_getinfo
array(37) {
["url"]=>
string(48) "http://test.my_shop.com/api/images/products/2364/"
["content_type"]=>
NULL
["http_code"]=>
int(0)
["header_size"]=>
int(0)
["request_size"]=>
int(0)
["filetime"]=>
int(-1)
["ssl_verify_result"]=>
int(0)
["redirect_count"]=>
int(0)
["total_time"]=>
float(0.032204)
["namelookup_time"]=>
float(0.001465)
["connect_time"]=>
float(0.031879)
["pretransfer_time"]=>
float(0)
["size_upload"]=>
float(0)
["size_download"]=>
float(0)
["speed_download"]=>
float(0)
["speed_upload"]=>
float(0)
["download_content_length"]=>
float(-1)
["upload_content_length"]=>
float(-1)
["starttransfer_time"]=>
float(0)
["redirect_time"]=>
float(0)
["redirect_url"]=>
string(0) ""
["primary_ip"]=>
string(15) "123.123.123.123"
["certinfo"]=>
array(0) {
}
["primary_port"]=>
int(80)
["local_ip"]=>
string(13) "192.168.0.106"
["local_port"]=>
int(13956)
["http_version"]=>
int(0)
["protocol"]=>
int(1)
["ssl_verifyresult"]=>
int(0)
["scheme"]=>
string(4) "HTTP"
["appconnect_time_us"]=>
int(0)
["connect_time_us"]=>
int(31879)
["namelookup_time_us"]=>
int(1465)
["pretransfer_time_us"]=>
int(0)
["redirect_time_us"]=>
int(0)
["starttransfer_time_us"]=>
int(0)
["total_time_us"]=>
int(32204)
}
curl_errno
string(0) ""
curl_error
string(0) ""
I have no idea what I'm doing wrong. I don't know why code posted on documentation page is not working dor me. If someone has any suggestion please post them, thanks.
I corrected first var_dump(curl_error($ch)); in my code and replaced it with var_dump(curl_errno($ch));. After i ran the code I got error no. 26
curl_errno
int(26)
I looked it up and found this answer: curl: (26) couldn't open file. I changed relative path to full path and now my code is fully working, photos are uploaded correctly. Here is my corrected code:
<?php
define('DEBUG', true);
$url = 'http://test.my_shop.com';
$key = 'MY_AUTH_KEY';
$psProductId = '2364';
$urlImage = $url.'/api/images/products/'.$psProductId.'/';
$image_path = 'C:/xampp/htdocs/my_folder/img/1.jpg';
$image_mime = 'image/jpg';
$args['image'] = new CurlFile($image_path, $image_mime, '1.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_URL, $urlImage);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $key.':');
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
print("<pre>");
echo '<br>curl_exec <br>';
$data_exec = curl_exec($ch);
var_dump($data_exec);
echo '<br>curl_getinfo <br>';
var_dump(curl_getinfo($ch));
echo '<br>curl_errno <br>';
var_dump(curl_errno($ch));
echo '<br>curl_error <br>';
var_dump(curl_error($ch));
print("</pre>");
curl_close($ch);
?>

PHP Can't get https content

I was working on using an api in php.
This is what I got for so far:
$keybotlink = file_get_contents('https://steamgaug.es/api/v2');
echo $keybotlink;
(Not much :D), Anyways, if I try to run this, The page is empty.
If I try to do
$w = stream_get_wrappers();
echo 'openssl: ', extension_loaded ('openssl') ? 'yes':'no', "\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "\n";
echo 'wrappers: ', var_dump($w);
This is the output:
openssl: yes
http wrapper: yes
https wrapper: yes
wrappers: array(22)
{ [0]=> string(13) "compress.zlib"
[1]=> string(4) "dict"
[2]=> string(3) "ftp"
[3]=> string(4) "ftps"
[4]=> string(6) "gopher"
[5]=> string(4) "http"
[6]=> string(5) "https"
[7]=> string(4) "imap"
[8]=> string(5) "imaps"
[9]=> string(4) "pop3"
[10]=> string(5) "pop3s"
[11]=> string(4) "rtsp"
[12]=> string(4) "smtp"
[13]=> string(5) "smtps"
[14]=> string(6) "telnet"
[15]=> string(4) "tftp"
[16]=> string(3) "php"
[17]=> string(4) "file"
[18]=> string(4) "glob"
[19]=> string(4) "data"
[20]=> string(3) "zip"
[21]=> string(4) "phar"
}
Thanks, Me
To allow https wrapper php_openssl extension mustbe enabled and allow_url_fopen must be set to on.
Add below lines in php.ini file if it does not exist:
extension=php_openssl.dll
allow_url_fopen = On
You can also use curl for this:
function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
if($result === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
curl_close($ch);
return $result;
}
print_r( json_decode( getData('https://steamgaug.es/api/v2') ) );
For download content from HTTPS sites use folowing code:
<?php
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://steamgaug.es/api/v2");
curl_setopt($ch, CURLOPT_HEADER, 0);
// if you want to connet to https page you can skip SSL verification by setting CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST to 0
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0 );
// if you want to fetch result to a variable use CURLOPT_RETURNTRANSFER
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// grab URL and pass it to the $output variable
$output = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
echo $output;
CURL is very good and full of options tool to working with HTTP(S) requests.

Authenticate with login.microsoftonline.com through PHP cURL (SSL connect error)

I am trying to extract data from a Micorosft Dynamics CRM 2015 with PHP. From various sources i learned that i had to start with an authentication with login.microsoftonline.com.
I am sending an XML request using cURL that results in a SSL connect error.
The XML request:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
<a:MessageID>urn:uuid:4e586759-a5cc-483c-bbd0-9f3eed7667dc</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo4TBVw9fIMZFmc7ZFxBXIcYAAAAAbd1LF/fnfUOzaja8sGev0GKsBdINtR5Jt13WPsZ9dPgACQAA</VsDebuggerCausalityData>
<a:To s:mustUnderstand="1">https://login.microsoftonline.com/RST2.srf</a:To>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="_0">
<u:Created>2015-06-11T17:14:09.00Z</u:Created>
<u:Expires>2015-06-12T17:14:09.00Z</u:Expires>
</u:Timestamp>
<o:UsernameToken u:Id="uuid-14bed392-2320-44ae-859d-fa4ec83df57f-4">
<o:Username>{username}</o:Username>
<o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">{password}</o:Password>
</o:UsernameToken>
</o:Security>
</s:Header>
<s:Body>
<t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<a:EndpointReference>
<a:Address>urn:crmemea:dynamics.com</a:Address>
</a:EndpointReference>
</wsp:AppliesTo>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
</t:RequestSecurityToken>
</s:Body>
The cURL setup:
$headers = array(
"POST " . $postUrl . " HTTP/1.1",
"Host: " . $hostname,
'Connection: Keep-Alive',
"Content-type: application/soap+xml; charset=UTF-8",
"Content-length: " . strlen($content),
);
$cURLHandle = curl_init();
$soapUrl = "https://login.microsoftonline.com/RST2.srf";
curl_setopt($cURLHandle, CURLOPT_URL, $soapUrl);
curl_setopt($cURLHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cURLHandle, CURLOPT_TIMEOUT, 60);
curl_setopt($cURLHandle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURLHandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($cURLHandle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($cURLHandle, CURLOPT_POST, 1);
curl_setopt($cURLHandle, CURLOPT_POSTFIELDS, $content);
curl_setopt($cURLHandle, CURLOPT_SSLVERSION , 3);
curl_setopt($cURLHandle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($cURLHandle, CURLINFO_HEADER_OUT, false);
$fp = fopen('error.txt', 'w');
curl_setopt($cURLHandle, CURLOPT_STDERR, $fp);
curl_setopt($cURLHandle, CURLOPT_VERBOSE, true);
$response = curl_exec($cURLHandle);
headers:
array(5) {
[0]=>
string(23) "POST /RST2.srf HTTP/1.1"
[1]=>
string(31) "Host: login.microsoftonline.com"
[2]=>
string(22) "Connection: Keep-Alive"
[3]=>
string(49) "Content-type: application/soap+xml; charset=UTF-8"
[4]=>
string(20) "Content-length: 3083"
}
curl_error: string(17) "SSL connect error"
Verbose Error info:
About to connect() to login.microsoftonline.com port 443 (#0)
Trying 23.97.148.36... * connected
Connected to login.microsoftonline.com (23.97.148.36) port 443 (#0)
warning: ignoring value of ssl.verifyhost
NSS error -5961
Closing connection #0
SSL connect error
cURL version info:
array(9) {
["version_number"]=>
int(463623)
["age"]=>
int(3)
["features"]=>
int(1597)
["ssl_version_number"]=>
int(0)
["version"]=>
string(6) "7.19.7"
["host"]=>
string(23) "x86_64-redhat-linux-gnu"
["ssl_version"]=>
string(22) "NSS/3.16.2.3 Basic ECC"
["libz_version"]=>
string(5) "1.2.3"
["protocols"]=>
array(12) {
[0]=>
string(4) "tftp"
[1]=>
string(3) "ftp"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(5) "ldaps"
[6]=>
string(4) "http"
[7]=>
string(4) "file"
[8]=>
string(5) "https"
[9]=>
string(4) "ftps"
[10]=>
string(3) "scp"
[11]=>
string(4) "sftp"
}
}
If i need to provide more please let me know any help would be appreciated!
Any information about NSS error -5961 would be helpfull to i guess.
I suspect it might be an issue with your POST and Host values. Your successfully connecting to login.microsoftonline.com however the next step I believe is your organisation.
I haven't played around with this stuff for a while however the values I have look like so:-
POST /Organization.svc
Host yourorganisation.api.crm5.dynamics.com
Obviously you need to change the "yourorganisation" part and the "crm5" to match your region.
I did a connection a few years ago that as far as I know still works.
http://crmtroubleshoot.blogspot.com.au/2013/07/dynamics-crm-2011-php-and-soap-using.html

How to return this XML-RPC response in an array using PHP?

I'm trying to put together a WordPress plugin and I want to grab a list of all categories (of other WordPress blogs) via XML-RPC. I have the following code and it looks like it works so far:
function get_categories($rpcurl,$username,$password){
$rpcurl2 = $rpcurl."/xmlrpc.php";
$params = array(0,$username,$password,true);
$request = xmlrpc_encode_request('metaWeblog.getCategories',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rpcurl2);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$results = curl_exec($ch);
$res = xmlrpc_decode($results);
curl_close($ch);
return $res;
}
If I use $res I get the following string as the response: Array
If I use $results then I get:
categoryId17 parentId0 descriptionTest categoryDescription categoryNameTest
htmlUrlhttp://test.yoursite.com/?cat=17 rssUrlhttp://test.yoursite.com/?feed=rss2&cat=17
categoryId1 parentId0 descriptionUncategorized categoryDescription
categoryNameUncategorized htmlUrlhttp://test.yoursite.com/?cat=1
rssUrlhttp://test.yoursite.com/?feed=rss2&cat=1
I need to pull out the names after description so Uncategorized and Test in this case.
It's my first time coding in PHP. I got these results by echoing them to the page, so not sure if they get changed in that process or not...
By the way I modified the above code from one that posts to a WordPress blog remotely so maybe I haven't set some of the options correctly?
With var_dump($res) I get:
array(2) { [0]=> array(7) { ["categoryId"]=> string(2) "17" ["parentId"]=> string(1)
"0" ["description"]=> string(4) "Test" ["categoryDescription"]=> string(0) ""
["categoryName"]=> string(4) "Test" ["htmlUrl"]=> string(40)
"http://test.youreventwebsite.com/?cat=17" ["rssUrl"]=> string(54)
"http://test.youreventwebsite.com/?feed=rss2&cat=17" } [1]=> array(7) {
["categoryId"]=> string(1) "1" ["parentId"]=> string(1) "0" ["description"]=>
string(13) "Uncategorized" ["categoryDescription"]=> string(0) "" ["categoryName"]=>
string(13) "Uncategorized" ["htmlUrl"]=> string(39) "http://test.youreventwebsite.com/?cat=1"
["rssUrl"]=> string(53) "http://test.youreventwebsite.com/?feed=rss2&cat=1" } }
You need to iterate your array:
foreach($res as $item) {
echo $item['description'] . $item['categoryName'] . $item['htmlUrl']; //etc...
}

Categories