guzzle undefined function getStatusCode() - php

My code is as follows:
require_once $DOCUMENT_ROOT.'/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
...
if($token!='' && $email!='')
{
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://graph.microsoft.com/v1.0/me/sendmail', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json;odata.metadata=minimal;odata.streaming=true'
],
'body' => $email
]);
if($response.getStatusCode() === 201) {
exit('<h1>Email sent, check your inbox</h1>');
} else {
exit('<h2>There was an error sending the email.</h2> Status code: ' . $response.getStatusCode());
}
}
I keep getting an error Call to undefined function getStatusCode().
I know I need to add another use, but I have tried everything and can't get it to work, same error every time.

Fixed it. Copied the code from Microsoft, it is supposed to be:
if($response->getStatusCode() === 202)
Also it is 202 not 201 for success

Related

why i am getting this error ??GuzzleHttp\Exception\ClientException with message 'Client error: `401 Unauthorized`

I am trying to implement Paypal Sandbox in my project. I have created a trait inside the app folder:
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
public function makeRequest(
$method,
$requestUrl,
$queryParams = [],
$formParams = [],
$headers = [],
$isJsonRequest=false
) {
$client = new Client([
'base_uri' => $this->baseUri,
]);
if (method_exists($this, 'resolveAuthorization')) {
$this->resolveAuthorization($queryParams, $formParams, $headers);
}
$response = $client->request($method, $requestUrl, [
$isJsonRequest ? 'json' : 'form_params' => $formParams,
'headers' => $headers,
'query' => $queryParams,
]);
$response = $response->getBody()->getContents();
if (method_exists($this, 'decodeResponse')) {
$response = $this->decodeResponse($response);
}
return $response;
}
}
I have also created the Paypal Services:
use App\Traits\ConsumesExternalServices;
class PaypalServices
{
use ConsumesExternalServices;
protected $baseUri;
protected $clientId;
protected $clientSecret;
public function __construct()
{
$this->baseUri = config('services.paypal.base_uri');
$this->clientId = config('services.paypal.client_id');
$this->clientSecret = config('services.paypal.client_secret');
}
public function resolveAuthorization(&$queryParams, &$formParams, &$headers)
{
$headers['Authorization']=$this->resolveAccessToken();
}
public function decodeResponse($response)
{
return json_decode($response);
}
public function resolveAccessToken()
{
$credentials = base64_encode("{$this->clientId} : {$this->clientSecret}");
return "Basic {$credentials}";
}
}
I am trying to integrate my sandbox account with my project but whenever I use tinker and try to make a request, I get the following error:
Psy Shell v0.10.8 (PHP 7.4.15 — cli) by Justin Hileman
>>> $paypal=new App\Services\PaypalServices;
=> App\Services\PaypalServices {#3473}
>>> $paypal->makeRequest('GET','v1/invoicing/invoices');
GuzzleHttp\Exception\ClientException with message 'Client error: `GET https://api-m.sandbox.paypal.com/v1/invoicing/invoices` resulted in a `401 Unauthorized` response:{"error":"invalid_client","error_description":"Client Authentication failed"}
I have no idea what is the problem. Laravel version is 8 and I am using Paypal Malaysia account.
I have mentioned in .env file:
PAYPAL_BASE_URI=https://api-m.sandbox.paypal.com
PAYPAL_CLIENT_ID=
PAYPAL_CLIENT_SECRET=
Inside my config/servies.php file:
'paypal' => [
'base_uri' => env('PAYPAL_BASE_URI'),
'client_id' => env('PAYPAL_CLIENT_ID'),
'client_secret' => env('PAYPAL_CLIENT_SECRET')
],
What client-id are you using? is it sandbox? If you use a live one with the base_uri set to sandbox, it will error with that 401. You need a valid clientid+secret for the environment you're testing in, from your REST apps. If you still have issues, create a new REST app there and ensure you copy-paste from it correctly.

laravel and guzzle auth

Hi i want to consume a service and i use laravel 5.x with guzzle with this code i can send request and i use the correct api-key but i always obtain 403 forbidden....
public function searchP(Request $request) {
$targa = request('targa');
$client = new \GuzzleHttp\Client();
$url = 'https://xxx.it/api/xxx/xxx-number/'.$targa.'/xxx-xxxx';
$api_key ='xxxxxcheepohxxxx';
try {
$response = $client->request(
'GET',
$url,
['auth' => [null, $api_key]]);
} catch (RequestException $e) {
var_dump($e->getResponse()->getBody()->getContent());
}
// Get JSON
$result = $response->json();
}
Why? I cannot understand
In postman i write in the AUTHORIZATION label this
key : x-apikey
value: xxxxxcheepohxxxx
Add to header
and it works.
i also tried this
.... try {
$response = $client->request('GET',$url,[
'headers' => [
'x-apikey', $api_key
]
]);
} catch .....
but doesn't work
Thx
it should be this, you have a typo
.... try {
$response = $client->request('GET',$url,[
'headers' => [
'x-apikey'=> $api_key
]
]);
} catch .....

Call to undefined function GuzzleHttp\Psr7\get_message_body_summary()

I am trying to perform CURL get request in guzzlehttp to check if a user exists in a CRM. Whenever I try to perform the request I get the following error in the title, I haven't been able to find any resources online for this specific problem. Any ideas would be super helpful, if you require any additional info please let me know in the comments.
Included packages:
require(__DIR__ . "/../../vendor/autoload.php");
require_once(__DIR__ . "/../../helpers/Validation.php");
use Symfony\Component\Dotenv\Dotenv;
use GuzzleHttp\Client;
use GuzzleHttp\Request;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Psr7;
use GuzzleHttp\Stream\Stream;
use Drupal\Core\Site\Settings;
// Load our environment variables
$dotenv = new Dotenv();
$dotenv->load(__DIR__ . "/../../.env");
private function checkDuplicate() {
// If no errors we can submit the registrant
// \Drupal::logger('signup')->notice("access token", print_r($this->_accessToken, TRUE));
if(!$this->_errors) {
$checkNewUser = new Client();
try {
$options = [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => "Bearer " . $this->_accessToken
],
"query" => '$filter=email%20eq%20"' .$this->_email . '"&$fields=Contact Key,First Name,Last Name'
];
$result = $checkNewUser->get($_ENV['REST_API_URL'], $options);
} catch (RequestException $e) {
\Drupal::logger('signup')->error("error " . print_r($e->getRequest(), TRUE));
if ($e->hasResponse()) {
\Drupal::logger('signup')->error("error " . print_r($e->getRequest(), TRUE));
echo $e->getRequest() . "\n";
\Drupal::logger('signup')->error("error " . print_r($e->getResponse(), TRUE));
}
}
}
I have a post request function to gain an access token that works correctly.
private function getAccessToken() {
try {
$requestAccessToken = new Client();
$options = [
'headers' => [
'Accept' => 'application/json',
],
"form_params" => [
"grant_type" => "client_credentials",
"client_id" => $_ENV["CLIENT_ID"],
"client_secret" => $_ENV["CLIENT_SECRET"]
]
];
$result = $requestAccessToken->post($_ENV['CLIENT_API_URL'], $options);
return (string) $result->getBody();
}
catch(Exception $error) {
\Drupal::logger('signup')->error("error " . $error-getMessage());
}
}
The issue was caused due to guzzlehttp being directly supported in drupal-8, caused a confliction with the package installed via composer.
After removing composer libraries for guzzle and use the following documentation:
https://www.drupal.org/docs/8/modules/http-client-manager/introduction

Guzzle - 400 Bad Request` response: {"error":"invalid_client"} - when making token request

I'm trying to make a token request using guzzle and receive an error "400 Bad Request` response: {"error":"invalid_client"}". I can make the same request with cURL and HTTP_Request2 with no problem.
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
session_start();
if(isset($_GET['code'])){
$code = $_GET['code'];
$encodeB64 = base64_encode('{clientID}:{clientSecret}');
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'https://identity.reckon.com/connect/token',[
['headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],['Authorization' => 'Basic '.$encodeB64]],
['body' => ['grant_type' => 'authorization_code'],['code' => $code],['redirect_uri' => '{redirectURI}']]
]);
$body = $response->getBody();
echo $body;
}
These are the details of how to make a token request with this API:
URL: https://identity.reckon.com/connect/token
Type: POST
Body: grant_type=authorization_code&code={code}&redirect_uri={redirect url}
Headers:
Content-Type = application/x-www-form-urlencoded
Authorization: Basic{client id:client secret encoded in base64}
Not sure where I'm going wrong.
I have worked it out. The answer was the following:
<?php
require 'C:/Users/Shane/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
session_start();
if(isset($_GET['code'])){
$code = $_GET['code'];
$encodeB64 = base64_encode('{client id}:{client secret}');
$authbody = 'grant_type=authorization_code&code='.$code.'&redirect_uri={redirect url}';
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'https://identity.reckon.com/connect/token',['headers' =>
['Content-Type' => 'application/x-www-form-urlencoded','Authorization' => 'Basic '.$encodeB64],
'body' => $authbody]);
$body = $response->getBody();
echo $body;
I have recently gone through {"error":"invalid_client"} with Guzzle, the error actually tells you specifically if something wrong with clientId or clientSecret. In my case I had first letter of clientSecret capitalized. It took a while to figure it out.

Laravel 5.0 Socialite with Wunderlist

I've created a custom Provider for Laravel Socialite.
The authentication part is going well until i'll try to call the user method.
Not sure what's going wrong.
Method documentation at wunderlist
My code:
/**
* {#inheritdoc}
*/
protected function getUserByToken($token)
{
$response = $this->getHttpClient()->get('https://a.wunderlist.com/api/v1/users', [
'X-Access-Token: ' . $token . ' X-Client-ID: ' . $this->clientId
]);
return json_decode($response->getBody(), true);
}
I get the following error:
InvalidArgumentException in MessageFactory.php line 202:
allow_redirects must be true, false, or array
Do i miss things in the options array?
Jos
Actually socialite is not supposed to do something like this. But instead you may use Guzzle. There is a good video at laracasts. Just search for Easy HTTP Requests. And here's the code that you may use for guzzle:
$client = new \Guzzle\Service\Client('a.wunderlist.com/api/v1/');
$response = $client->get('user')->send();
// If you want this response in array:
$user = $response->json();
Just read the docs here.
When using this with straight forward curl there is no issue.
As far as i can see the issue lies in the headers i'll parse.
The following solution is something i can live with, although it's not perfect.
$headers = array();
$headers[] = 'X-Access-Token: ' . $token;
$headers[] = 'X-Client-ID: ' . $this->clientId;
$response = $this->getHttpClient()->get('a.wunderlist.com/api/v1/user', [
'config' => [
'curl' => [
CURLOPT_POST => 0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false
]
]
]);
return json_decode($response->getBody(), true);

Categories