I am calling an API of a shipping company to get the POD (Proof of delivery) image of a delivery as per this document.
I am expecting to see an image but the the API response is null.
Here is my code:
$host = "api.shiplogic.com";
$accessKey = 'AKIA55D5DNTBI4X24BCM'; //Sandbox credentials
$secretKey = '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'; //Sandbox credentials
$requestUrl = 'https://api.shiplogic.com';
$uri = '/shipments/pod/images?';
$httpRequestMethod = 'GET';
$data = 'tracking_reference=';
$refnr = 'FQJNF'; //created for testing
require 'AWS/aws-autoloader.php';;
use Aws\Signature\SignatureV4;
use Aws\Credentials\Credentials;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Client\ClientInterface;
$signature = new SignatureV4('execute-api', 'af-south-1');
$credentials = new Credentials($accessKey, $secretKey);
$psr7Request = new Request($httpRequestMethod, $requestUrl.$uri.$data.$refnr);
$client = new Client([$requestUrl, 'timeout' => 30]);
$sr = $signature->signRequest($psr7Request, $credentials);
$response = $client->send($sr);
$json = $response->getBody()->getContents();
echo $json;
I have tried to var_dump() and print_r()
What am I missing or doing wrong?
[{"id":203913730,"parcel_id":0,"date":"2022-08-05T09:44:19.704Z","status":"delivered","source":"danieladmin","message":"POD file(s) captured","data":{"images":["https://shiplogic-backend-prod-infra-images-and-notes.s3.af-south-1.amazonaws.com/shipment-images/8155533-fe1e0e10-324c-4360-b2f4-be51f091f8bb.png?X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026X-Amz-Credential=ASIA55D5DNTBLMDRXYD5%2F20220805%2Faf-south-1%2Fs3%2Faws4_request\u0026X-Amz-Date=20220805T113651Z\u0026X-Amz-Expires=86400\u0026X-Amz-Security-Token=IQoJb3JpZ2luX2VjEJ7%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCmFmLXNvdXRoLTEiRzBFAiB4vd1t%2F11LRUaoSCpqMdIP8gOuT9L32p1LSyCzSiGUBQIhAMt8FtNGK6ibRWvAJtIf%2FIGvOsESyCw2bIgNl27PWYBwKp0DCLv%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEQAhoMOTU1ODkyNTkxODEwIgwhD2CnEtahYg8Ck0Iq8QLMbochjBL6wQyuYPgOrOyvgliZs44WoRZqjDllfIPfa86R5TDw6hKI6aTaQLpNWUInFDnrGRu7sd%2BolgUsqnN17lr20S2h7Fy%2FnU0Rwv2z11AYSXgXrvxWbHVMJzngkyfteitp0GpD3cjK%2BdIJ9iKRS8g%2BO5WfFQKu99StSfkTWgJ%2Fo1myNwJoJkWkWhYiO1c%2BStpBSs0vdKhSKLOuNu3HBQIpWTQ1U8qnGvNdigAdz%2B7gCJwsaNqUH%2FHtl3xNSSbUSkEzqYLzdkjmKNFUC%2BrVAePsS4UnVhkMmWlnal%2BvSI%2FgY%2BDE1IuuhWYl7kuWa5SC6E5p2vngpN9lm0EnDSmK3OFsohMIJnu23WUXBJTxpmx%2Fb6KL%2FPrXapAhHccAz%2FJFmeU55%2FnMp0AqiuHjWYWE1ei1TPR2mhyj94wTW3Y4lUxhnvfeHz7QmPeh3KN3HAN0S2WHDf9Bv1gUD6bDshj1tiREoeChZzfp1ZbArO86AOgw%2BcSzlwY6nQFtpA37RYzkLVk52OW4g1tyja35Mfs6%2FykajH9IqkjuTLqvNmGIfrS7cLGgqhvdLUEs3QTIYDfPbjgkNsl5roEHbI7NO%2FhfrjIpBVmOsxJsqp62yL8Ze%2F29hgfug0TnycpXSg1bAOQ5ROelqQi5kcuy%2FTT3tePuZy1EO%2BXTm0tQbE3tf0XkLw34cQ6078ZAQJ7tyI4R4qRnWfdTkLtM\u0026X-Amz-SignedHeaders=host\u0026X-Amz-Signature=9a3d73a886012ac24e4719888156922d840a73d43569934a8de33ab2336f47b1"]}}]
<Error>
<Code>AuthorizationQueryParametersError</Code>
<Message>
X-Amz-Algorithm only supports "AWS4-HMAC-SHA256 and AWS4-ECDSA-P256-SHA256"
</Message>
<RequestId>ECGG4HGD86Y0PYAY</RequestId>
<HostId>
qZHFwL8gZ3GEibJ6UmgAoNd97EMVGe1Xw24RjYIKAqqrOi2Cx+YPmBJGoCy4opTiih5Nz5YlEuU=
</HostId>
</Error>
Your code is actually entirely correct as far as getting the response, but the problem is that the response you're trying to copy the URL from is still JSON encoded. This leaves some of the parts of the URL in an invalid, encoded state; specifically, the & is encoded to /u0026.
...?X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026...
That /u0026 at the end of each parameter is the culprit. If you json_decode() the response, then you get the correct URL.
The URL I received when I ran the code and decoded the result seems to work. All I did was add a line and change the last line:
...
$json = $response->getBody()->getContents();
$result = json_decode($json, false);
echo $result[0]->data->images[0];
You could obviously do that without adding a line and just changing the line where $json is assigned, but I wanted to leave that line alone to make it easier to see exactly what was different.
...
$json = json_decode($response->getBody()->getContents(), false);
echo $json[0]->data->images[0];
Related
We are using the MTN PHP-SDK from the below URL
https://github.com/digitalmaterial/dep.api.auth.php
Code:
$path = '/subscription/' . $subscription_id;
$depClient = new MTNDEP\DEPClient($accessKey, $accessSecret, $apiKey, $baseUrl);
$requestBody = [];
$response = $depClient->createRequest(MTNDEP\DEPClient::DELETE, $path, null, $requestBody)->send();
$responseArray = json_decode((string) $response->getBody(), true);
Response:
Client error: `DELETE https://api.dep.mtn.co.za/subscription/` resulted in a `404 Not Found` response:
{"message":"No method found matching route subscription/ for http method DELETE."}
We are unable to find any MTN-DEP Cancel subscription PHP code. Please help us and let us know how can we delete the subscription from MTN end?
i have noticed 2 things :
1- in the mentioned documentation, the request sent like this
$depClient->createRequest('POST' '/subscription');
so i think you need to use this , please try to adhere with all steps
$depClient->createRequest('DELETE',$path); // Returns DEPClient object for chaining, see below
$depClient->getRequest(); // Will return the GuzzleHttp\Psr7\Request object with signed auth details for DEP API requests
$response = $depClient->send();
$statusCode = $response->getStatusCode(); // returns the http status code
$rawResponse = (string) $response->getBody(); // body, you will need to cast to string or echo to get the body data.
$responseArray = json_decode($rawResponse, true); // return json decode array.
2- make sure the $subscription_id is set and have a value before you send the request.
Stating to the documentation, you need to specify the customer ID and the subscription ID.
You have to make a DELETE request to the endpoint /customers/{id}/subscriptions/{subscriptionId}.
Maybe the path specified in your code should look like this:
$path = '/customers/' . $customer_id . '/subscriptions/' . $subscription_id;
$depClient = new MTNDEP\DEPClient($accessKey, $accessSecret, $apiKey, $baseUrl);
$requestBody = [];
$response = $depClient->createRequest(MTNDEP\DEPClient::DELETE, $path, null, $requestBody)->send();
$responseArray = json_decode((string) $response->getBody(), true);
I'm trying to return a value from my API using PHP, api can be found here:
code is as follows:
Im not seeing the echo on my page, don't see any errors and I believing im reading the json in correctly. Any help appreciated!
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue["Age"];
?>
From what I can tell, the json is not valid on the server side (due to the "connected to db" text in front of the {} part). I think it would be a good idea to fix the server side response json data, if possible!
For now, here is a way to get the value it looks like you are intending to retrieve:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$adjusted_response = str_replace('connected to db', '', $response);
$returnvalue = json_decode($adjusted_response, true);
echo $returnvalue['tv_shows']['Age'];
?>
Output:
$ php example.php
16+
If the server side json data is fixed, I think you could shorten the code to something like this:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue['tv_shows']['Age'];
?>
The thing is that $response is returned as string , in order to fix that you need to edit your backend and make it give the response without "connected to db"
I want to send btc using my account with api with php.
I tried coinbase api from github which is depreciated
https://github.com/coinbase/coinbase-php
and i am getting error when i tried this code
require_once( __DIR__ . '/requires/coinbase/vendor/autoload.php');
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
$transaction = Transaction::send([
'toBitcoinAddress' => "$bticoin_address",
'amount' => new Money($amount, CurrencyCode::USD),
'description' => 'Your first bitcoin!',
'fee' => '0.0001' // only required for transactions under BTC0.0001
]);
try {
$transaction = $client->createAccountTransaction($account, $transaction);
}
catch(Exception $e) {
echo $e->getMessage();
}
and i am getting this error
<b>Fatal error</b>: Uncaught TypeError: Argument 1 passed to Coinbase\Wallet\Exception\HttpException::exceptionClass() must be an instance of Psr\Http\Message\ResponseInterface, null given, called in /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php on line 33 and defined in /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php:98
Stack trace:
#0 /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php(33): Coinbase\Wallet\Exception\HttpException::exceptionClass(NULL)
#1 /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/HttpClient.php(137): Coinbase\Wallet\Exception\HttpException::wrap(Object(GuzzleHttp\Exception\RequestException))
#2 /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/HttpClient.php(121): Coinbase\Wallet\HttpClient->send(Object(GuzzleHttp\Psr7\Request), Array)
#3 /home/fiberpay/public_html/owne in <b>/home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php</b> on line <b>98</b><br />
Is there anyway to do that ??
I spend much time to google it but still not found any solution that is i why i put that on there may be i got some good solution from there :)
Best Regars
Instead of using coinbase PHP wrapper use coinbase API itself
To send money from one coinbase account to another you can use the below code
first, get api_key and api_secret
$private_key = 'Doadlraixxxxxx'; //Coinbase Private Key
$api_key = 'ysEZjjBxxxxx'; //Coinbase API KEY
The Create a new stdClass object which contains your request method for withdrawing it will be POST, the path will be API path, and for withdrawing it will be /v2/accounts/:accountid/transactions, and then simply put private key and API key here
$json = new stdClass();
$json->method = "POST";
$json->path = "/v2/accounts/".$account_id."/transactions";
$json->secretapikey = $private_key;
$json->apikey = $api_key;
Now create another stdClass that contain your withdrawal info like email, currency, etc
$body = new stdClass();
$body->type = "send";
$body->to = $to_email;
$body->amount = $amount;
$body->currency = $currency;
then in the next step, we have to create a signature according to the timestamp for this we have to create SHA256 hash of current time, path, and the $body stdClass
$result = json_encode($json);
$body = json_encode($body);
$time= time();
$sign = $time.$json->method.$json->path.$body;
$hmac = hash_hmac("SHA256", $sign, $json->secretapikey);
Our Signature and body are ready now just need to post it
$URL = "https://api.coinbase.com/v2/accounts/".$account_id."/transactions";
$header = array(
"CB-ACCESS-KEY:".$api_key,
"CB-ACCESS-SIGN:".$hmac,
"CB-ACCESS-TIMESTAMP:".time(),
"CB-VERSION:2019-11-15",
"Content-Type:application/json"
);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
After sending a request the money will be sended successfully.
And with a little decoration code will look like this
https://gist.github.com/AdityaEXP/27408bd361d5b8fcc9ac2bf459eb5303
I've been using the coinbase php library for 4years.
When you get that error, it's highly probably due to incorrect account credentials.
Also, the default github library has an expired uploaded certificate in one of its folder.
You have to replace it.
Coinbase PHP works fine for me everytime.
I am currently updating recaptchalib.php to upgrade captcha from V1 to V2.
I have done the client integration successfully. But at the server side facing issues. In my below code snippet if I hit the URL directly in browser I either get
"success" : false with "error-codes" as "timeout-or-duplicate" OR
"success" :true but in both the above cases file_get_contents() returns the value as bool(false). Ultimately, always I get the error as "reCaptcha not enetered correctly" .Please suggest why file_get_content() is always returning bool(false)? What correction can be done in code so that we get response in correct format and then do json_decode successfully i.e hit 'true' case .
Below is the code snippet
$postdata = http_build_query(
array(
'secret' => $privkey,
'response' => $response,
'remoteip' => $remoteip
)
);
$url = 'https://www.google.com/recaptcha/api/siteverify?'.$postdata;
print "URL is " . $url . "<br>";
$response = file_get_contents($url);
var_dump($response) ;
$responses = json_decode($response, true);
if($responses["success"] === TRUE){
echo "true";
}else{
echo "false";
}
For file_get_contents() to work, the URL that is passed must not conatin any special characters. To obtain the sanitized version of the URL, use urlencode() as mentioned here. Looks like your URL might have special characters (private key etc.).
Try this:
$url = 'https://www.google.com/recaptcha/api/siteverify?'.$postdata;
$url = urlencode($url);
$response = file_get_contents($url);
I am getting the restful web service response as well. But I am not able to parse it properly
my code looks like this
include 'RestClient.class.php';
error_reporting(E_ALL);
// Client Profile
$url = "http://localhost/lgen/index.php/api/client";
$ex = RestClient::get($url,array('requestType' =>'viewClientProfile',
'username' => 'uname',
'pass' =>'pass'));
echo $response = $ex->getResponse();
$xml = simplexml_load_string($response);
when print $response I am getting data on browser but while trying to parse it am not getting any kind of data
echo $response = $ex->getResponse();
You are creating and echoing a variable at the same time.
Try this:
$xml = simplexml_load_string($ex->getResponse());
var_dump($xml);