I'm trying to use the $rank variable outside the function and class.
class UrlInfo {
protected static $ActionName = 'UrlInfo';
protected static $ResponseGroupName = 'Rank,LinksInCount';
protected static $ServiceHost = 'awis.amazonaws.com';
protected static $ServiceEndpoint = 'awis.us-west-1.amazonaws.com';
protected static $NumReturn = 10;
protected static $StartNum = 1;
protected static $SigVersion = '2';
protected static $HashAlgorithm = '******';
protected static $ServiceURI = "/api";
protected static $ServiceRegion = "us-west-1";
protected static $ServiceName = "awis";
public function __construct($accessKeyId, $secretAccessKey, $site) {
$this->accessKeyId = $accessKeyId;
$this->secretAccessKey = $secretAccessKey;
$this->site = $site;
$now = time();
$this->amzDate = gmdate("Ymd\THis\Z", $now);
$this->dateStamp = gmdate("Ymd", $now);
}
/**
* Get site info from AWIS.
*/
public function getUrlInfo() {
$canonicalQuery = $this->buildQueryParams();
$canonicalHeaders = $this->buildHeaders(true);
$signedHeaders = $this->buildHeaders(false);
$payloadHash = hash('sha256', "");
$canonicalRequest = "GET" . "\n" . self::$ServiceURI . "\n" . $canonicalQuery . "\n" . $canonicalHeaders . "\n" . $signedHeaders . "\n" . $payloadHash;
$algorithm = "AWS4-HMAC-SHA256";
$credentialScope = $this->dateStamp . "/" . self::$ServiceRegion . "/" . self::$ServiceName . "/" . "aws4_request";
$stringToSign = $algorithm . "\n" . $this->amzDate . "\n" . $credentialScope . "\n" . hash('sha256', $canonicalRequest);
$signingKey = $this->getSignatureKey();
$signature = hash_hmac('sha256', $stringToSign, $signingKey);
$authorizationHeader = $algorithm . ' ' . 'Credential=' . $this->accessKeyId . '/' . $credentialScope . ', ' . 'SignedHeaders=' . $signedHeaders . ', ' . 'Signature=' . $signature;
$url = 'https://' . self::$ServiceHost . self::$ServiceURI . '?' . $canonicalQuery;
$ret = self::makeRequest($url, $authorizationHeader);
// echo "\nResults for " . $this->site .":\n\n";
// echo $ret;
self::parseResponse($ret);
}
protected function sign($key, $msg) {
return hash_hmac('sha256', $msg, $key, true);
}
protected function getSignatureKey() {
$kSecret = 'AWS4' . $this->secretAccessKey;
$kDate = $this->sign($kSecret, $this->dateStamp);
$kRegion = $this->sign($kDate, self::$ServiceRegion);
$kService = $this->sign($kRegion, self::$ServiceName);
$kSigning = $this->sign($kService, 'aws4_request');
return $kSigning;
}
/**
* Builds headers for the request to AWIS.
* #return String headers for the request
*/
protected function buildHeaders($list) {
$params = array(
'host' => self::$ServiceEndpoint,
'x-amz-date' => $this->amzDate
);
ksort($params);
$keyvalue = array();
foreach($params as $k => $v) {
if ($list)
$keyvalue[] = $k . ':' . $v;
else {
$keyvalue[] = $k;
}
}
return ($list) ? implode("\n",$keyvalue) . "\n" : implode(';',$keyvalue) ;
}
/**
* Builds query parameters for the request to AWIS.
* Parameter names will be in alphabetical order and
* parameter values will be urlencoded per RFC 3986.
* #return String query parameters for the request
*/
protected function buildQueryParams() {
$params = array(
'Action' => self::$ActionName,
'Count' => self::$NumReturn,
'ResponseGroup' => self::$ResponseGroupName,
'Start' => self::$StartNum,
'Url' => $this->site
);
ksort($params);
$keyvalue = array();
foreach($params as $k => $v) {
$keyvalue[] = $k . '=' . rawurlencode($v);
}
return implode('&',$keyvalue);
}
/**
* Makes request to AWIS
* #param String $url URL to make request to
* #param String authorizationHeader Authorization string
* #return String Result of request
*/
protected function makeRequest($url, $authorizationHeader) {
// echo "\nMaking request to:\n$url\n";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/xml',
'Content-Type: application/xml',
'X-Amz-Date: ' . $this->amzDate,
'Authorization: ' . $authorizationHeader
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* Parses XML response from AWIS and displays selected data
* #param String $response xml response from AWIS
*/
public static function parseResponse($response) {
$xml = new SimpleXMLElement($response,LIBXML_ERR_ERROR,false,'http://awis.amazonaws.com/doc/2005-07-11');
if($xml->count() && $xml->Response->UrlInfoResult->Alexa->count()) {
$info = $xml->Response->UrlInfoResult->Alexa;
$links = $info->ContentData->LinksInCount;
$rank = $info->TrafficData->Rank;
echo "<br>Links in Count: " .$links;
echo "<br>Rank: " .$rank;
);
}
}
}
}
Does anyone have an idea?
Thanks!
I want to add the $rank to an array;
$arrayinfo = array(
"domain" => $ip,
"ip" => $ipphp,
"Rank" => $rank,);
What if you declare $rank as a static variable like the $name of following example
<?php
class Test{
static $name;
static function setName($name){
self::$name=$name;
}
}
Test::setName("Test Name");
Test::setName("Test1 Name");
echo Test::$name; //Test1 Name
Related
When I am trying to integrate the PayU integration. Whatever changes I do I am getting invalid hash. I think I am doing something minor mistake.
For generating the hash I have written in PHP though currently, all data is static I have matched all are same only.
In the following php example I am using payment_related_details_for_mobile_sdk_hash key in android
Here is my code:
paymentIntegration("741852963", "1.0", "SmartAuto", "Piyush", "piyush.sahay#mail.com", "330122983a2492fe6ff18ad2fcccc6a78ed499f988a6b06b226ff4f27b9b390356f18c297282105b2dbb70166bfd0c2332dfa4e55a784543658bd67330f98b39", "XXXXX:XXXXX#XXXXX.com");
private void paymentIntegration(String txnId, String amount, String productName, String userName, String userEmail, String hash1, String userCredentials) {
HashMap<String, Object> additionalParams = new HashMap<>();
additionalParams.put(PayUCheckoutProConstants.CP_UDF1, "udf1");
additionalParams.put(PayUCheckoutProConstants.CP_UDF2, "udf2");
additionalParams.put(PayUCheckoutProConstants.CP_UDF3, "udf3");
additionalParams.put(PayUCheckoutProConstants.CP_UDF4, "udf4");
additionalParams.put(PayUCheckoutProConstants.CP_UDF5, "udf5");
PayUPaymentParams.Builder builder = new PayUPaymentParams.Builder();
builder.setAmount(amount)
.setIsProduction(true)
.setProductInfo(productName)
.setKey(MERCHANT_KEY)
.setPhone("XXXXXXXX")
.setTransactionId(txnId)
.setFirstName(userName)
.setEmail(userEmail)
.setSurl("https://payu.herokuapp.com/success")
.setFurl("https://payu.herokuapp.com/failure")
.setUserCredential(userCredentials)
.setAdditionalParams(additionalParams);
PayUPaymentParams payUPaymentParams = builder.build();
PayUCheckoutPro.open(
this,
payUPaymentParams,
new PayUCheckoutProListener() {
#Override
public void onPaymentSuccess(Object response) {
//Cast response object to HashMap
HashMap<String,Object> result = (HashMap<String, Object>) response;
String payuResponse = (String)result.get(PayUCheckoutProConstants.CP_PAYU_RESPONSE);
String merchantResponse = (String) result.get(PayUCheckoutProConstants.CP_MERCHANT_RESPONSE);
}
#Override
public void onPaymentFailure(Object response) {
//Cast response object to HashMap
HashMap<String,Object> result = (HashMap<String, Object>) response;
String payuResponse = (String)result.get(PayUCheckoutProConstants.CP_PAYU_RESPONSE);
String merchantResponse = (String) result.get(PayUCheckoutProConstants.CP_MERCHANT_RESPONSE);
}
#Override
public void onPaymentCancel(boolean isTxnInitiated) {
}
#Override
public void onError(ErrorResponse errorResponse) {
String errorMessage = errorResponse.getErrorMessage();
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show();
}
#Override
public void setWebViewProperties(#Nullable WebView webView, #Nullable Object o) {
//For setting webview properties, if any. Check Customized Integration section for more details on this
}
#Override
public void generateHash(HashMap<String, String> valueMap, PayUHashGenerationListener hashGenerationListener) {
String hashName = valueMap.get(PayUCheckoutProConstants.CP_HASH_NAME);
String hashData = valueMap.get(PayUCheckoutProConstants.CP_HASH_STRING);
if (!TextUtils.isEmpty(hashName) && !TextUtils.isEmpty(hashData)) {
//Do not generate hash from local, it needs to be calculated from server side only. Here, hashString contains hash created from your server side.
String hash = hash1;
HashMap<String, String> dataMap = new HashMap<>();
dataMap.put(hashName, hash);
hashGenerationListener.onHashGenerated(dataMap);
}
}
}
);
}
Here is my PHP Code for a hash generation:
$output=getHashes("741852963", "1.0", "SmartAuto", "Piyush", "piyush.sahay#gmail.com", "XXXXX:XXXXX#XXXXX.com","udf1","udf2","udf3","udf4","udf5","","" );
function getHashes($txnid, $amount, $productinfo, $firstname, $email, $user_credentials, $udf1, $udf2, $udf3, $udf4, $udf5,$offerKey,$cardBin)
{
// $firstname, $email can be "", i.e empty string if needed. Same should be sent to PayU server (in request params) also.
$key = 'XXXXX';
$salt = 'XXXXXX';
$payhash_str = $key . '|' . checkNull($txnid) . '|' .checkNull($amount) . '|' .checkNull($productinfo) . '|' . checkNull($firstname) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '||||||' . $salt;
$paymentHash = strtolower(hash('sha512', $payhash_str));
$arr['payment_hash'] = $paymentHash;
$cmnNameMerchantCodes = 'get_merchant_ibibo_codes';
$merchantCodesHash_str = $key . '|' . $cmnNameMerchantCodes . '|default|' . $salt ;
$merchantCodesHash = strtolower(hash('sha512', $merchantCodesHash_str));
$arr['get_merchant_ibibo_codes_hash'] = $merchantCodesHash;
$cmnMobileSdk = 'vas_for_mobile_sdk';
$mobileSdk_str = $key . '|' . $cmnMobileSdk . '|default|' . $salt;
$mobileSdk = strtolower(hash('sha512', $mobileSdk_str));
$arr['vas_for_mobile_sdk_hash'] = $mobileSdk;
$cmnPaymentRelatedDetailsForMobileSdk1 = 'payment_related_details_for_mobile_sdk';
$detailsForMobileSdk_str1 = $key . '|' . $cmnPaymentRelatedDetailsForMobileSdk1 . '|default|' . $salt ;
$detailsForMobileSdk1 = strtolower(hash('sha512', $detailsForMobileSdk_str1));
$arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk1;
//used for verifying payment(optional)
$cmnVerifyPayment = 'verify_payment';
$verifyPayment_str = $key . '|' . $cmnVerifyPayment . '|'.$txnid .'|' . $salt;
$verifyPayment = strtolower(hash('sha512', $verifyPayment_str));
$arr['verify_payment_hash'] = $verifyPayment;
if($user_credentials != NULL && $user_credentials != '')
{
$cmnNameDeleteCard = 'delete_user_card';
$deleteHash_str = $key . '|' . $cmnNameDeleteCard . '|' . $user_credentials . '|' . $salt ;
$deleteHash = strtolower(hash('sha512', $deleteHash_str));
$arr['delete_user_card_hash'] = $deleteHash;
$cmnNameGetUserCard = 'get_user_cards';
$getUserCardHash_str = $key . '|' . $cmnNameGetUserCard . '|' . $user_credentials . '|' . $salt ;
$getUserCardHash = strtolower(hash('sha512', $getUserCardHash_str));
$arr['get_user_cards_hash'] = $getUserCardHash;
$cmnNameEditUserCard = 'edit_user_card';
$editUserCardHash_str = $key . '|' . $cmnNameEditUserCard . '|' . $user_credentials . '|' . $salt ;
$editUserCardHash = strtolower(hash('sha512', $editUserCardHash_str));
$arr['edit_user_card_hash'] = $editUserCardHash;
$cmnNameSaveUserCard = 'save_user_card';
$saveUserCardHash_str = $key . '|' . $cmnNameSaveUserCard . '|' . $user_credentials . '|' . $salt ;
$saveUserCardHash = strtolower(hash('sha512', $saveUserCardHash_str));
$arr['save_user_card_hash'] = $saveUserCardHash;
$cmnPaymentRelatedDetailsForMobileSdk = 'payment_related_details_for_mobile_sdk';
$detailsForMobileSdk_str = $key . '|' . $cmnPaymentRelatedDetailsForMobileSdk . '|' . $user_credentials . '|' . $salt ;
$detailsForMobileSdk = strtolower(hash('sha512', $detailsForMobileSdk_str));
$arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk;
}
// if($udf3!=NULL && !empty($udf3)){
$cmnSend_Sms='send_sms';
$sendsms_str=$key . '|' . $cmnSend_Sms . '|' . $udf3 . '|' . $salt;
$send_sms = strtolower(hash('sha512',$sendsms_str));
$arr['send_sms_hash']=$send_sms;
// }
if ($offerKey!=NULL && !empty($offerKey)) {
$cmnCheckOfferStatus = 'check_offer_status';
$checkOfferStatus_str = $key . '|' . $cmnCheckOfferStatus . '|' . $offerKey . '|' . $salt ;
$checkOfferStatus = strtolower(hash('sha512', $checkOfferStatus_str));
$arr['check_offer_status_hash']=$checkOfferStatus;
}
if ($cardBin!=NULL && !empty($cardBin)) {
$cmnCheckIsDomestic = 'check_isDomestic';
$checkIsDomestic_str = $key . '|' . $cmnCheckIsDomestic . '|' . $cardBin . '|' . $salt ;
$checkIsDomestic = strtolower(hash('sha512', $checkIsDomestic_str));
$arr['check_isDomestic_hash']=$checkIsDomestic;
}
return $arr;
}
function checkNull($value) {
if ($value == null) {
return '';
} else {
return $value;
}
}
echo json_encode($output);
function S3_delete($s3_array)
{
$AWSAccessKeyId = 'youraccesskey';
$AWSSecretAccessKey = 'yoursecretaccesskey';
$BucketName = 'yourbucket';
$AWSRegion = 'ap-south-1';
$canonical_uri="/images/coupon_images/medium_banner/2019091810352344157.jpg";
$encoded_uri = str_replace('%2F', '/', rawurlencode($canonical_uri));
if($AWSRegion == 'us-east-1') {
$hostname = trim($BucketName .".s3.amazonaws.com");
$header_string = "host:" . $hostname . "\n";
$signed_headers_string = "host";
} else {
$hostname = trim($BucketName . ".s3-" . $AWSRegion . ".amazonaws.com");
$header_string = "host:" . $hostname . "\n";
$signed_headers_string = "host";
}
$date_text = gmdate('Ymd', time());
$time_text = gmdate('Ymd\THis\Z');
$algorithm = 'AWS4-HMAC-SHA256';
$scope = $date_text . "/" . $AWSRegion . "/s3/aws4_request";
$x_amz_params = array(
'X-Amz-Algorithm' => $algorithm,
'X-Amz-Credential' => $AWSAccessKeyId . '/' . $scope,
'X-Amz-Date' => $time_text,
'X-Amz-SignedHeaders' => $signed_headers_string
);
$expires = 72000;
if ($expires > 0) {
$x_amz_params['X-Amz-Expires'] = $expires;
}
ksort($x_amz_params);
$query_string = "";
foreach ($x_amz_params as $key => $value) {
$query_string .= rawurlencode($key) . '=' . rawurlencode($value) . "&";
}
$query_string = substr($query_string, 0, -1);
$canonical_request = "DELETE\n" . $encoded_uri . "\n" . $query_string . "\n" . $header_string . "\n" . $signed_headers_string . "\nUNSIGNED-PAYLOAD";
$string_to_sign = $algorithm . "\n" . $time_text . "\n" . $scope . "\n" . hash('sha256', $canonical_request, false);
$signing_key = hash_hmac('sha256', 'aws4_request', hash_hmac('sha256', 's3', hash_hmac('sha256', $AWSRegion, hash_hmac('sha256', $date_text, 'AWS4' . $AWSSecretAccessKey, true), true), true), true);
$signature = hash_hmac('sha256', $string_to_sign, $signing_key);
$url = 'https://' . $hostname . $encoded_uri . '?' . $query_string . '&X-Amz-Signature=' . $signature;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
return $httpcode = curl_getinfo($ch);
}
above code give response like this,
SignatureDoesNotMatchThe request signature we calculated does not
match the signature you provided. Check your key and signing
method.AKIAJKLJAHRPH4X4FSMQAWS4-HMAC-SHA256 20190919T053115Z
20190919/ap-south-1/s3/aws4_request
100% work the below code..
S3_delete('201909251745545.jpg','imagesbook/post_blog/'); //call function
function S3_delete($filename,$path)
{
$file_name = $filename;
$file_delete_path = $path;
$aws_access_key_id = 'your-accress-key';
$aws_secret_access_key = 'your-secret-access-key';
$bucket_name = 'your-bucket-name';
$aws_region = 'your-region'; // Enter your aws region Ex. us-east-1
$host_name = $bucket_name . '.s3.amazonaws.com';
$content_acl = 'public-read';
$content_type = '';
$content='';
$content_title = $file_delete_path.$file_name;
$aws_service_name = 's3';
$timestamp = gmdate('Ymd\THis\Z');
$date = gmdate('Ymd');
$request_headers = array();
$request_headers['Content-Type'] = $content_type;
$request_headers['Date'] = $timestamp;
$request_headers['Host'] = $host_name;
$request_headers['x-amz-acl'] = $content_acl;
$request_headers['x-amz-content-sha256'] = hash('sha256',"");
ksort($request_headers);
$canonical_headers = [];
foreach($request_headers as $key => $value)
{
$canonical_headers[] = strtolower($key) . ":" . $value;
}
$canonical_headers = implode("\n", $canonical_headers);
$signed_headers = [];
foreach($request_headers as $key => $value)
{
$signed_headers[] = strtolower($key);
}
$signed_headers = implode(";", $signed_headers);
$canonical_request = [];
$canonical_request[] = "DELETE";
$canonical_request[] = "/" . $content_title;
$canonical_request[] = "";
$canonical_request[] = $canonical_headers;
$canonical_request[] = "";
$canonical_request[] = $signed_headers;
$canonical_request[] = hash('sha256', $content);
$canonical_request = implode("\n", $canonical_request);
$hashed_canonical_request = hash('sha256', $canonical_request);
$scope = [];
$scope[] = $date;
$scope[] = $aws_region;
$scope[] = $aws_service_name;
$scope[] = "aws4_request";
$string_to_sign = [];
$string_to_sign[] = "AWS4-HMAC-SHA256";
$string_to_sign[] = $timestamp;
$string_to_sign[] = implode('/', $scope);
$string_to_sign[] = $hashed_canonical_request;
$string_to_sign = implode("\n", $string_to_sign);
$kSecret = 'AWS4' . $aws_secret_access_key;
$kDate = hash_hmac('sha256', $date, $kSecret, true);
$kRegion = hash_hmac('sha256', $aws_region, $kDate, true);
$kService = hash_hmac('sha256', $aws_service_name, $kRegion, true);
$kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
$signature = hash_hmac('sha256', $string_to_sign, $kSigning);
$authorization = [
'Credential=' . $aws_access_key_id . '/' . implode('/', $scope),
'SignedHeaders=' . $signed_headers,
'Signature=' . $signature
];
$authorization = 'AWS4-HMAC-SHA256' . ' ' . implode( ',', $authorization);
$curl_headers = [ 'Authorization: ' . $authorization ];
foreach($request_headers as $key => $value)
{
$curl_headers[] = $key . ": " . $value;
}
$url = 'https://' . $host_name . '/' . $content_title;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
return curl_exec($ch); // return response data 1
//$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//curl_close($ch);
//return $httpcode;
}
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');
I am trying to invoke the getTransactionDetail end point on sagepay reporting api (https://www.sagepay.co.uk/file/6946/download-document/Reporting_and_Admin_API_Integration_Guideline_31012014.pdf) and the signature I made as per the following instructions:
does not appear to be working, I am getting an invalid signature response.
Here's what I have tried so far:
<?php
$vendor = 'myvendername';
$username = 'my-username';
$password = 'my-password';
$vpstxid = '{my-vpstxid-guid-here}';
$request = [
'command' => 'getTransactionDetail',
'vendor' => $vendor,
'user' => $username,
'vpstxid' => $vpstxid,
];
$signature = _calculate_request_signature($request);
$request_xml = _build_sagepay_request($request, $signature);
$result = _call_sagepay_server('https://test.sagepay.com/access/access.htm', $request_xml);
$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
echo '<pre>'; print_r($array); exit;
function _calculate_request_signature($data) {
global $password;
$req = '';
foreach ($data as $key => $value) {
$req .= '<' . $key . '>' . $value . '</' . $key . '>' . PHP_EOL;
}
$req .= '<password>' . $password . '</password>';
return md5($req);
}
function _build_sagepay_request($data, $signature) {
$result = '<vspaccess>' . PHP_EOL;
foreach ($data as $key => $value) {
$result .= "\t" . '<' . $key . '>' . $value . '</' . $key . '>' . PHP_EOL;
}
$result .= "\t" . '<signature>' . $signature . '</signature>' . PHP_EOL;
$result .= '</vspaccess>';
return $result;
}
function _call_sagepay_server($url, $request_xml)
{ ... snipped ... }
Any ideas?
Ok, I've figured it out:
No tabs / PHP_EOL in the request / signature calc, keep it flat one line xml and it works.
function _calculate_request_signature($data) {
global $password;
$req = '';
foreach ($data as $key => $value) {
$req .= '<' . $key . '>' . $value . '</' . $key . '>';
}
$req .= '<password>' . $password . '</password>';
return strtoupper(md5($req));
}
function _build_sagepay_request($data, $signature) {
$result = '<vspaccess>';
foreach ($data as $key => $value) {
$result .= '<' . $key . '>' . $value . '</' . $key . '>';
}
$result .= '<signature>' . $signature . '</signature>';
$result .= '</vspaccess>';
return $result;
}
function _call_sagepay_server($url, $request_xml)
{
global $lastCurlError;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'XML=' . $request_xml);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 45);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$lastCurlError = curl_errno($curl);
curl_close($curl);
return $result;
}
I have this Form with several subForms I'm using a tabContainer,
In one of them I have a button when clicked would like that in that "space" subForm
a datagrid would appear with some values.
Is it possible to do this, how?
I tried creating a datagrid View Helper but this didn't work properly the DataGrid does not show.
Code used:
/** * Description of DataGrid * * #author andref * #version $Id$
*/ class Zend_View_Helper_DataGrid {
private $_nameDG = 'DefaultSt';
private $_action = '';
private $_key = '';
private $_selectMode = "single";
private $_fields = array();
private $_storage = 'getall/';
public function dataGrid($key, $action = null, $options = array() )
{
if (count($options) > 0 ) {
if (array_key_exists("selectmode", $options)) {
$this->_selectMode = $options['selectmode'];
} elseif (array_key_exists("fields", $options)) {
if (!is_array($options['fields'])) {
throw new Exception("fields is not an array");
}
$this->_fields = $options['fields'];
} elseif(array_key_exists("selectmode", $options)) {
$this->_selectMode = $options['selectmode'];
} elseif(array_key_exists("storage", $options)) {
$this->_storage = $options['storage'];
}
}
if ($action !== null ) {
$this->_action = $action;
}
if ($key === null ) {
throw new Exception("Key cannot be null.");
}
$this->_key = $key;
return $this->_init();
}
private function _init()
{
$str = '';
if (!empty($this->_action)) {
$str .= $this->addJS();
}
$str .= $this->storageType();
$str .= $this->draw();
return $str;
}
/**
* Returns double click handler to direct to a form
*
* #return String
*/
public function addJS()
{
$str = "<script type=\"text/Javascript\">\n";
$str .= "function pickit(event)\n";
$str .= "{\n";
$str .= "grid = dijit.byId('grid".$this->_key."');\n";
$str .= "selected_index = grid.focus.rowIndex;\n";
$str .= "selected_item = grid.getItem(selected_index);\n";
//Not sure if this is the most efficient way but it worked for me
$str .= "selected_id = grid.store.getValue(selected_item, \"".$this->_key."\");\n";
$str .= "location.href = " . $this->_action . "+selected_id;\n";
$str .= "}\n";
$str .= "</script>\n";
return $str;
}
public function storageType()
{
if (strpos($this->_storage, "[") !== false ) {
$st = "jsonData".$this->_key . " = " . $this->_storage."\n";
$st .= "<gett dojoType=\"dojo.data.ItemFileReadStore\"
jsId=\"jsonStore" . $this->_key . "\"
data=\"jsonData" . $this->_key . "\" id=\"store" . $this->_key . "\" />";
} else {
$st = '<gett dojoType="dojo.data.ItemFileReadStore" jsId=\"jsonStore'.$this->_key.'"
url="' . $this->_storage . '" id="store'.$this->_key.'" />';
}
return $st;
}
public function draw()
{
$str = '';
$str .= "<table dojoType=\"dojox.grid.DataGrid\" id=\"grid".$this->_key."\" jsid=\"gridJ".$this->_key."\"
query=\"{ " . $this->_key . ": '*' }\" store=\"jsonStore".$this->_key."\"
selectionMode=\"" . $this->_selectMode . "\" autoWidth=\"true\"
style=\"width: 100%; height: 400px\" onRowDblClick='pickit();'>\n";
$str .= "<thead>\n";
$str .= "<tr>\n";
foreach ($this->_fields as $k => $v ) {
$str .= "\t<th field=\"$k\">$v</th>\n";
}
$str .= "</tr>\n";;
$str .= "</thead>\n";
$str .= "</table>\n";
return $str;
}
}
try creating a grid in pure js and place it
using grid.placeat("idOfElement") in your element. Take a look here:
http://dojotoolkit.org/reference-guide/1.8/dojox/grid/DataGrid.html