How can I create the curl request exactly as a guzzle? - laravel

I have a curl request like below I'm trying to convert it to guzzle but when I send a request to cloudflare it keeps returning me an error. "decoding error" Is there a bug in my guzzle request? Normal curl request should be stable.
`curl \
-X POST \
-d '{"url":"https://storage.googleapis.com/zaid-test/Watermarks%20Demo/cf-ad-original.mp4","meta":{"name":"My First Stream Video"}}' \
-H "Authorization: Bearer <API_TOKEN>" \
https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/stream/copy`
My codes are available below.
$response = $client->request('POST', 'https://api.cloudflare.com/client/v4/accounts/' . $accountId . '/stream/copy', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
'form_params' => [
"url" => "https://storage.googleapis.com/zaid-test/Watermarks%20Demo/cf-ad-original.mp4",
"meta" => [
"name": "My First Stream Video"
]
]

Try setting the content type header as well.
$response = $client->request('POST', 'https://api.cloudflare.com/client/v4/accounts/' . $accountId . '/stream/copy', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
'form_params' => [
"url" => "https://storage.googleapis.com/zaid-test/Watermarks%20Demo/cf-ad-original.mp4",
"meta" => [
"name": "My First Stream Video"
]
]

This answer is using Laravel's HTTP request.
Http::withBody('{"url":"https://storage.googleapis.com/zaid-test/Watermarks%20Demo/cf-ad-original.mp4","meta":{"name":"My First Stream Video"}}')
->withToken('<API_TOKEN>')
->post('https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/stream/copy');
Also, check this amazing tool owned by Shift
https://laravelshift.com/convert-curl-to-http

This is how I found the solution. If anyone has problems, they can use this.
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => [
"url" => "https://storage.googleapis.com/zaid-test/Watermarks%20Demo/cf-ad-original.mp4",
"meta" => [
"name": "My First Stream Video"
]
]

Related

Cannot send an empty message 50006 when using multipart Laravel Http post

I am getting this error when trying to send a message to a Discord webhook.
{"message": "Cannot send an empty message", "code": 50006}
I've read the discord documentation on sending images, and can honestly not see what I'm doing wrong.
Here's the code I'm running:
Http::withHeaders([
'Content-Type' => 'multipart/form-data; boundary=--abcdefghijklmnop'
])
->asMultipart()
->post(
$this->webhookUrl,
[
[
'name' => 'payload_json',
'contents' => '{
"content": "Hello, World!",
"embeds": [{
"title": "Hello, Embed!",
"description": "This is an embedded message.",
"thumbnail": {
"url": "attachment://image1.jpg"
},
"image": {
"url": "attachment://image2.jpg"
}
}],
"attachments": [{
"id": 0,
"description": "Image of a cute little cat",
"filename": "image1.jpg"
}, {
"id": 1,
"description": "Rickroll gif",
"filename": "image2.jpg"
}]
}',
'headers' => [
'Content-Type' => 'application/json',
]
],
[
'name' => 'image1.jpg',
'contents' => 'data:image/jpeg;base64,[[encoded image]]',
'headers' => [
'Content-Type' => 'image/jpeg',
]
],
[
'name' => 'image2.jpg',
'contents' => 'data:image/jpeg;base64,[[encoded image]]',
'headers' => [
'Content-Type' => 'image/jpeg',
]
]
];
);
As you can see, this is basically the message they use in their documentation as an example and I've just translated it to be sent with the Http facade.
What am I missing?

Tried to made an POST request using Guzzle

Im so new using API in my project, so i tried to make an POST request using Guzzle in Laravel, but i really dont know to do it, i've been seraching on the internet how to but i can't find the answer, here's what i've been tried:
$headers = [
'Content-Type' => 'application/json',
'signature' => '73ceef837b9be3cf098eca4a4697bd6a36718b64b0cf407c4324415941ff9780',
'va' => '0000002298436631',
'timestamp', '20191209155701'
];
$body = '{
"name": "Dudy",
"phone": "082298436631",
"email": "muhammadmaududy4#gmail.com",
"amount": "10000",
"notifyUrl": "https://mywebsite.com",
"expired": "24",
"expiredType": "hours",
"comments": "Catatan",
"referenceId": "1",
"paymentMethod": "qris",
"paymentChannel": "qris"
}';
$request = new Request('POST', 'https://sandbox.ipaymu.com/api/v2/payment/direct',
$headers, $body);
And i tried to do it on postman and its work perfectly, here's the setting on my postman:
You can use Laravel's Http Facade to deal with requests (easier to test later, if needed):
$headers = [];
$body = [];
$request = Http::send(
method: 'POST',
url: 'https://your.url/',
options: [
'headers' => $headers,
'form_params' => $body,
]
);
$response = Http::withHeaders([
'X-First' => 'foo',
'X-Second' => 'bar'
])->post('http://example.com/users', [
'name' => 'Taylor',
]);
I show a example code on top. I provide your code below.
$response = Http::withHeaders ([
'Content-Type' => 'application/json',
'signature' => '73ceef837b9be3cf098eca4a4697bd6a36718b64b0cf407c4324415941ff9780',
'va' => '0000002298436631',
'timestamp', '20191209155701'
])->post('https://sandbox.ipaymu.com/api/v2/payment/direct',[
"name": "Dudy",
"phone": "082298436631",
"email": "muhammadmaududy4#gmail.com",
"amount": "10000",
"notifyUrl": "https://mywebsite.com",
"expired": "24",
"expiredType": "hours",
"comments": "Catatan",
"referenceId": "1",
"paymentMethod": "qris",
"paymentChannel": "qris"
]);
Try this
$client = new \GuzzleHttp\Client();
$response = $client->post(
'https://sandbox.ipaymu.com/api/v2/payment/direct',
[
'form_params' => [
"name" => "Dudy",
"phone" => "082298436631",
"email" => "muhammadmaududy4#gmail.com",
"amount" => "10000",
"notifyUrl" => "https://mywebsite.com",
"expired" => "24",
"expiredType" => "hours",
"comments" => "Catatan",
"referenceId" => "1",
"paymentMethod" => "qris",
"paymentChannel" => "qris"
]
],
[
'headers' => [
'Content-Type' => 'application/json',
'signature' => '73ceef837b9be3cf098eca4a4697bd6a36718b64b0cf407c4324415941ff9780',
'va' => '0000002298436631',
'timestamp', '20191209155701'
]
]
);
dd($response) //response data

