How to send variable with the guzzle post method - php

I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:
$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
'headers' => ['Content-Type' => 'application/json'],
'body' => '{
"Amount":"i want to send $amount here",
"something":"1",
"Description":"desc",
}'
]);
so every thing is fine and static data is being send but I want to know how can I send a variable.

You can bind the data in form_params parameter like
$client = new \GuzzleHttp\Client();
$amount = $request->get('amount');
$requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
'form_params' => [
"Amount" => "i want to send $amount here",
"something" => "1",
"Description" => "desc",
]
]);
Hope this works for you.

Amount can pass in an array and after you can encode with json using ```json_encode``
Hope this works for you.
$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$url = "http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber";
$data = [
"amount" => $amount,
"something" => "1",
"description" => "desc",
];
$requestAPI = $client->post( $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data);
]);

You can try to use Guzzle json option:
$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$response = $client->post(
'http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber',
[
GuzzleHttp\RequestOptions::JSON => [
'Amount' => $amount,
'something' => '1',
'Description' => 'desc',
]
]
);
Check Guzzle manual - http://docs.guzzlephp.org/en/stable/request-options.html#json

Related

How to Post with request to create new data from form using guzzle - Laravel

I have this function in my controller:
public function store(Request $request)
{
$client = new Client();
$headers = [
'Authorization' => $token,
'Content-Type' => 'application/json'
];
$body = '{
"DocNo": 1167722,
"AOQty": 0,
"TL": [
{
"Key": 11678,
"Code": "Screw Hex",
"Detail": true,
"DTL": []
}
]
}';
$request = new Psr7Request('POST', 'http://example.com/api/Order/', $headers, $body);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();
}
that will store the data to the external API
but i want to POST the data from a form
when i work with normal routing (not API) i usually do this:
'Key' => $request->Key,
how can i achieve the above with guzzle?
currently when i submit the form from the view it will submit the above function (store) as static data, how can i submit the data from the form?
UPDATE:
When i use Http as showing below:
$store = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => $token,
])->post('http://example.com/api/Order/', [
'DocNo' => "SO-000284",
'AOQty' => 0.0,
'TL[Key]' => 11678,
'TL[Code]' => "SCREW HEX CAPHEAD 6X30MM",
'TL[Detail]' => true,
'TL[DTL]' => [],
]);
echo $store;
it will store everything before [TL] Array, it won't store anything of:
'TL[Key]' => 11678,
'TL[Code]' => "SCREW HEX CAPHEAD 6X30MM",
'TL[Detail]' => true,
'TL[DTL]' => [],
am i doing it wrong?
You can use HTTP client provided by Laravel.
$response = Http::withToken($token)->post('http://example.com/users', $request->only(['request_param_1', 'request_param_2']));
Or
$data = [];
$data['param_1'] = $request->get('param_1');
$data['param_2'] = $request->get('param_2');
$data['param_3'] = $request->get('param_3');
$response = Http::withToken($token)->post('http://example.com/users', $data);
Edit
$data = [
'DocNo' => "SO-000284",
'AOQty' => 0.0,
'TL' => [
'key' => 11678,
'Code' => "SCREW HEX CAPHEAD 6X30MM",
'Detail' => true,
'DTL' => [],
]
];
SOLUTION:
Using Http client:
'TL' => array ([
'Dtl' => "",
'Code' => "Screw Hex",
'IsDetail' => true,
"DTL" => [],
])
]);

make the variable as string in laravel

how are you ?
I'm using Guzzle to send post method but when i tried to send the post method with variable getting error so i tried to convert it to sting but still same
this is my current code
if $ mobile value is 55454545445 , them the 'numbers' => "{$mobile}" will be different not "55454545445"
$user = Auth::user();
$mobile = $user->mobile;
$client = new Client();
$booking = Booking::where('id', '=', e($id))->first();
if($booking)
{
$booking->booking_status_id = 3;
$booking->save();
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$data = array('userName' => "test",
'apiKey' => "1",
'numbers' => "{$mobile}",
'userSender' => "sender",
'msg' =>'msg',
'msgEncoding' => "UTF8",);
$dataJson = json_encode($data);
$response = $client->post('https://www.test.test',
['body' => $dataJson]
);
i used this
"0{$mobile}"
instead of
"{$mobile}"
and its work

Payment API Returns AuthenticationFailed Error

I am integrating payments to my app and using PHP-Payments-SDK from Intuit
When creating echeck debit by the following code.
public function echeck(Request $request){
$this->refreshToken();
$record = QuickbookModel::first();
$client = new PaymentClient([
'access_token' => $record->accessToken,
'environment' => "sandbox" // or 'environment' => "production"
]);
$array = [
"bankAccount" => [
"phone" => $request->phone,
"routingNumber" => $request->routingNumber,
"name" => $request->name,
"accountType" => $request->accountType,
"accountNumber" => $request->accountNumber
],
"description" => "Easyfi Testing",
"paymentMode" => "WEB",
"amount" => "5.55",
];
$bank = ECheckOperations::buildFrom($array);
$response = $client->debit($bank);
if($response->failed()){
$code = $response->getStatusCode();
$errorMessage = $response->getBody();
return json_encode(["status" => $code, "message" => $errorMessage]);
}else{
$responseCharge = $response->getBody();
//Get the Id of the charge request
$id = $responseCharge->id;
//Get the Status of the charge request
$status = $responseCharge->status;
return json_encode(["status" => $status, "message" => $responseCharge, "data" => $id]);
}
}
I always getting following error even everything is up to mark including Access Token
{status: 401, message: "{"code":"AuthenticationFailed","type":"INPUT","message":null,"detail":null,"moreInfo":null}"}

Firebase Update Multiple Items

How can I update multiple items on firebase with just one request?
I can not let my system wait to complete multiple requests, so I need to update them with just one.
Current Firebase Data:
PHP Code:
$data = [
'mydata-1' => [
'position' => 1,
],
'mydata-2' => [
'position' => 2,
],
];
$client = new \GuzzleHttp\Client();
$response = $client->put(FIREBASE_ENDPOINT . '/data', [
'json' => $data,
]);
Expected Firebase Data:
Problem:
The request subscribe all my data and I lose the title field.
I also tried PATCH request, but I got the same response.
Based on Frank van Puffelen comment:
$data = [
'mydata-1/position' => 1,
'mydata-2/position' => 2,
];
$client = new \GuzzleHttp\Client();
$response = $client->patch(FIREBASE_ENDPOINT . '/data', [
'json' => $data,
]);
Documentation:
https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html

Can you include raw JSON in Guzzle POST Body?

This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment. All the CURL functions utilise raw JSON variables in the body.
I am trying to create a working Guzzle client but the server is respsonding with 'invalid request' and I am just wondering if something fishy is going on with the JSON I am posting. I am starting to wonder if you can not use raw JSON in the Guzzle POST request body? I know the headers are working as I am receiving a valid response from the server and I know the JSON is valid as it is currently working in a CURL request. So I am stuck :-(
Any help would be sooo greatly appreciated.
$headers = array(
'NETOAPI_KEY' => env('NETO_API_KEY'),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'NETOAPI_ACTION' => 'GetOrder'
);
// JSON Data for API post
$GetOrder = '{
"Filter": {
"OrderID": "N10139",
"OutputSelector": [
"OrderStatus"
]
}
}';
$client = new client();
$res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers ], [ 'body' => $GetOrder ]);
return $res->getBody();
You can send a regular array as JSON via the 'json' request option; this will also automatically set the right headers:
$headers = [
'NETOAPI_KEY' => env('NETO_API_KEY'),
'Accept' => 'application/json',
'NETOAPI_ACTION' => 'GetOrder'
];
$GetOrder = [
'Filter' => [
'OrderID' => 'N10139',
'OutputSelector' => ['OrderStatus'],
],
];
$client = new client();
$res = $client->post(env('NETO_API_URL'), [
'headers' => $headers,
'json' => $GetOrder,
]);
Note that Guzzle applies json_encode() without any options behind the scenes; if you need any customisation, you're advised to do some of the work yourself
$res = $client->post(env('NETO_API_URL'), [
'headers' => $headers + ['Content-Type' => 'application/json'],
'body' => json_encode($getOrders, ...),
]);
Guzzle 7 Here
The below worked for me with raw json input
$data = array(
'customer' => '89090',
'username' => 'app',
'password' => 'pwd'
);
$url = "http://someendpoint/API/Login";
$client = new \GuzzleHttp\Client();
$response = $client->post($url, [
'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
print_r(json_decode($response->getBody(), true));
For some reasons until I used the json_decode on the response, the output wasn't formatted.
You probably need to set the body mime type. This can be done easily using the setBody() method.
$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);
$request->setBody($GetOrder, 'application/json');

Categories