Why isn't my Azure SAS Token Signature matching? - php

This is the error returned when I try to access a blob in storage:
Code: AuthenticationFailed
Message: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
AuthenticationErrorDetail: Signature did not match. String to sign used was xxstorageaccount rwdlac b sco 2017-08-17T21:29:24Z 2017-08-17T21:34:24Z https 2017-04-17
Here's my code:
$storageAccount = config('azure.storage.account');
$start = new \DateTime();
$end = (new \DateTime())->modify('+5 minutes');
$start = $start->format('Y-m-d\TH:i:s\Z');
$end = $end->format('Y-m-d\TH:i:s\Z');
$toSign = $storageAccount . "\n";
$toSign .= "rwdlac" . "\n";
$toSign .= "b" . "\n";
$toSign .= "sco" . "\n";
$toSign .= $start . "\n";
$toSign .= $end . "\n";
$toSign .= "\n";
$toSign .= "https" . "\n";
$toSign .= "2017-04-17" . "\n";
$signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, $sasKeyValue, TRUE)));
$token = "?sv=2017-04-17&ss=b&srt=sco&sp=rwdlac&se=" . $end . "&st=" . $start . "&spr=https&sig=" . $signature;
return $uri . $token;

You could do 2 things to avoid this error.
Convert start and end time to GMT time via setTimezone() function or consider using the gmdate function instead.
Decode base64 account key through base64_decode() function.
Please change your code like the following:
$storageAccount = config('azure.storage.account');
$start = (new \DateTime())->setTimezone(new DateTimeZone('GMT'));
$end = (new \DateTime())->setTimezone(new DateTimeZone('GMT'))->modify('+5 minutes');
$start = $start->format('Y-m-d\TH:i:s\Z');
$end = $end->format('Y-m-d\TH:i:s\Z');
$toSign = $storageAccount . "\n";
$toSign .= "rwdlac" . "\n";
$toSign .= "b" . "\n";
$toSign .= "sco" . "\n";
$toSign .= $start . "\n";
$toSign .= $end . "\n";
$toSign .= "\n";
$toSign .= "https" . "\n";
$toSign .= "2017-04-17" . "\n";
$signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, base64_decode($sasKeyValue), TRUE)));
$token = "?sv=2017-04-17&ss=b&srt=sco&sp=rwdlac&se=" . $end . "&st=" . $start . "&spr=https&sig=" . $signature;
return $uri . $token;

Related

AWS signature version 4 parsing issue

