Send request parameter from console commands laravel - php

How can I send request via console commands in laravel 5.1 ? I need to pass API request to controller in same folder project, my first attempt is using guzzle :
$gClient = new \GuzzleHttp\Client(['base_uri' => env('URL_AUTO_CONFIRM_PAYMENT')]);
$res = $gClient->post('api/payment/inquiries',
[
'headers'=> [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
],
'json'=>[
'payment_method' => 'transfer',
'payment_channel' => 'bca',
'account_number' => $row->parameter['accountNo'],
'invoice_id' => $row->parameter['paymentInvoice'],
'amount' => (int)$row->parameter['totalCommission'],
'currency_code' => 'IDR',
'description' => 'Testing'
],
'http_errors' => false
]
);
but I think its not good because in same folder project, which can I call controller directly, but the problem is, my controller has been set to only receive $request not param (my_controller(Request $request)).
So, how can I handle this ? It is ok using guzzle ? Or should I use another alternative ?
Any advice will appreciate.
Thanks

Make a request instance and pass that to the specific controller method.
use Illuminate\Http\Request;
$request = new Request(
[
'payment_method' => 'transfer',
'payment_channel' => 'bca',
'account_number' => $row->parameter['accountNo'],
'invoice_id' => $row->parameter['paymentInvoice'],
'amount' => (int)$row->parameter['totalCommission'],
'currency_code' => 'IDR',
'description' => 'Testing'
],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json']
);
$response = $controller->edit($request);

Related

How do I pass apikey and other keys to header in guzzle 6.3?

I have a simple registration form that the user can register in my app, now I want to send submitted data to another service.
First I test my request using postman as follows using a raw option in a postman panel.
Api url : app3.salesmanago.pl/api/contact/upsert
JSON DATA:
{
"clientId":"w2ncrw06k7ny45umsssc",
"apiKey":"ssssj2q8qp4fbp9qf2b8p49fz",
"requestTime":1327056031488,
"sha":"ba0ddddddb543dcaf5ca82b09e33264fedb509cfb4806c",
"async" : true,
"owner" : "adam#rce.com",
"contact" : {
"email" : "test-1#konri.com",
"name" : "Test",
"address":{
"streetAddress":"Brzyczynska 123",
}
}
}
UPDATE I get the following success result
{
"success": true,
"message": [],
"contactId": "b52910be-9d22-4830-82d5-c9dc788888ba",
"externalId": null
}
Now using guuzle htpp request in laravel
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$client = new client();
$current_timestamp = Carbon::now()->timestamp;
try {
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
]);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
$status = $request->getStatusCode();
$response = $request->getBody();
$r = json_decode($response);
dd($r);
dd($status, $r );
return $user;
}
When I run my app and send the form data I get this using the same data as in postman I get this
{#306 ▼
+"success": false
+"message": array:1 [▼
0 => "Not authenticated"
]
+"contactId": null
+"externalId": null
}
It seems like my API key and other header data are not passed to the header as required,
Can someone tell me what am I doing wrong here?
Maybe something like this. Notice that according to the API some values should be passed as headers (Accept, and Content-Type -commonly used as headers, btw-), and other values as part of the body. This is the case of the authentication values like clientId and apiKey.
I don't have guzzle 6 installed at hand but you can try and modify the code to include that data not in the headers section of the request but in the body:
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
],
],
]);
I'm not sure about the 'form_params' in under the RequestOptions::JSON, but mabye you can put the values directly under RequestOptions::JSON.
Just FYI, not sure what Laravel you're using but there's now The Laravel HTTP client which make this sooo much easier.
$response = Http::withHeaders([
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
])->post('app3.salesmanago.pl/api/contact/upsert', [
'name' => $data['name'],
'email' => $data['email'],
]);
if($response->successful()){
dd($response->json())
}else{
// handle yo errors
}

Post data and file using Guzzle - PHP & Laravel

I am using guzzle 6.3 to post a file along with some data to my api built on laravel 5.5. When i post the data, i am not able to get the data sent to the api except the file posted.
Client Side
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->request('POST',$url, [
'multipart' => [
[
'name' => 'body',
'contents' => json_encode(['documentation' => 'First Doc', 'recipient' => ['78011951231']]),
'headers' => ['Content-Type' => 'application/json']
],
[
'name' => 'file',
'contents' => fopen('/path/public/media/aaaah.wav', 'r'),
'headers' => ['Content-Type' => 'audio/wav']
],
],
]);
echo($response->getBody()->getContents());
API Controller
if (($Key)) {
return response()->json([
'status' => 'success',
'documenation' => $request->get('documentation'),
'recipient' => $request->get('recipient'),
'file' =>$request->get('file'),
'media'=>$request->hasFile('file')
]);
}
Response
{"status":"error","documentation":null,,"recipient":null,"file":null,"media":true}
Why am i getting NULL returned for the data that i am posting? Could it be because of the file that i am posting ?

PHP Guzzle POST Request Returning Null

