cURL command to Guzzle - php

I need to convert a cURL command like this into Guzzle-way:
curl -XPOST "https://api/v1.0/endpoint" -F "file=#img.jpg"
This is what I'm trying so far:
$httpClient = new \GuzzleHttp\Client;
$req = $httpClient->createRequest('POST', $url), []);
$postBody = $req->getBody();
$postBody->addFile(new \GuzzleHttp\Post\PostFile('photo', fopen(storage_path() . '/' . $filename, 'r')));
$response = $httpClient->send($req);
But I'm not getting the same response as with the previous command, which is something like:
{"id":5378678,"url":"ui/54/68/97/24/img.jpg"}
I'm getting a GuzzleHttp\Message\Response object, but I'm not being able to find the id and url attributes in there.
Any help will be appreciated!

Just noticed I could do $response->json() to get what I wanted.

Related

How do I get a POD image from an API call

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];

PHP: Cancel/Delete Subscription Not working in MTN DEP

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);

Curl to PHP with array, probably simple answer

I'm new to curl in PHP... and I was just wondering how to transform this curl command into PHP:
curl https://ancient-test.chargebee.com/api/v1/portal_sessions \
-u test_rdsfgfgfddsffds: \
-d customer[id]="EXAMPLE" \
-d redirect_url="https://yourdomain.com/users/3490343"
Right now I've got:
$post_data['customer']['id'] = "EXAMPLE";
$post_data['redirect_url'] = "http://" . SITE_URL . "/myaccount/";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://ancient-test.chargebee.com/api/v1/portal_sessions");
curl_setopt($ch,CURLOPT_USERPWD,"test_rdsfgfgfddsffds:");
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
$output = curl_exec($ch);
curl_close($ch);
But I get the error message:
{"errors":[{"message":"There were errors while submitting"},{"param":"customer[id]","message":"cannot be blank"}]}
Thanks for your help!
Jan
https://github.com/CircleOfNice/CiRestClientBundle
This one has a beautiful api.
$client->post($url, $payload, $options);
Using curl here's probably the answer Posting with PHP and Curl, deep array
$post_data['customer[id]'] = "EXAMPLE";
Guzzle is an awesome HTTP client library wrapping curl in PHP that will make your life way easier :)
With guzzle v6 your php code would look like this :
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'https://ancient-test.chargebee.com/api/v1/portal_sessions', [
'auth' => ['test_rdsfgfgfddsffds', 'password'],
'json' => [customer => [id => 'EXAMPLE']]
]);

Get a cURL command from the PHP's object

Is it possible to get the cURL command from the PHP's object? I mean, make this:
$ch = curl_init('http://'.$host . $url);
//...
$response = curl_exec($ch);
Look like this:
curl -X POST -d http://www.google.com/
Is it possible? Is there a trick or a native method?
It's not possible to get the command line equivalent (options) to execute the tool curl from the PHP library cURL.
Both tool and PHP library use libcurl to perform client-side URL transfers, which is a C library. But that's all. Very likely you have a PHP equivalent for most of curl options available in cURL, however, it's not a rule.
I don't think you simply would like to do requests from your application using curl, if you want so, you'd be using PHP library's. That said, there is no easy way to get what you want. Probably you'll need to build the command as a string. Something like this:
function getCurlCommand($url, $method = 'GET', array $params = null /* , ... */ )
{
$cmd = 'curl';
$params = [];
if ($method !== 'GET') {
$params[] = '-X ' . $method;
}
if ($data !== null) {
$params[] = '-d ' . http_build_query($data);
}
// ...
return $cmd . ' ' . implode(' ', $params) . ' ' . $url;
}

Guzzle passing multiple dimension array

My cURL request looks like:
http://httpbin.org/post -d '{"multifilter":{"limit":5}}'
My Guzzle code:
$request = $client->createRequest('POST', 'http://httpbin.org/post');
$postBody = $request->getBody();
$postBody->setField('multifilter', array("limit"=>"5"));
$response = $client->send($request);
This line
$postBody->setField('multifilter', array("limit"=>"5"));
is not correct, but how to set variable as array ?
Or maybe exist something to add json query ? I mean something like addJsonquery('multifilter":{"limit":5}}') ?
solution is add json to body
$request = $client->createRequest('POST', $url, [
'body' => $json,
]);
$response = $client->send($request);
Answer in github:
github.com/guzzle/guzzle/issues/1027

Categories