I am working on aws signature version 4. Now my concern is that I receive signature from api request at Amazon api gateway and gateway auhorize and authenticate the request and forward to php microservice. Now I want to detect user from signature that is in request headers. How I can resolve this issue.
Below is my working code through I generate aws signature
public function generateAWSToken($uid) {
try {
$method = 'GET';
$uri = '/dev';
$json = file_get_contents('php://input');
$obj = json_decode($json);
if (isset($obj->method)) {
$m = explode("|", $obj->method);
$method = $m[0];
$uri .= $m[1];
}
$secretKey = env('AWS_SECRET_ACCESS_KEY');
$access_key = env('AKIAJR2JSY655JXI5LIA');
$token = env('AWS_SECRET_ACCESS_KEY');
$region = env('AWS_DEFAULT_REGIO');
$service = 'execute-api';
$options = array();
$headers = array();
$host = "YOUR-API-HOST.execute-api.ap-southeast-1.amazonaws.com";
//Or you can define your host here.. I am using API gateway.
$alg = 'sha256';
$date = new \DateTime('UTC');
$dd = $date->format('Ymd\THis\Z');
$amzdate2 = new \DateTime('UTC');
$amzdate2 = $amzdate2->format('Ymd');
$amzdate = $dd;
$algorithm = 'AWS4-HMAC-SHA256';
// $parameters = (array) $obj->data;
if (isset($obj->data) && ($obj->data == null || empty($obj->data))) {
$obj->data = "";
} else {
$param = "";
// $param = json_encode($obj->data);
// if ($param == "{}") {
// $param = "";
// }
$requestPayload = strtolower($param);
$hashedPayload = hash($alg, $uid);
$canonical_uri = $uri;
$canonical_querystring = '';
$canonical_headers = "content-type:" . "application/json" . "\n" . "host:" . $host . "\n" . "x-amz-date:" . $amzdate . "\n" . "x-amz-security-token:" . $token . "\n";
$signed_headers = 'content-type;host;x-amz-date;x-amz-security-token';
$canonical_request = "" . $method . "\n" . $canonical_uri . "\n" . $canonical_querystring . "\n" . $canonical_headers . "\n" . $signed_headers . "\n" . $hashedPayload;
$credential_scope = $amzdate2 . '/' . $region . '/' . $service . '/' . 'aws4_request';
$string_to_sign = "" . $algorithm . "\n" . $amzdate . "\n" . $credential_scope . "\n" . hash('sha256', $canonical_request) . "";
//string_to_sign is the answer..hash('sha256', $canonical_request)//
$kSecret = 'AWS4' . $secretKey;
$kDate = hash_hmac($alg, $amzdate2, $kSecret, true);
$kRegion = hash_hmac($alg, $region, $kDate, true);
$kService = hash_hmac($alg, $service, $kRegion, true);
$kSigning = hash_hmac($alg, 'aws4_request', $kService, true);
$signature = hash_hmac($alg, $string_to_sign, $kSigning);
$authorization_header = $algorithm . ' ' . 'Credential=' . $access_key . '/' . $credential_scope . ', ' . 'SignedHeaders=' . $signed_headers . ', ' . 'Signature=' . $signature;
$headers = [
'content-type' => 'application/json',
'x-amz-security-token' => $token,
'x-amz-date' => $amzdate,
'Authorization' => $authorization_header];
return $signature;
}
} catch (\Exception $ex) {
return false;
}
}
Suggest any usefull link and method.
How are you generating the AKS+AKI+token? If you are using Cognito pools & identity federation, this should be helpful. This helped me
how to user identity id to link to cognito user pool
PS: this might be a copy-paste error but surely the token is not $token = env('AWS_SECRET_ACCESS_KEY');

Create WSDL File For SoapServer EndPoint PHP File