I'm racking my brains over this - the request goes fine in Postman, but I can't access the body using Guzzle.
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://apitest.authorize.net/xml/v1/request.api', [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode([
'createTransactionRequest' => [
'merchantAuthentication' => [
'name' => '88VuW****',
'transactionKey' => '2xyW8q65VZ*****'
],
'transactionRequest' => [
'transactionType' => 'authCaptureTransaction',
'amount' => "5.00",
'payment' => [
'opaqueData' => [
'dataDescriptor' => 'COMMON.ACCEPT.INAPP.PAYMENT',
'dataValue' => $_POST['dataValue']
]
]
]
]
])
]);
dd(json_decode($res->getBody()));
The above returns null - no errors, just null. The below is the same request in Postman, successful with a body.
Any ideas would be really appreciated, thanks!
You should use $res->getBody()->getContents().
And json_decode() returns null in case of any error. You have to check them separately (unfortunately) with json_last_error().

Php, Guzzle, Schema validation failed but working in curl

I'm in the process of convert from cURL to Guzzle, and got most of it working.
GET requests working great etc.
My problem is the POST request, getting Schema validation errors.
It works in curl, so I'm a bit confused... well, a lot.
Client error: `POST https://restapi.e-conomic.com/customers` resulted in a `400 Bad Request` response:
{"message":"Schema validation failed.","errorCode":"E00500"
I hope one of you can tell me, if I did something wrong in the convert? Maybe my arrays needs to be formatted in another way.
This is my old working "cURL code":
$data = array(
'name' => 'Test User',
'address' => 'Road 123',
'email' => 'morten#domain.com',
'zip' => '9000',
'city' => 'City',
'country' => 'Danmark',
'corporateIdentificationNumber' => '12345678',
'customerGroup' => array(
'customerGroupNumber' => 1
),
'currency' => 'DKK',
'paymentTerms' => array(
'paymentTermsNumber' => 1
),
'vatZone' => array(
'vatZoneNumber' => 1
)
);
$options = array(
CURLOPT_URL => 'https://restapi.e-conomic.com/customers',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'X-AppSecretToken:[removed]',
'X-AgreementGrantToken:[removed]',
'Content-Type:application/json; charset=utf-8'
),
CURLOPT_POSTFIELDS => json_encode($data)
);
curl_setopt_array($ch, $options);
This is my new "guzzle code", that is causing me problems:
$client = new GuzzleHttp\Client();
$headers = [
'X-AppSecretToken' => '[removed]',
'X-AgreementGrantToken' => '[removed]',
'Content-Type' => 'application/json;charset=utf-8',
'debug' => false
];
$form_params = [
'name' => 'Test User',
'address' => 'Road 123',
'email' => 'test#email.dk',
'zip' => '9000',
'city' => 'City',
'country' => 'Danmark',
'corporateIdentificationNumber' => '12345678',
'customerGroup' => [
'customerGroupNumber' => 1
],
'currency' => 'DKK',
'paymentTerms' => [
'paymentTermsNumber' => 1
],
'vatZone' => [
'vatZoneNumber' => 1
]
];
$response = $client->post('https://restapi.e-conomic.com/customers', [
'headers' => $headers,
'form_params' => $form_params
]);
I tried to use the "body" parameter, as stated in the Guzzle documentation, but received this error:
Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or the "multipart" request option to send a multipart/form-data request.
I'm not sure what to do and really hope, that one of you guys will tell me what i'm doing wrong.
https://restapi.e-conomic.com/schema/customers.post.schema.json#_ga=2.167601086.1488491524.1500877149-796726383.1499933074
https://restdocs.e-conomic.com/#post-customers
I had to post the quest as json:
$response = $client->post('https://restapi.e-conomic.com/customers', [
'headers' => $headers,
'json' => $form_params
]);

Guzzle form_params not accepting array

I am using Guzzle 6 and I can't pass array with form_params in the body of the client
$postFields = [
form_params => [
'data[test]' => "TEST",
'data[whatever]' => "Whatever..."
]
];
$client = new GuzzleClient([
'cookies' => $jar, // The cookie
'allow_redirects' => true, // Max 5 Redirects
'base_uri' => $this->navigateUrl, // Base Uri
'headers' => $this->headers
]);
$response = $client->post('api',[$postFields]);
Finally, when i send the request my data is gone... But if I manually add the the data in the response it's working fine.
$response = $client->post(
'api',
[form_params => [
'data[test]'=>"TEST",
'data[wht]' => 'Whatever'
],
]
// It's working this way...
I hope I am clear enough if u need more info feel free to ask. Thanks in advance.
I see a couple of issues. First is the fact that your $postFields array does not appear to be properly formatted, and second you wrap your $postFields array inside another array.
$options = [
'debug' => true,
'form_params' => [
'test' => 15,
'id' => 43252435243654352,
'name' => 'this is a random name',
],
'on_stats' => $someCallableItem,
];
$response = $client->post('api', $options);

Categories