How to set proxy in Http request in Laravel 7?

Below is my successful HTTP request on DEV environment:
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Accept' => 'application/json'
])
->withToken('xxxxxxxxxxxxxx')
->post('https://xxxxxxxxx.com/v0.1/messages/', [
'from' => [
'type' => 'xxxx',
'number' => 'xxxxxxxx',
],
'to' => [
'type' => 'xxxxx',
'number' => 'xxxxxx',
],
'message' => [
'content' => [
'type' => 'text',
'text' => 'test message from laravel'
]
]
]);
But on production its mandatory to add a proxy to the request.
Anyone have any idea how to pass a proxy with the request above ?
Thank you in advance.
You can specify Guzzle options using the withOptions method.
Hence:
$response = Http::withOptions([
'proxy' => 'http://username:password#proxyhost.com:7000'
])->withHeaders( ...

How to pass the Zoho-oauthtoken in the Header using Guzzle on Laravel?

I have this cURL that I want to convert for Guzzle
curl_setopt_array($curl, array(
CURLOPT_URL => "https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"{\n \"plan\": {\n \"plan_code\": \"AM-001\",\n \"price\": " . $gPrice . ",\n \"tax_id\": \"1786305000000842230\",\n },\n \"addons\": [\n {\n \"addon_code\": \"AB-001\",\n \"addon_description\": \"Ads Budget\",\n \"price\": " . $bPrice . ",\n\n }\n ],\n \"coupon_code\": \"150-credit\"\n \n}",
CURLOPT_HTTPHEADER => array(
"X-com-zoho-subscriptions-organizationid: " . $org_id,
"Authorization: Zoho-oauthtoken " . $accessToken,
"Content-Type: application/x-www-form-urlencoded"
),
));
For now, I have convert this :
$headers = [
'Authorization' => 'Zoho-oauthtoken ' . $access_token,
'X-com-zoho-subscriptions-organizationid' => $org_id,
];
$res = $client->request('POST', 'https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription', $headers, [
'plan' => [
'plan_code' => 'AM-001',
'price' => $data['finaltotal'],
'tax_id' => '1786305000000842230',
],
'addons' =>[
'addon_code' => 'AB-001',
'addon_description' => 'Ads Budget',
'price' => $data['finalads']
],
'coupon_code' => '150-credit'
]);
But I have
"Client error: POST https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription resulted in a 401 Unauthorized response:
{"code":14,"message":"Invalid value passed for authtoken."}"
Have I correctly defined the header?
Thank you for your help.
third option is options for request, So if you need to pass headers you need to specify key headers.
so your code should look like this
$options = [
'headers' => [ // <- here :)
'Authorization' => 'Zoho-oauthtoken ' . $access_token,
'X-com-zoho-subscriptions-organizationid' => $org_id,
];
]
$res = $client->request(
'POST',
'https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription',
$options, // <- options
[
'plan' => [
'plan_code' => 'AM-001',
'price' => $data['finaltotal'],
'tax_id' => '1786305000000842230',
],
'addons' =>[
'addon_code' => 'AB-001',
'addon_description' => 'Ads Budget',
'price' => $data['finalads']
],
'coupon_code' => '150-credit'
]
);
try this it should work.
if any doubt please comment.

Guzzle POST request always returns 400 Bad Request

I have been trying to make a simple POST request to an endpoint with a payload using Guzzle but I always get 400 Bad Request returned.
I can make the same request in Postman and it works. Also, If I make the request using cURL it works.
Can anyone tell from my code what I am doing wrong?
Here's the original cURL request:
curl "https://endpoint.com/" \
-H "Authorization: ApiKey pp_test_*********" \
--data '{
"shipping_address": {
"recipient_name": "Deon Botha",
"address_line_1": "Eastcastle House",
"address_line_2": "27-28 Eastcastle Street",
"city": "London",
"county_state": "Greater London",
"postcode": "W1W 8DH",
"country_code": "GBR"
},
"customer_email": "email£example.com",
"customer_phone": "123455677",
"customer_payment": {
"amount": 29.99,
"currency": "USD"
},
"jobs": [{
"assets": ["http://psps.s3.amazonaws.com/sdk_static/1.jpg"],
"template_id": "i6_case"
}, {
"assets": ["http://psps.s3.amazonaws.com/sdk_static/2.jpg"],
"template_id": "a1_poster"
}]
}'
And the Postman PHPHttp Request which works too.
<?php
$request = new HttpRequest();
$request->setUrl('https://endpoint.com/');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'cache-control' => 'no-cache',
'Connection' => 'keep-alive',
'Content-Length' => '678',
'Accept-Encoding' => 'gzip, deflate',
'Host' => 'api.kite.ly',
'Cache-Control' => 'no-cache',
'Accept' => '*/*',
'User-Agent' => 'PostmanRuntime/7.19.0',
'Content-Type' => 'text/plain',
'Authorization' => 'ApiKey pk_test_*******'
));
$request->setBody(' {
"shipping_address": {
"recipient_name": "Deon Botha",
"address_line_1": "Eastcastle House",
"address_line_2": "27-28 Eastcastle Street",
"city": "London",
"county_state": "Greater London",
"postcode": "W1W 8DH",
"country_code": "GBR"
},
"customer_email": "email#example.com",
"customer_phone": "12345667",
"customer_payment": {
"amount": 29.99,
"currency": "USD"
},
"jobs": [{
"assets": ["http://psps.s3.amazonaws.com/sdk_static/1.jpg"],
"template_id": "i6_case"
}, {
"assets": ["http://psps.s3.amazonaws.com/sdk_static/2.jpg"],
"template_id": "a1_poster"
}]
}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
But when I try to send make the same request with Guzzle it fails with 400 Bad Request and I can't understand why.
$data = [
"shipping_address" => [
"recipient_name" => "Deon Botha",
"address_line_1" => "Eastcastle House",
"address_line_2" => "27-28 Eastcastle Street",
"city" => "London",
"county_state" => "Greater London",
"postcode" => "W1W 8DH",
"country_code" => "GBR"
],
"customer_email" => "example#email.com",
"customer_phone" => "+44 (0)784297 1234",
"customer_payment" => [
"amount" => 29.99,
"currency" => "USD"
],
"jobs" =>
[
"assets" => ["http://psps.s3.amazonaws.com/sdk_static/1.jpg"],
"template_id" => "i6_case"
]
];
$options = json_encode($data);
$response = $client->request('POST', config('services.endpoint.com'),
['headers' => ["Authorization" => config('services.endpoint.com.public_key'),
'Content-Type' => "application/json"], $options]);
If anyone can help me to debug this I'd be really grateful.
If you're using Guzzle 6 (and you probably should be), you're actually constructing in a more complex way than you need to, such that the endpoint is not receiving the expected JSON. Try this instead:
$client = new Client([
'base_uri' => 'https://my.endpoint.com/api',
'headers' => [
'Accept' => 'application/json',
...other headers...
]
]);
$data = [...your big slab of data...];
$response = $client->post('/kitely/path', ['json' => $data]);
// a string containing the results, which will depend on the endpoint
// the Accept header says we will accept json if it is available
// then we can use json_decode on the result
$result = $response->getBody()->getContents();
I'm using Unirest to make any sort of HTTP requests. I tried using Guzzle, but was facing the same issue as you are.
So what I did was install Unirest in my project, all the process are given in details in their documentation. This works perfectly fine for me.

Resources