i wanna create wsdl file for my php end point.
this is my php end point class with two function:
class server{
private $UserIdSender;
private $UserIdReciver;
private $Title;
private $Body;
private $BoardId;
private $obj_ticket;
private $obj_ticket_owner;
private $ticket_id;
public function __construct() {
date_default_timezone_set("Asia/Tehran");
require_once "../../diba-modules/conf.php";
require_once "../../diba-modules/functions.php";
require_once "../../diba-include/entities/ticket.php";
require_once "../../diba-include/entities/ticket_owner.php";
$this->obj_ticket = new \entities\ticket(TRUE);
$this->obj_ticket_owner = new \entities\ticket_owner(TRUE);
mb_internal_encoding("UTF-8");
}
/*public board = 17*/
public function SaveTicketFromPortal($Token,$NationalCodeSender , $NationalCodeReciver , $Title , $Body = "" , $BoardId = 17 ){
$this->UserIdSender = get_id_from_national_code($NationalCodeSender);
$this->UserIdReciver = get_id_from_national_code($NationalCodeReciver);
$this->Title = trim(filter_var($Title,FILTER_SANITIZE_STRING));
$this->Body = trim(filter_var($Body,FILTER_SANITIZE_STRING));
$this->BoardId = filter_var($BoardId,FILTER_SANITIZE_NUMBER_INT);
if($this->UserIdSender <= 0 ){
return array("Success" => "-1" , "Message" => "Sender NationalCode Not Found !" );
}elseif($this->UserIdReciver <= 0 ){
return array("Success" => "-1" , "Message" => "Reciver NationalCode Not Found !" );
} elseif(mb_strlen($this->Title)>500){
return array("Success" => "-1" , "Message" => "OverFlow in Ticket Title Variable! Type Of Variable Is String(500) " );
}elseif(mb_strlen($this->Body)>3000){
return array("Success" => "-1" , "Message" => "OverFlow in Ticket Body Variable! Type Of Variable Is String(3000) " );
}elseif(!is_numeric($this->BoardId) ){
return array("Success" => "-1" , "Message" => "BoardId Should Be Number!" );
}else{
$this->ticket_id = $this->obj_ticket->save(NULL, $this->Title, $this->Body, $this->UserIdSender , date("Y-m-d H:i:s"), "" , 3 , 0 , $this->BoardId);
$this->obj_ticket_owner->save(NULL, $this->ticket_id, $this->UserIdReciver, date("Y-m-d H:i:s"), 3, 0, 1);
if($this->obj_ticket->flage && $this->obj_ticket_owner->flage){
$this->obj_ticket->commit(TRUE);
$this->obj_ticket_owner->commit(TRUE);
$boardname = get_board_name($this->BoardId);
$robot_msg = "\xF0\x9F\x93\xA2 Your Ticket Has Been Successfuly Refrenced From Portal. \n\x23\xE2\x83\xA3 $this->ticket_id \n\xF0\x9F\x93\x8B Board $boardname";
send_with_telegram($this->UserIdReciver, $robot_msg,$this->UserIdSender);
return array("Success" => "1" , "Message" => "Your Ticket Has Been Successfuly Refrenced." );
}else{
$this->obj_ticket->commit(FALSE);
$this->obj_ticket_owner->commit(FALSE);
return array("Success" => "-1" , "Message" => "Error In Ticket Referrals!" );
}
}
}
public function SaveTicketFromPortalResponse($Token){
}
}
$params=array("uri"=>"http://127.0.0.1/board/my-webservice/portal/server.php");
$server = new SoapServer(NULL,$params);
$server->setClass("server");
$server->handle();
when i use address "server.php?wsdl" for call my Soap Function from asp.net i recive a error like this :
WSDL generation is no supported yet.!
please help.
its emergency.
thanks a lot.
i found it =>
wsdl.php
<?php
$functions = array();
$serviceName = "My Webservice For Recive Data From Portal";
$functions[] = array("funcName" => "SaveTicketFromPortal",
"doc" => "My Webservice For Recive Data From Portal",
"inputParams" => array(array("name" => "Token", "type" => "string"),
array("name" => "NationalCodeSender", "type" => "string"),
array("name" => "NationalCodeReciver", "type" => "string"),
array("name" => "Title", "type" => "string"),
array("name" => "Body", "type" => "string")
),
"outputParams" => array(array("name" => "Success", "type" => "string"),
array("name" => "Message" ,"type" => "string" )),
"soapAddress" => "http://192.168.10.16/board/my-webservice/portal/server.php"
);
$functions[] = array("funcName" => "SetState",
"doc" => "To Change Ticket State From Todo To Doing And Done",
"inputParams" => array(array("name" => "Token", "type" => "string"),
array("name" => "TicketId", "type" => "string"),
array("name" => "NationalCode", "type" => "string"),
array("name" => "StateId", "type" => "string")),
"outputParams" => array(array("name" => "Success", "type" => "string"),
array("name" => "Message" ,"type" => "string" )),
"soapAddress" => "http://192.168.10.16/board/my-webservice/portal/server.php"
);
if (stristr($_SERVER['QUERY_STRING'], "wsdl")) {
// WSDL request - output raw XML
header("Content-Type: application/soap+xml; charset=utf-8");
echo DisplayXML();
} else {
// Page accessed normally - output documentation
$cp = substr($_SERVER["SCRIPT_NAME"], strrpos($_SERVER["SCRIPT_NAME"], "/") + 1); // Current page
echo '<!-- Attention: To access via a SOAP client use ' . $cp . '?WSDL -->';
echo '<html>';
echo '<head><title>' . $serviceName . '</title></head>';
echo '<body>';
echo '<h1>' . $serviceName . '</h1>';
echo '<p style="margin-left:20px;">To access via a SOAP client use <code>' . $cp . '?WSDL</code></p>';
// Document each function
echo '<h2>Available Functions:</h2>';
echo '<div style="margin-left:20px;">';
for ($i=0;$i<count($functions);$i++) {
echo '<h3>Function: ' . $functions[$i]['funcName'] . '</h3>';
echo '<div style="margin-left:20px;">';
echo '<p>';
echo $functions[$i]['doc'];
echo '<ul>';
if (array_key_exists("inputParams", $functions[$i])) {
echo '<li>Input Parameters:<ul>';
for ($j=0;$j<count($functions[$i]['inputParams']);$j++) {
echo '<li>' . $functions[$i]['inputParams'][$j]['name'];
echo ' (' . $functions[$i]['inputParams'][$j]['type'];
echo ')</li>';
}
echo '</ul></li>';
}
if (array_key_exists("outputParams", $functions[$i])) {
echo '<li>Output Parameters:<ul>';
for ($j=0;$j<count($functions[$i]['outputParams']);$j++) {
echo '<li>' . $functions[$i]['outputParams'][$j]['name'];
echo ' (' . $functions[$i]['outputParams'][$j]['type'];
echo ')</li>';
}
echo '</ul></li>';
}
echo '</ul>';
echo '</p>';
echo '</div>';
}
echo '</div>';
echo '<h2>WSDL output:</h2>';
echo '<pre style="margin-left:20px;width:800px;overflow-x:scroll;border:1px solid black;padding:10px;background-color:#D3D3D3;">';
echo DisplayXML(false);
echo '</pre>';
echo '</body></html>';
}
exit;
/*****************************************************************************
* Create WSDL XML
* #PARAM xmlformat=true - Display output in HTML friendly format if set false
*****************************************************************************/
function DisplayXML($xmlformat=true) {
global $functions; // Functions that this web service supports
global $serviceName; // Web Service ID
$i = 0; // For traversing functions array
$j = 0; // For traversing parameters arrays
$str = ''; // XML String to output
// Tab spacings
$t1 = ' ';
if (!$xmlformat) $t1 = ' ';
$t2 = $t1 . $t1;
$t3 = $t2 . $t1;
$t4 = $t3 . $t1;
$t5 = $t4 . $t1;
$serviceID = str_replace(" ", "", $serviceName);
// Declare XML format
$str .= '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n\n";
// Declare definitions / namespaces
$str .= '<wsdl:definitions ' . "\n";
$str .= $t1 . 'xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" ' . "\n";
$str .= $t1 . 'xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" ' . "\n";
$str .= $t1 . 'xmlns:s="http://www.w3.org/2001/XMLSchema" ' . "\n";
$str .= $t1 . 'targetNamespace="http://www.darkerwhite.com/" ' . "\n";
$str .= $t1 . 'xmlns:tns="http://www.darkerwhite.com/" ' . "\n";
$str .= $t1 . 'name="' . $serviceID . '" ' . "\n";
$str .= '>' . "\n\n";
// Declare Types / Schema
$str .= '<wsdl:types>' . "\n";
$str .= $t1 . '<s:schema elementFormDefault="qualified" targetNamespace="http://www.darkerwhite.com/">' . "\n";
for ($i=0;$i<count($functions);$i++) {
// Define Request Types
if (array_key_exists("inputParams", $functions[$i])) {
$str .= $t2 . '<s:element name="' . $functions[$i]['funcName'] . 'Request">' . "\n";
$str .= $t3 . '<s:complexType><s:sequence>' . "\n";
for ($j=0;$j<count($functions[$i]['inputParams']);$j++) {
$str .= $t4 . '<s:element minOccurs="1" maxOccurs="1" ';
$str .= 'name="' . $functions[$i]['inputParams'][$j]['name'] . '" ';
$str .= 'type="s:' . $functions[$i]['inputParams'][$j]['type'] . '" />' . "\n";
}
$str .= $t3 . '</s:sequence></s:complexType>' . "\n";
$str .= $t2 . '</s:element>' . "\n";
}
// Define Response Types
if (array_key_exists("outputParams", $functions[$i])) {
$str .= $t2 . '<s:element name="' . $functions[$i]['funcName'] . 'Response">' . "\n";
$str .= $t3 . '<s:complexType><s:sequence>' . "\n";
for ($j=0;$j<count($functions[$i]['outputParams']);$j++) {
$str .= $t4 . '<s:element minOccurs="1" maxOccurs="1" ';
$str .= 'name="' . $functions[$i]['outputParams'][$j]['name'] . '" ';
$str .= 'type="s:' . $functions[$i]['outputParams'][$j]['type'] . '" />' . "\n";
}
$str .= $t3 . '</s:sequence></s:complexType>' . "\n";
$str .= $t2 . '</s:element>' . "\n";
}
}
$str .= $t1 . '</s:schema>' . "\n";
$str .= '</wsdl:types>' . "\n\n";
// Declare Messages
for ($i=0;$i<count($functions);$i++) {
// Define Request Messages
if (array_key_exists("inputParams", $functions[$i])) {
$str .= '<wsdl:message name="' . $functions[$i]['funcName'] . 'Request">' . "\n";
$str .= $t1 . '<wsdl:part name="parameters" element="tns:' . $functions[$i]['funcName'] . 'Request" />' . "\n";
$str .= '</wsdl:message>' . "\n";
}
// Define Response Messages
if (array_key_exists("outputParams", $functions[$i])) {
$str .= '<wsdl:message name="' . $functions[$i]['funcName'] . 'Response">' . "\n";
$str .= $t1 . '<wsdl:part name="parameters" element="tns:' . $functions[$i]['funcName'] . 'Response" />' . "\n";
$str .= '</wsdl:message>' . "\n\n";
}
}
// Declare Port Types
for ($i=0;$i<count($functions);$i++) {
$str .= '<wsdl:portType name="' . $functions[$i]['funcName'] . 'PortType">' . "\n";
$str .= $t1 . '<wsdl:operation name="' . $functions[$i]['funcName'] . '">' . "\n";
if (array_key_exists("inputParams", $functions[$i]))
$str .= $t2 . '<wsdl:input message="tns:' . $functions[$i]['funcName'] . 'Request" />' . "\n";
if (array_key_exists("outputParams", $functions[$i]))
$str .= $t2 . '<wsdl:output message="tns:' . $functions[$i]['funcName'] . 'Response" />' . "\n";
$str .= $t1 . '</wsdl:operation>' . "\n";
$str .= '</wsdl:portType>' . "\n\n";
}
// Declare Bindings
for ($i=0;$i<count($functions);$i++) {
$str .= '<wsdl:binding name="' . $functions[$i]['funcName'] . 'Binding" type="tns:' . $functions[$i]['funcName'] . 'PortType">' . "\n";
$str .= $t1 . '<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />' . "\n";
$str .= $t1 . '<wsdl:operation name="' . $functions[$i]['funcName'] . '">' . "\n";
$str .= $t2 . '<soap:operation soapAction="' . $functions[$i]['soapAddress'] . '#' . $functions[$i]['funcName'] . '" style="document" />' . "\n";
if (array_key_exists("inputParams", $functions[$i]))
$str .= $t2 . '<wsdl:input><soap:body use="literal" /></wsdl:input>' . "\n";
if (array_key_exists("outputParams", $functions[$i]))
$str .= $t2 . '<wsdl:output><soap:body use="literal" /></wsdl:output>' . "\n";
$str .= $t2 . '<wsdl:documentation>' . $functions[$i]['doc'] . '</wsdl:documentation>' . "\n";
$str .= $t1 . '</wsdl:operation>' . "\n";
$str .= '</wsdl:binding>' . "\n\n";
}
// Declare Service
$str .= '<wsdl:service name="' . $serviceID . '">' . "\n";
for ($i=0;$i<count($functions);$i++) {
$str .= $t1 . '<wsdl:port name="' . $functions[$i]['funcName'] . 'Port" binding="tns:' . $functions[$i]['funcName'] . 'Binding">' . "\n";
$str .= $t2 . '<soap:address location="' . $functions[$i]['soapAddress'] . '" />' . "\n";
$str .= $t1 . '</wsdl:port>' . "\n";
}
$str .= '</wsdl:service>' . "\n\n";
// End Document
$str .= '</wsdl:definitions>' . "\n";
if (!$xmlformat) $str = str_replace("<", "<", $str);
if (!$xmlformat) $str = str_replace(">", ">", $str);
if (!$xmlformat) $str = str_replace("\n", "<br />", $str);
return $str;
}
?>

