Laravel problem with parameter in GuzzleHttp - php

Hello
When I use GuzzleHttp\Client is working fine but form_params not working but It was working with me in another project but this project no params working with me when I send it in form_params
Guzzle Code working
$http = new Client;
try {
$response = $http->post('https://smsmisr.com/api/webapi/?username='.$this->username.'&password='.$this->password.'&language=1&sender='.$this->sender.'&mobile=XXXX&message=Hello&DelayUntil='.Carbon::now()->toDateTimeString());
// retrun json_decode((string)) $response->getBody(), true);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if($e->getCode() === 400) {
return response()->json('Invalid Request.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your username and passowrd are incorrect', $e->getCode());
}
return response()->json('Something went wrong on the server', $e->getCode());
}
Guzzle Code not working
the code no sends any form_params yet.
$response = $http->post($this->link, [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
],
'form_params' => [
'username' => $this->username,
'password' => $this->password,
'sender' => $this->sender,
'language' => 1,
'mobile' => 'XXXXXXX',
'message' => 'Hello guys',
'DelayUntil' => Carbon::now()->toDateString()
]
]);
This problem in my Vuejs too when using Axios I should make
s
ubmitForm(context, data) {
const params = {
...data
}
return new Promise((resolve, reject) => {
axios.post(`${data.post.apiURL}`, params)
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
})
})
},
I testing on PostMan.

From the docs here
form_params cannot be used with json:
form_params cannot be used with the multipart option. You will need to use one or the other. Use form_params for application/x-www-form-urlencoded requests, and multipart for multipart/form-data requests.
This option cannot be used with body, multipart, or json

Try this bro, change "form_params" to "json"
$response = $http->post($this->link, [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
],
'json' => [
'username' => $this->username,
'password' => $this->password,
'sender' => $this->sender,
'language' => 1,
'mobile' => 'XXXXXXX',
'message' => 'Hello guys',
'DelayUntil' => Carbon::now()->toDateString()
] ]);

Related

Coinbase Invalid 404 request OAuth2 Guzzle

I try make authorization in coinbase with OAuth2:
$client = new Client(['cookies' => true]);
try {
$response = $client->request('POST', $this->urlAccessToken, [
'headers' => [
'cache-control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $request->code,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectUri
]
]);
dd($response->getBody());
} catch (\Exception $e) {
return response($e->getMessage(), 400);
}
After authorization in coinbase him me redirect to redirect URI and when send request exchange code i see bad response:
Client error: POST http://www.coinbase.com/oauth/token resulted in a 404 Not Found response: Invalid request. Instead of a GET request, you should be making a POST with valid POST params. For more informat (truncated...)
All code which will authorize in Coinbase:
private $clientId;
private $clientSecret;
private $redirectUri;
private $urlAuthorize;
private $urlAccessToken;
public function __construct()
{
$this->clientId = env('COINBASE_CLIENT_ID');
$this->clientSecret = env('COINBASE_CLIENT_SECRET');
$this->redirectUri = route('oauth2-redirect');
$this->urlAuthorize = 'https://www.coinbase.com/oauth/authorize';
$this->urlAccessToken = 'http://www.coinbase.com/oauth/token';
}
public function oauth(Request $request)
{
$state = hash('sha256', $request->session()->getId());
if (!isset($request->code)) {
$parameters = [
'response_type' => 'code',
'client_id' => $this->clientId,
'redirect_uri' => $this->redirectUri,
'state' => $state
];
$authorizationUrl = $this->urlAuthorize . '?' . http_build_query($parameters);
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
} elseif (empty($request->state) || $request->state !== $state) {
return response('Invalid state', 400);
} else {
$client = new Client(['cookies' => true]);
try {
$response = $client->request('POST', $this->urlAccessToken, [
'headers' => [
'cache-control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $request->code,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectUri
]
]);
dd($response->getBody());
} catch (\Exception $e) {
return response($e->getMessage(), 400);
}
}
}
Also i checked it in postman and him return good response:
enter image description here
Problem was in URL access token, need use https://api.coinbase.com/oauth/token instead http://www.coinbase.com/oauth/token.

