AMAZON SP-API AWS SIGNATURE The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details
public function getOrdersFromApi(){
// Configuration values
$host = 'sellingpartnerapi-eu.amazon.com';
$accessKey = 'XXXXX';
$secretKey = 'XXXXXX';
$region = 'eu-west-1';
$service = 'execute-api';
/**
* You should modify the script
* for
* 1. full request url
* 2. uri for AWS signature
* 3. request method GET / POST / PUT
* 4. actual data of the request
* and call the above functions
*/
$requestUrl = 'https://sellingpartnerapi-eu.amazon.com/orders/v0/orders?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992';
$uri = '?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992';
$httpRequestMethod = 'GET';
$data = json_encode(array());
$headers = $this->calcualteAwsSignatureAndReturnHeaders($host, $uri, $requestUrl,
$accessKey, $secretKey, $region, $service,
$httpRequestMethod, $data, TRUE);
$result = $this->callToAPI($requestUrl, $httpRequestMethod, $headers, $data, TRUE);
print_r($result);
}
public function calcualteAwsSignatureAndReturnHeaders($host, $uri, $requestUrl,
$accessKey, $secretKey, $region, $service,
$httpRequestMethod, $data, $debug = TRUE){
$terminationString = 'aws4_request';
$algorithm = 'AWS4-HMAC-SHA256';
$phpAlgorithm = 'sha256';
$canonicalURI = $uri;
$canonicalQueryString = '';
$signedHeaders = 'content-type;host;x-amz-date'; $signedHeaders = "content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token";
$currentDateTime = new DateTime('UTC');
$reqDate = $currentDateTime->format('Ymd');
$reqDateTime = $currentDateTime->format('Ymd\THis\Z');
// Create signing key
$kSecret = $secretKey;
$kDate = hash_hmac($phpAlgorithm, $reqDate, 'AWS4' . $kSecret, true);
$kRegion = hash_hmac($phpAlgorithm, $region, $kDate, true);
$kService = hash_hmac($phpAlgorithm, $service, $kRegion, true);
$kSigning = hash_hmac($phpAlgorithm, $terminationString, $kService, true);
// Create canonical headers
$canonicalHeaders = array();
$canonicalHeaders[] = 'content-type:application/json';
$canonicalHeaders[] = 'host:' . $host;
$canonicalHeaders[] = 'x-amz-date:' . $reqDateTime;
$canonicalHeadersStr = implode("\n", $canonicalHeaders);
// Create request payload
$requestHasedPayload = hash($phpAlgorithm, $data);
// Create canonical request
$canonicalRequest = array();
$canonicalRequest[] = $httpRequestMethod;
$canonicalRequest[] = $canonicalURI;
$canonicalRequest[] = $canonicalQueryString;
$canonicalRequest[] = $canonicalHeadersStr . "\n";
$canonicalRequest[] = $signedHeaders;
$canonicalRequest[] = $requestHasedPayload;
$requestCanonicalRequest = implode("\n", $canonicalRequest);
$requestHasedCanonicalRequest = hash($phpAlgorithm, utf8_encode($requestCanonicalRequest));
if($debug){
echo "<h5>Canonical to string</h5>";
echo "<pre>";
echo $requestCanonicalRequest;
echo "</pre>";
}
// Create scope
$credentialScope = array();
$credentialScope[] = $reqDate;
$credentialScope[] = $region;
$credentialScope[] = $service;
$credentialScope[] = $terminationString;
$credentialScopeStr = implode('/', $credentialScope);
// Create string to signing
$stringToSign = array();
$stringToSign[] = $algorithm;
$stringToSign[] = $reqDateTime;
$stringToSign[] = $credentialScopeStr;
$stringToSign[] = $requestHasedCanonicalRequest;
$stringToSignStr = implode("\n", $stringToSign);
if($debug){
echo "<h5>String to Sign</h5>";
echo "<pre>";
echo $stringToSignStr;
echo "</pre>";
}
// Create signature
$signature = hash_hmac($phpAlgorithm, $stringToSignStr, $kSigning);
// Create authorization header
$authorizationHeader = array();
$authorizationHeader[] = 'Credential=' . $accessKey . '/' . $credentialScopeStr;
$authorizationHeader[] = 'SignedHeaders=' . $signedHeaders;
$authorizationHeader[] = 'Signature=' . ($signature);
$authorizationHeaderStr = $algorithm . ' ' . implode(', ', $authorizationHeader);
// Request headers
$headers = array();
$headers[] = 'authorization:'.$authorizationHeaderStr;
$headers[] = 'content-length:'.strlen($data);
$headers[] = 'content-type: application/json';
$headers[] = 'user-agent:sellergeni/1.0 (Php=7.2)';
$headers[] = 'x-amz-access-token:Atza|IwEBII0yZlQvoo95puL9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$headers[] = 'host: ' . $host;
$headers[] = 'x-amz-date: ' . $reqDateTime;
return $headers;
}
public function callToAPI($requestUrl, $httpRequestMethod, $headers, $data, $debug=TRUE)
{
// Execute the call
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $requestUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $httpRequestMethod,
CURLOPT_POSTFIELDS => $data,
CURLOPT_VERBOSE => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HEADER => false,
CURLINFO_HEADER_OUT=>true,
CURLOPT_HTTPHEADER => $headers,
));
$response = curl_exec($curl);
$err = curl_error($curl);
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($debug){
$headers = curl_getinfo($curl, CURLINFO_HEADER_OUT);
echo "<h5>Request</h5>";
echo "<pre>";
echo $headers;
echo "</pre>";
}
curl_close($curl);
if ($err) {
if($debug){
echo "<h5>Error:" . $responseCode . "</h5>";
echo "<pre>";
echo $err;
echo "</pre>";
}
} else {
if($debug){
echo "<h5>Response:" . $responseCode . "</h5>";
echo "<pre>";
echo $response;
echo "</pre>";
}
}
return array(
"responseCode" => $responseCode,
"response" => $response,
"error" => $err
);
}
Response of this code like this
Canonical to string
GET
?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992
content-type:application/json
host:sellingpartnerapi-eu.amazon.com
x-amz-date:20210204T060039Z
content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
String to Sign
AWS4-HMAC-SHA256
20210204T060039Z
20210204/eu-west-1/execute-api/aws4_request
f11a59afb96cf62bbdd17e44405da8c5567178531f839826e89e9b1fcb77a24a
Request
GET /orders/v0/orders?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992 HTTP/1.1
Host: sellingpartnerapi-eu.amazon.com
Accept: */*
authorization:AWS4-HMAC-SHA256 Credential=xxxxxxxxxxxxxx/20210204/eu-west-1/execute-api/aws4_request, SignedHeaders=content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token, Signature=3ddc540c9a1e38ea0466e4d4570a5ea8a1bc7274cfbc2fffd50609c7f379c495
content-length:2
content-type: application/json
user-agent:sellergeni/1.0 (Php=7.2)
x-amz-access-token:Atza|xxxxxxxxxxxxxxxxxxxxxxxxx
x-amz-date: 20210204T060039Z
Response:403
{
"errors": [
{
"message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'GET
/orders/v0/orders
CreatedAfter=2021-01-15T05%3A26%3A31.308992&MarketplaceIds=A21TJRUUN4KGV
content-type:application/json
host:sellingpartnerapi-eu.amazon.com
user-agent:sellergeni/1.0 (Php=7.2)
x-amz-access-token:Atza|IwEBII0yZlQvoo95puL9xxxxxxxxxxxxxxxxxx
x-amz-date:20210204T060039Z
x-amz-security-token:
content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20210204T060039Z
20210204/eu-west-1/execute-api/aws4_request
e995c02098c1a2d5d775380f1fc49804b32af9534b5e330145ca125fe098f0af'
",
"code": "InvalidSignature"
}
]
}
Run:
sign pathparam/resource
Replace:
/messaging/v1/orders/{orderId}
with:
/messaging/v1/orders/xxx-xxxxxxx-xxxxxxx
There is a problem with my paypal Integration in live site.
For 90% of transactions, I didn't get any problem. Some times only I am facing this below problem.
Problem: After successful transaction, I am not getting Pay pal values like Transaction Id, Message etc. All values shows empty. It comes for 10% of transactions only. please tell me what may be the problem. Can't able to find out the reason
Thanks in Advance..
$paypal_email = '5345345345345f';
$cur_dir='http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
$return_url = $cur_dir.'/paymentsucess.php';
$cancel_url = $cur_dir.'/payment-not-sucess.php';
$notify_url = $cur_dir.'/payments.php';
extract($_POST);
$item_name = $exam_name;
$item_amount = $amount;
$userid=$userid;
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
$querystring = "?business=".urlencode($paypal_email)."&";
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
exit();
}else{
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A) (.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['userid'] = $_POST['userid'];
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){
$orderid = updatePayments($data);
if($orderid){
}else{
}
}else{
}
}else if (strcmp ($res, "INVALID") == 0) {
}
}
fclose ($fp);
}
}
This mailer works with go daddy but I cant get it too work with a home server. It will send the mail and shows up in the inbox but not the content. I think it has to do with using $body tag but I am not sure any suggestions?
<?php
// PHPmailer settings
$mail = new PHPMailer(); // create a new object
$mail->Issmtp(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = "email"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->From = $email;
$mail->FromName = $contact_name;
$mail->SetFrom($email, $contact_name);
$mail->AddAddress('email');
$mail->Priority = 1;
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Gray Gables maintenance request";
$mail->Body = $body;
$mail->AltBody = "This is the text-only body";
// gets info from form
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$phone = $_POST['phone'] ;
$message = $_POST['message'] ;
$ip = $_SERVER['REMOTE_ADDR'];
// defines how message looks in email
$mail->Body="
Name: $name<br>
Telephone: $phone<br>
Email: $email<br>
IP address: $ip <br>
-------------------<br>
Message:<br>
$message";
// looks good in your inbox
$mail->From = "$email";
$mail->FromName = "$name";
$mail->AddReplyTo("$email","$name");
// gives success or error
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo '
<meta http-equiv="refresh" content="3;url=http/">
<center><font size="5px">
Message has been sent!!<br>
you will be redirected to our home page in 3 seconds...<br>
click here to return now.
</font>
</center>
';
?>
<?php
echo ' Client IP: ';
if ( isset($_SERVER["REMOTE_ADDR"]) ) {
echo '' . $_SERVER["REMOTE_ADDR"] . ' ';
} else if ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ) {
echo '' . $_SERVER["HTTP_X_FORWARDED_FOR"] . ' ';
} else if ( isset($_SERVER["HTTP_CLIENT_IP"]) ) {
echo '' . $_SERVER["HTTP_CLIENT_IP"] . ' ';
}
?>
I think you are looking for this...
$body = file_get_contents('yourfile.html');
You can attach any HTML content in 'yourfile.html', which displays in your body of the mail.
I am using the below script to allow user to upload images and email it to me. I did received the email but the attachment is not included in the email. It also show the from email as root user instead of the user's email address. please help.
<?php
ob_start();
require("class.phpmailer.php");
$salutation = $_POST['salutation'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$photo = $_FILES['photo'];
isset($_POST['submit']);
$active_keys = array();
foreach($_FILES[$photo]['name'] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
} }
foreach($active_keys as $key)
{ switch(exif_imagetype($_FILES[$photo]['tmp_name'][$key])) {
case IMAGETYPE_JPEG:
case IMAGETYPE_PNG:
break;
default:
echo "{";
echo "error: 'This is no photo..'\n";
echo "}";
exit(0);
} }
$message = "Photo submitted by: $salutation $firstname $lastname. <br>Comments: $comments.<br>terms:$terms.";
$mail = new PHPMailer();
$mail->From = ($email);
$mail->AddAddress('info#domain.com');
$mail->Subject = "Submitted Photos";
$mail->Body = $message;
$mail->WordWrap = 50;
foreach($FILES['photo']['tmp_name'] as $photo) {
if(!empty($photo)) {
$mail->AddAttachment($photo);
}}
$mail->Send();
header("Location: thankyou.php");
exit();
?>
change
foreach($FILES['photo']['tmp_name'] as $photo) {
to
foreach($_FILES['photo']['tmp_name'] as $photo)
This is the code of my export_to_excel helper:
function export_to_excel($query, $filename='exceloutput')
{
$headers = ''; // just creating the var for field headers to append to below
$data = ''; // just creating the var for field data to append to below
$obj =& get_instance();
$fields = $query->list_fields();
if ($query->num_rows() == 0) {
echo '<p>The table appears to have no data.</p>';
} else {
foreach ($fields as $field) {
$headers .= $field . "\t";
}
foreach ($query->result() as $row) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r","",$data);
header("Content-type: application/x-msexcel; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename.xls");
echo "$headers\n$data";
}
}
I get different results in localhost and on server. When I run the code in localhost, it outputs the proper result with no problem, but when I run the code on server, it gives the same result as in localhost, but it adds two more lines (excel rows) containing error as follows:
<br />
<b>Fatal error</b>: ob_start()
[< a href='ref.outcontrol'> ref.outcontrol</a>]:
Cannot use output buffering in output buffering display handlers in
<b>/home/username/public_html/Codeigniter_website/system/core/Exceptions.php</b>
on line <b>181</b><br />
Any solutions?
It's almost a large project and it's the only difference that I have seen between local and server.
The solution is to make sure output and parsing stops after the desired output.
The can be done by putting exit; after echo "$headers\n$data";