Authorize.Net Simple Chekout method on XML after ARB process

How can I add the 2nd time Direct Post method after payment is getting succeeded on Authorized Dot Net ARB. Let me elaborate
Suppose an user will subscribe for membership and the website will ask for donation too. After payment of Membership on ARB(XML version) how may I pay again for donation one time through Authorized dot net. I tried to use ARB and got duplicate entry error. Let me paste the code here for more details.
ARB Code I used
$SubscrName = $FirstName." ".$LastName;
$length = 12;
$unit = "months";
$totatltenure = $CardExpYear-date("Y");
$start_date = date("Y-m-d");
$totalOccurrences = 1*$totatltenure;
$trialOccurrences = 0;
$trialAmount = 0;
$expirationDate = $CardExpYear."-".$CardExpMonth;
$content =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<ARBCreateSubscriptionRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">" .
"<merchantAuthentication>".
"<name>" . $loginname . "</name>".
"<transactionKey>" . $transactionkey . "</transactionKey>".
"</merchantAuthentication>".
"<refId>" . $refId . "</refId>".
"<subscription>".
"<name>" . $SubscrName . "</name>".
"<paymentSchedule>".
"<interval>".
"<length>". $length ."</length>".
"<unit>". $unit ."</unit>".
"</interval>".
"<startDate>" . $start_date . "</startDate>".
"<totalOccurrences>". $totalOccurrences . "</totalOccurrences>".
"<trialOccurrences>". $trialOccurrences . "</trialOccurrences>".
"</paymentSchedule>".
"<amount>". $TotalCosting ."</amount>".
"<trialAmount>" . $trialAmount . "</trialAmount>".
"<payment>".
"<creditCard>".
"<cardNumber>" . $CardNumber . "</cardNumber>".
"<expirationDate>" . $expirationDate . "</expirationDate>".
"<cardCode>".$CVV_Code."</cardCode>".
"</creditCard>".
"</payment>".
"<billTo>".
"<firstName>". $CardFirstName . "</firstName>".
"<lastName>" . $CardLastName . "</lastName>".
"<address>" . $CardStreet . "</address>".
"<city>" . $CardCity . "</city>".
"<state>" . $CardState . "</state>".
"<zip>" . $CardZip . "</zip>".
"</billTo>".
"</subscription>".
"</ARBCreateSubscriptionRequest>";
$response = send_request_via_curl($host,$path,$content);
if ($response)
{
list ($refId, $resultCode, $code, $text, $subscription_id) =parse_return($response);
if($resultCode == "Ok")
{
if($_SESSION['willdonate'] == 'donated' && $_SESSION['donateammount'] != '')
{
$SubscrName = $FirstName." ".$LastName;
$length = 2;
$unit = "months";
$totatltenure = 1;
$start_date = date("Y-m-d");
$totalOccurrences = 1;
$trialOccurrences = 0;
$trialAmount = 0;
$expirationDate = date("Y-m");
$TotalCosting = $_SESSION['donateammount'];
$contentDonation =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<ARBCreateSubscriptionRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">" .
"<merchantAuthentication>".
"<name>" . $loginname . "</name>".
"<transactionKey>" . $transactionkey . "</transactionKey>".
"</merchantAuthentication>".
"<refId>" . $refId . "</refId>".
"<subscription>".
"<name>" . $SubscrName . "</name>".
"<paymentSchedule>".
"<interval>".
"<length>". $length ."</length>".
"<unit>". $unit ."</unit>".
"</interval>".
"<startDate>" . $start_date . "</startDate>".
"<totalOccurrences>". $totalOccurrences . "</totalOccurrences>".
"<trialOccurrences>". $trialOccurrences . "</trialOccurrences>".
"</paymentSchedule>".
"<amount>". $TotalCosting ."</amount>".
"<trialAmount>" . $trialAmount . "</trialAmount>".
"<payment>".
"<creditCard>".
"<cardNumber>" . $CardNumber . "</cardNumber>".
"<expirationDate>" . $expirationDate . "</expirationDate>".
"<cardCode>".$CVV_Code."</cardCode>".
"</creditCard>".
"</payment>".
"<billTo>".
"<firstName>". $CardFirstName . "</firstName>".
"<lastName>" . $CardLastName . "</lastName>".
"<address>" . $CardStreet . "</address>".
"<city>" . $CardCity . "</city>".
"<state>" . $CardState . "</state>".
"<zip>" . $CardZip . "</zip>".
"</billTo>".
"</subscription>".
"</ARBCreateSubscriptionRequest>";
$responseDonation = send_request_via_curl($host,$path,$contentDonation);
if ($responseDonation)
{
var_dump($responseDonation);
exit;
list ($refId, $resultCodeDonation, $code, $text, $subscription_id) =parse_return($responseDonation);
if($resultCodeDonation == "Ok")
{}
}
}
}
}
Here is the code I have used where I tried ARB Script two times to pay 2nd time but I think this is not the right process so I get an error of Duplicate entry. Can anyone help me providing XML CUrl code of Direct Post method like ARB XML Curl I used. I didn't find any suitable example after searching a lot.

