This question already has answers here:
(Updated) Laravel PUT Method Not Working
(2 answers)
Closed 5 years ago.
updated - I am trying to use the API documentation to change the billing date using the PUT method in Http and Guzzle in Laravel, however, the JSON file would return but it will not change the billing date at all.
Reference 1: The official documentation about changing the billing date.
Reference2: their sample code in detail (sorry about the bad formatting):
<?php
$request = new HttpRequest();
$request->setUrl('https://subdomain.chargify.com/subscriptions/subscriptionId.json');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array('content-type' => 'application/json'));
$request->setBody('{"subscription":{"next_billing_at":"2018-12-15"}}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
My code in detail:
public function changeYearlySubscriptionBillingDate(Request $request)
{
$user = $request->user();
$subscriptionId = $user->subscription->subscription_id;
$nextBilling = Carbon::now()->addYear();
$hostname = env('CHARGIFY_HOSTNAME');
$headers = [
'authorization' => 'Basic ANIDIANDIAJIJCQ',
'content-type' => 'application/json'
];
$body = ["subscription" => ["next_billing_at" =>[ $nextBilling ]]];
$config = [
'headers' => $headers,
'form_param' => $body
];
$client = new Client($config);
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json");
echo $res->getBody();
}
Changes this:
echo $response->getBody();
to
dd($response->getBody());
and repost the response data is returned.
Related
I'm trying to make a request with my other endpoint, using GuzzleHttp in laravel, but the token isn't authorizing it. I believe it's in the way I'm going. Anyone know how to fix this? This is my code.
public function productRecommendation($rowPerPage,$keywords, $page){
try{
$request = request();
$token = $request->bearerToken();
$client = new \GuzzleHttp\Client();
$promise = $client->request('GET', $this->sellerUrl.'recommended', [
'headers' => ['Authorization' => "Bearer {$token}"],
'query' =>
[
'rowPerPage' => $rowPerPage,
'page' => $page,
'keywords' => $keywords,
],
]);
$response = (string) $promise->getBody();
return json_decode($response, true);
}
catch (Exception $e){
return $e;
}
}
You are getting the bearer token of your first application using $request->bearerToken() and send it to your second application for authorization which must not work;
You need to get a working token from your second application. You can either generate a token in your second application and copy it inside your current $token variable, or first call the login endpoint of second application with your credentials and use that token.
By the way, Laravel now supports a guzzle wrapper called Illuminate\Support\Facades\Http which makes things lot easier, you can rewrite your code like this:
public function productRecommendation($rowPerPage, $keywords, $page)
{
try{
$token = "some valid token from second endpoint";
$response = Http::withToken(
$token
)->get(
$this->sellerUrl . 'recommended',
[
'rowPerPage' => $rowPerPage,
'page' => $page,
'keywords' => $keywords,
]
);
return response()->json(
json_decode($response->body(), true)
);
}
catch (Exception $e){
return $e;
}
}
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 .....
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
I am trying to recreate the following Tesco API code using Symfony\Component\HttpFoundation:
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}');
$url = $request->getUrl();
$headers = array(
// Request headers
'Ocp-Apim-Subscription-Key' => '{subscription key}',
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_GET);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
I am new to php in general and I am undertaking my first Symfony project. Could somebody please help me will recreating the above code using Symfony HttpFoundation instead?
I have tried the following code, and I return nothing:
$req2 = Request::create('https://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}', 'GET');
$req2->headers->set('Ocp-Apim-Subscription-Key', 'my_api_key');
$params = array(
'query' => 'walkers',
'offset' => '0',
'limit' => '10',
);
$req2->query->add($params);
try
{
$response = new Response();
var_dump($response);die;
}
catch (HttpException $ex)
{
die ('EX: '.$ex);
}
Symfony's Request class is used for an incoming request to Symfony. Maybe you should have a look at Guzzle to use an object-oriented approach to create a request or cURL like proposed in Symfony2 - How to perform an external Request
I have a method using gullzehttp and would like to change it to the pool plus the pool implements the Request method
<?php
use GuzzleHttp\Client;
$params = ['password' => '123456'];
$header = ['Accept' => 'application/xml'];
$options = ['query' => $params, 'headers' => $header];
$response = $client->request('GET', 'http://httpbin.org/get', $options);
I need to change to the Request method, but I could not find in the documentation how to send querystring variables in the Request
<?php
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org/get', $options);
You need to add the query as a string to the URI.
For that you can use http_build_query or a guzzle helper function to convert a parameter array to an encoded query string:
$uri = new Uri('http://httpbin.org/get');
$request = new Request('GET', $uri->withQuery(GuzzleHttp\Psr7\build_query($params)));
// OR
$request = new Request('GET', $uri->withQuery(http_build_query($params)));
I also had trouble figuring out how to properly place the new Request() parameters. but structuring it the way i did below using php http_build_query to convert my arrays to query params and then appended it to the url before sending fixed it.
try {
// Build a client
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://pro-api.coinmarketcap.com',
// You can set any number of default request options.
// 'timeout' => 2.0,
]);
// Prepare a request
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';
$headers = [
'Accepts' => 'application/json',
'X-CMC_PRO_API_KEY' => '05-88df-6f98ba'
];
$params = [
'id' => '1'
];
$request = new Request('GET', $url.'?'.http_build_query($params), $headers);
// Send a request
$response = $client->send($request);
// Receive a response
dd($response->getBody()->getContents());
return $response->getBody()->getContents();
} catch (\Throwable $th) {
dd('did not work', $th);
return false;
}