Tried to made an POST request using Guzzle - laravel

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

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?

Laravel 8 - Get value from api json response

I am trying to get the value from 'title' in an API JSON response in Laravel 8.
{
"kind": "search#companies",
"page_number": 1,
"items_per_page": 20,
"total_results": 1,
"items": [
{
"kind": "searchresults#company",
"links": {
"self": "/company/13082103"
},
"title": "BITPIX LIMITED",
}
],
"start_index": 0
}
The call is setup and it works as expected but I am unsure how to get the variable.
The call will only ever return 1 response within items[] as the search is based on id.
Here is my method
$company = Auth::user()->companies()->first();
$apiKey = env("COMPANIES_HOUSE");
$query = $request->validate([
'query' => 'required',
]);
$response = Http::withHeaders([
'Authorization' => 'Basic ' . $apiKey,
'Connection' => 'keep-alive',
'Accept-Encoding' => 'gzip, deflate, br',
'Accept' => '*/*'
])->get('https://api.companieshouse.gov.uk/search/companies?q=' . $query['query']);
$data = json_decode($response->body());
//dd($data);
$provider = $company->providers()->create([
'name' => $data['items'][0]->title
]);
which produces this error:
Cannot use object of type stdClass as array relating to the ->create line
Many thanks for any help you can provide.
you have to decode the json you have recieved then extract the data you want:
$value = '{ "kind": "search#companies", "page_number": 1, "items_per_page": 20, "total_results": 1, "items": [{ "kind": "searchresults#company", "links": { "self": "/company/13082103" }, "title": "BITPIX LIMITED" }], "start_index": 0 }';
$decodeValue = json_decode($value);
$firstTitle = $decodeValue->items[0]->title; // first title is BITPIX LIMITED

How to send image API From laravel to slim

I have an API created by SLIM to save an image client side.
this is my controller code
$response = Http::withOptions([
'verify' => false,
])->post('http://localhost/events_platforma/create/event
', [
"title" => $request->title,
"alias" => $request->alias,
"description" => $request->description,
"image" => $request->file('image'),
"status" => $request->status,
]);
And it through back error when i return that response
When i use with Postman it work fine and saves a file but when it from Laravel app it give that error
Everything is given in the docs. use attach()
$response = Http::withOptions([
'verify' => false,
])->attach(
'image', $request->file('image'), "image" . $request->file('image')->getClientOriginalExtension();
)->post('http://localhost/events_platforma/create/event', [
"title" => $request->title,
"alias" => $request->alias,
"description" => $request->description,
"status" => $request->status,
]);
2nd Approach
$response = Http::withOptions([
'verify' => false,
'multipart' => [
[
'name' => 'image',
'contents' => $request->file('image')
]]
])->post('http://localhost/events_platforma/create/event
', [
"title" => $request->title,
"alias" => $request->alias,
"description" => $request->description,
"status" => $request->status,
]);

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