Microsoft Azure and SAS for PHP

i trying to create SAS link to blob resource using PHP. Unfortunately currently in azure SDK there is no method for creating SAS signature.
I wrote a code for generating SAS but when i'm trying to get a resource by the link generated by this method i'm getting this message: Signature fields not well formed.
public function getSharedAccessSignatureURL($container, $blob)
{
$signedStart = date('c', strtotime('-1 day'));
$signedExpiry = date('c', strtotime('+1 day'));
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$responseContent = "file; attachment";
$responseType = "binary";
$canonicalizedResource = '/'.$this->account['accountName'].'/'.$container.'/'.$blob;
$signedVersion = '2014-02-14';
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion;
$signature = base64_encode(
hash_hmac(
'sha256',
urldecode(utf8_encode($stringToSign)),
$this->account['primaryKey'],
true
)
);
$arrayToUrl = [
'sv='.urlencode($signedVersion),
'st='.urlencode($signedStart),
'se='.urlencode($signedExpiry),
'sr='.urlencode($signedResource),
'sp='.urlencode($signedPermission),
'rscd='.urlencode($responseContent),
'rsct='.urlencode($responseType),
'sig='.urlencode($signature)
];
$url = 'https://'.$this->account['accountName'].'.blob.core.windows.net'.'/'
.$container.'/'
.$blob.'?'.implode('&', $arrayToUrl);
return $url;
}
Any suggest what i am doing wrong? I am commpletle newbie at Microsoft Azure
I believe there's an issue with your $stringToSign variable. Based on the documentation here: http://msdn.microsoft.com/en-US/library/azure/dn140255.aspx, your string to sign should be constructed like the following:
StringToSign = signedpermissions + "\n"
signedstart + "\n"
signedexpiry + "\n"
canonicalizedresource + "\n"
signedidentifier + "\n"
signedversion + "\n"
rscc + "\n"
rscd + "\n"
rsce + "\n"
rscl + "\n"
rsct
considering you're including rscd and rsct in your SAS querystring. Please try the following and see if that makes the difference:
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion."\n".
"\n".
$responseContent."\n".
"\n".
"\n".
$responseType;
UPDATE
Please try the code below. Replace the account name/key, container name and blob name with appropriate values:
<?php
$signedStart = gmdate('Y-m-d\TH:i:s\Z', strtotime('-1 day'));
echo $signedStart."\n";
$signedExpiry = gmdate('Y-m-d\TH:i:s\Z', strtotime('+1 day'));
echo $signedExpiry."\n";
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$accountName = "[account name]";
$accountKey = "[account key]";
$container = "[container name]";
$blob = "[blob name]";
$canonicalizedResource = '/'.$accountName.'/'.$container.'/'.$blob;
$signedVersion = '2014-02-14';
echo $canonicalizedResource."\n";
$rscc = '';
$rscd = 'file; attachment';//Content disposition
$rsce = '';
$rscl = '';
$rsct = 'binary';//Content type
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion."\n".
$rscc."\n".
$rscd."\n".
$rsce."\n".
$rscl."\n".
$rsct;
echo $stringToSign."\n";
$signature = base64_encode(
hash_hmac(
'sha256',
$stringToSign,
base64_decode($accountKey),
true
)
);
echo $signature."\n";
$arrayToUrl = [
'sv='.urlencode($signedVersion),
'st='.urlencode($signedStart),
'se='.urlencode($signedExpiry),
'sr='.urlencode($signedResource),
'sp='.urlencode($signedPermission),
'rscd='.urlencode($rscd),
'rsct='.urlencode($rsct),
'sig='.urlencode($signature)
];
$url = 'https://'.$accountName.'.blob.core.windows.net'.'/'
.$container.'/'
.$blob.'?'.implode('&', $arrayToUrl);
echo $url."\n";
?>
Essentially there were two issues (apart from incorrect $stringToSign variable):
Start/End date time were not properly formatted.
We would need to base64_decode the account key for calculating signature.
I run into exactly the same problem. But now you can use MicrosoftAzure\Storage\Common\SharedAccessSignatureHelper which can handle a lot of problems for you. I has been added to the common libary 2 years ago in this PR (https://github.com/Azure/azure-storage-php/pull/73/files).
And it should be solved very simple like this:
$sasHelper = new SharedAccessSignatureHelper(
'nameofyouraccount',
'H...your-token...=='
);
$sas = $sasHelper->generateAccountSharedAccessSignatureToken(
'2018-11-09',
'rwl',
'b',
'sco',
(new \DateTime())->modify('+10 minute'),
(new \DateTime())->modify('-5 minute'),
'',
'https'
);
$connectionString = "BlobEndpoint=https://nameofyouraccount.blob.core.windows.net/;SharedAccessSignature={$sas}";
And you got your connection string!
modified and turned in to a function from #Gaurav Mantri
function generateSasToken($bucket,$key, $accountName, $accountKey){
$signedStart = gmdate('Y-m-d\TH:i:s\Z', time());
$signedExpiry = gmdate('Y-m-d\TH:i:s\Z', time()+3600);
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$canonicalizedResource = '/' . $accountName . '/' . $bucket . '/' . $key;
$signedVersion = '2014-02-14';
$rscc = '';
$rscd = 'file; attachment';//Content disposition
$rsce = '';
$rscl = '';
$rsct = 'binary';//Content type
$stringToSign =
$signedPermission . "\n" .
$signedStart . "\n" .
$signedExpiry . "\n" .
$canonicalizedResource . "\n" .
$signedIdentifier . "\n" .
$signedVersion . "\n" .
$rscc . "\n" .
$rscd . "\n" .
$rsce . "\n" .
$rscl . "\n" .
$rsct;
$signature = base64_encode(
hash_hmac(
'sha256',
$stringToSign,
base64_decode($accountKey),
true
)
);
$arrayToUrl = [
'sv=' . urlencode($signedVersion),
'st=' . urlencode($signedStart),
'se=' . urlencode($signedExpiry),
'sr=' . urlencode($signedResource),
'sp=' . urlencode($signedPermission),
'rscd=' . urlencode($rscd),
'rsct=' . urlencode($rsct),
'sig=' . urlencode($signature)
];
$url = 'https://' . $accountName . '.blob.core.windows.net' . '/'
. $bucket . '/'
. $key . '?' . implode('&', $arrayToUrl);
return $url;
}

Could not convert object to string

So I I've tried to make this code log an exception but it gives me the error message object of class domain_model could not be converted to string
The function looks as follows:
function errorLog($log, $error_type, $string, $file, $row, $error_hash, $error_trace)
{
$text = $error_hash . ' (' . date('Y-m-d H:i') . "):\n[Error type]: " . $error_type . "\n[Message]: " . $string . "\n[File]: " . $file . "\n[Row]: " . $row . "\n";
$text .= "[Trace]:\n";
foreach ($error_trace as $t)
{
$text .= ((isset($t['type']) && isset($t['object'])) ? $t['object'] . $t['type'] . $t['function'] : $t['function']) . "\n";
$text .= $t['file'] . "\n";
$text .= $t['line'] . "\n";
$text .= print_r($t['file'], 1) . "\n";
}
file_put_contents(BASE . $log . '.log', $text, FILE_APPEND);
}
After alot of thinking eventually saw that the line in making a mess is infact this one:
$text .= ((isset($t['type']) && isset($t['object'])) ? $t['object'] . $t['type'] . $t['function'] : $t['function']) . "\n";
And as I see it the only one in need of conversion should be $t['object'] however using (string)$t['object'] didn't work and still gives me the same error. Is there any other solution on how to convert it to a string than this?
I've looked at how they suggest it to be done here

Categories