Laravel sending post request with guzzle http request

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",
}
}
}
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']),
]);
$current_timestamp = Carbon::now()->timestamp;
$client = new Client();
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::JSON => [
'headers' => [
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
],
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
]
]
]);
$response = $request->getBody();
$r = json_decode($response);
dd($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
}
Can someone tell me why in Postman everything works fine but in laravel It fails?
What is wrong with my code?
Because you wrote headers inside json option. here is the correct one
$client = new Client();
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
\GuzzleHttp\RequestOptions::HEADERS => [
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
],
]);
You can use it like
$client->request('POST', 'app3.salesmanago.pl/api/contact/upsert', [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
'headers' => [
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
'requestTime' => $current_timestamp,
'owner' => 'testemail#wp.com',
]
]);

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
}

How can I get response from guzzle in Laravel 5.3

I try like this :
$client = new Client();
$res = $client->request('POST', 'https://api.orange.com/smsmessaging/v1/outbound/tel:+phone/requests/', [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization'=>'Bearer '.$token,
/*'Content-Type' => 'application/x-www-form-urlencoded',*/
],
/*'form_params' => $body ,*/
'json' => [
'outboundSMSMessageRequest'=>[
'address'=> 'tel:+$phone',
'senderAddress'=>'tel:+phone_rec',
'outboundSMSTextMessage'=>[
'message'=> 'Hello test!'
]
]],
'debug' => true,
'verify' => false,
]
);
$res->getStatusCode();
// 200
$res->getHeader('content-type');
// 'application/json; charset=utf8'
$res->getBody();
When executed, the result is an errror curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE*
How can I get the response?
I try in postman, it success get response
But I try use guzzle, it failed
You can try code below:
try {
$client = new Client();
$token = 'token';
$res = $client->request('POST', 'https://api.orange.com/smsmessaging/v1/outbound/tel:+phone/requests/', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization'=>'Bearer '. $token,
],
'json' => [
'outboundSMSMessageRequest'=>[
'address'=> "tel:youre-phone",
'senderAddress'=>'tel:+phone_rec',
'outboundSMSTextMessage'=>[
'message'=> 'Hello test!'
]
]],
'debug' => true,
'verify' => false,
]
);
echo $res->getBody();
} catch ( \GuzzleHttp\Exception\ClientException $exception ) {
echo $exception->getResponse()->getBody();
}
I resolved it like this
$requestContent = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization'=>'Bearer '.$token,
],
'json' => [
'outboundSMSMessageRequest'=>[
'address'=> "tel:youre-phone",
'senderAddress'=>'tel:+phone_rec',
'outboundSMSTextMessage'=>[
'message'=> 'Hello test !'
]
]
]
];
try {
$client = new Client();
$res = $client->request('POST', 'https://api.orange.com/smsmessaging/v1/outbound/tel:+phone_rec/requests/', $requestContent);
$response = json_decode($res->getBody());
dd($response);
} catch (RequestException $re) {
}

how fix Authorization Bearer Problem in guzzle

I'm trying to send this request to the server, but with a 401 error
Which part of the code can the problem be?
"guzzle version 6.3"
try {
$urlDoPayment = 'https://api.example.com/v1/pay';
$client = new Client();
try {
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($content);
} catch (GuzzleException $e) {
dd($e->getMessage());
}
} catch (\Exception $exception) {
dd($exception->getCode());
}
The headers in the request are nested in the wrong part of the request options. That should at least fix the 401 error if the token is valid.
Try:
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
// headers should not be here
], // json post body params end
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
This problem solved using this code
$response = $client->request('POST', $urlDoPayment, [
'json' => [
'amount' => 100,
'returnUrl' => "http://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
I suspect that the problem lays in undefined port or protocol. Headers content wasn't an issue for me. I resolved same problem by changing:
115.12.3.44 to 115.12.3.44:80
also tested
115.12.3.44 to http://115.12.3.44
or
google.com to http://google.com

Categories