guzzle client throws exception in laravel - laravel

I am trying to make a http post request in laravel as below
$client = new Client(['debug'=>true,'exceptions'=>false]);
$res = $client->request('POST', 'http://www.myservice.com/find_provider.php', [
'form_params' => [
'street'=> 'test',
'apt'=> '',
'zip'=> 'test',
'phone'=> 'test',
]
]);
It return empty response. On debugging ,following exception is occurring
curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE*
I am using latest version of guzzle.
Any idea how to solve it?.

The request() method is returning a GuzzleHttp\Psr7\Response object.
To get the actual data that is returned by your service you should use:
$data = $res->getBody()->getContents();
Now check what you have in $data and if it corresponds to the expected output.
More information on using Guzzle Reponse object here

I had to do this
$data = $res->getBody()->getContents();<br>
but also change<br>
$client = new \GuzzleHttp\Client(['verify' => false, 'debug' => true]);<br>
to<br>
$client = new \GuzzleHttp\Client(['verify' => false]);

Here is what i did for my SMS api
use Illuminate\Support\Facades\Http; // Use this on top
// Sample Code
$response = Http::asForm()
->withToken(env('SMS_AUTH_TOKEN'))
->withOptions([
'debug' => fopen('php://stderr', 'w') // Update This Line
])
->withHeaders([
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded',
])
->post($apiUrl,$request->except('_token'));

Related

Laravel: Can't use the autoload function

I have a question about autoloading in Laravel.
I am trying to use an API to translate a web site. I typed in the code given by the provider in the controller and I got the following error message.
require(vendor\autoload.php): failed to open stream: No such file or directory
This is the code.
require 'vendor\autoload.php'; <=★Here★
session_start();
define('URL', '');
define('KEY', '');
define('SECRET', '');
define('NAME', '');
$api_name = '';
$api_param = '';
$provider = new \League\OAuth2\Client\Provider\GenericProvider(
[
'clientId' => KEY,
'clientSecret' => SECRET,
'redirectUri' => '',
'urlAuthorize' => '',
'urlAccessToken' => URL . '/oauth2/token.php',
'urlResourceOwnerDetails' => '',
],
);
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('client_credentials');
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$params = array(
'access_token' => $accessToken->getToken(),
'key' => KEY,
'api_name' => $api_name,
'api_param' => $api_param,
'name' => NAME,
'type' => 'xml',
'xxx' => 'xxx',
);
$request = $provider->getAuthenticatedRequest(
'POST',
URL . '/api/?' . http_build_query($params),
$accessToken,
);
$response = $provider->getResponse($request);
$data = $response->getBody()->getContents();
print_r($data);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
I checked the file pointed out in the error message and actually autoload.php file was in the vendor folder. I did some research and I found some web sites saying that I should add a directory in composer.json but I wasn't so sure what I should do.
I appreciate if you could tell me what I'm doing wrong or what I should do. Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.

Laravel 7 HTTP Client - Unable to send POST request with `body`

Using Laravel 7.6 and it's built-in HTTP Client.
I'm trying to send a simple POST request with body in Raw JSON format to my other domain but no luck:
$response = Http::post('https://example.com', [
'body' => '{ test: 1 }'
]);
I get 400 Bad Request - Client error - because my server expects body as a mandatory.
What am I missing here?
$response = Http:post('http://example.com/', [
'foo' => 'bar'
]);
Or this
$response = Http::withHeaders([
'User-Agent' => 'Some Agent',
])->asForm()->post('http://www.example.com/', [
'foo' => 'bar',
]);
Try this, in my case this should works.
$response = Http::withHeaders(['Content-Type' => 'application/json'])
->send('POST', 'https://example.com', [
'body' => '{ test: 1 }'
])->json();

POSTING XML USING GUZZLE CLIENT LARAVEL

I am a laravel junior developer and i have been using gazzle http for handling my requests, now i have a task of integrating Collections to a system. The provided API only wants me to post XML data. When i use Json, it works well, but now i have a task of posting xml through gazzle. how can i do it.
with Json,
$response = $client->request('POST', 'https://app.apiproviders.com/api/payment/donate', [
'form_params' => [
'name' => 'TIG Test',
'amount' => $amount,
'number' => str_replace('+', '',$this->senders_contact),
'chanel' => 'TIG',
'referral' => str_replace('+', '',$this->senders_contact)
]
]);
the desired XML format to post:
<?xml version="1.0" encoding="UTF-8"?>
<AutoCreate>
<Request>
<Method>acdepositfunds</Method>
<NonBlocking></NonBlocking>
<Amount>500</Amount>
<Account>256702913454</Account>
<AccountProviderCode></AccountProviderCode>
<Narrative>Testing the API</Narrative>
<NarrativeFileName>receipt.doc</NarrativeFileName>
<NarrativeFileBase64>aSBhbSBwYXlpbmcgNjAwMDAgc2hpbGxpbmdz</NarrativeFileBase64>
</Request>
</AutoCreate>
how can i pass this xml to gazzle in laravel??
I had a same problem a while ago, and I found a good solution using AttayToXml package. All you need to do is to create an array of your data:
$array = [
'Request' => [
'Method' => 'value',
'NonBlocking' => 'value',
'Amount' => 'value',
//and so on...
]
];
Then, you convert this array to xml, using the convert() method, where you pass the name of the root element of your xml:
$xml = ArrayToXml::convert($array, 'AutoCreate');
And this will create your desired xml:
<AutoCreate>
<Request>
<Method>acdepositfunds</Method>
<NonBlocking></NonBlocking>
<Amount>500</Amount>
//and so on...
</Request>
</AutoCreate>
And then, send it through Guzzle client with something like this, which I used in on of my projects:
$request = $httpClient->post($yourUrl, [
'body' => $xml,
'http_errors' => true,
'verify' => false,
'defaults' => ['verify' => false]
]);
<?php
~~~
use Illuminate\Support\Facades\Http;
~~~
$xml = new \SimpleXMLElement('<Hogeattribute></Hogeattribute>');
$xml->addChild('hogeId', 'hoge1');
$response = Http::withBody(
$xml->asXML(),
'text/xml'
)->post('https://hoge');
$json = json_encode(simplexml_load_string($response->body()));
$data = json_decode($json, true);
https://readouble.com/laravel/8.x/ja/http-client.html
https://qiita.com/megponfire/items/e2cfa22216073dd5d596

Can’t submit data to API Platform

I have a controller through which I send data to my local environment of the api platform (which is running fine)
/**
* Creates a new Location entity.
*
*/
public function createAction(Request $request)
{
$this->get("suvya_breadcrumbs.factory")->update('New Hub');
$form = $this->createForm(HubType::class);
$form->handleRequest($request);
$new_url = $this->generateUrl('new_hub');
$redirect_url = $this->generateUrl('home');
if ($form->isSubmitted() && $form->isValid()) {
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'form_params'=> $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Content-Type'=> 'application/json',
'Authorization'=> 'eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhZG1pbiIsImlhdCI6MTUxNzg3NjE1NCwiZXhwIjoxNTE3ODc5NzU0fQ.gIG9lueJJZxzkOl8qblhHWwiJvW97m4gz1-1mYeM9SgMzMW35Wh6XamOOYiISDN99yJ6Ovo-wKk6whpE5UGMDVw_wGek003Dd6r-Y7Ql3kVLHksn2JFzhAN3GwlXFcOI4MIjmq5qBhkzv21pHymO0yn1SlzWBwb0O7WygywefMu5p09zGuvAiP9I2ShyQLZhjj8bB_odf3dI-Ql0ZbRmn_JDkDoPcm5U11i-3S1oMikBmFq0WtTcWo7vezt3QdA3bY4_bgaISINAiYRR-_cvjpBSqFSE6n1ZYtHvKFn-98wXXsBGxEAoZw6iQL4iRgOI8F_uaiCo0eRHC7q0_xQ_V_W0-5XDIQXWDwoiVaUXnjO6xo2Fldp7PLO1ueJz1e4wiOy2-TunZdc8UCtw2BdFIQtWatPLi_v_rsNvF2H-6hwa9UOKEi9Z4tH4KkuATbXAxxfkCbSOyY1SAWP0riooPQi_AI2J7L2Ly86eAuKo1Hix3EuEogo19GSyBz_cCWczyERQWM9gikuUs8E22SIAdxTl8ZLFaXgiZIibDvb8pqcN8izFjywWbF2CkyWC58WxrVd6Bfmfnm7k9T6oZqwIZ-TQR-SbRnUHN1hpWUjFCk-tHhgvh7osHXmxe3grzA8M3LPBpQGQiTeqBZFMjF4Tx8zW2tuiEn6TwhV14Lj24Vc'
]
]);
die();
}
return $this->render('SuvyaFabricsCloudBundle:Common:basic.html.twig', array(
'form' => $form->createView(),
'page_title'=> 'Hub aanmaken',
'action_path' => $new_url,
'cancel_path'=> $redirect_url,
'submit_button_title' => 'Opslaan',
));
}
But unfortunately i'm getting an error in my dev.log of the api environment:
[2018-02-06 02:32:37] request.INFO: Matched route "api_hubs_post_collection". {"route":"api_hubs_post_collection","route_parameters":{"_controller":"api_platform.action.post_collection","_format":null,"_api_resource_class":"AppBundle\\Entity\\Hub","_api_collection_operation_name":"post","_route":"api_hubs_post_collection"},"request_uri":"http://127.0.0.1:8000/hubs","method":"POST"} []
[2018-02-06 02:32:37] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Serializer\Exception\UnexpectedValueException: "Syntax error" at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php line 78 {"exception":"[object] (Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException(code: 0): Syntax error at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php:78)"} []
The output of form->getData():
array (size=4)
'postalCode' => string 'sdfdsf' (length=6)
'streetName' => string 'sdfsdf' (length=6)
'doorNumber' => string 'sdfsfd' (length=6)
'city' => string 'sdfsfd' (length=6)
Running the endpoint at the api platform with the same values goes fine as well.
Does anyone of you has an idea why this goes wrong?
You're sending a payload encoded in application/x-www-form-urlencoded (HTML form like) to the API Platform API, while, according to the headers you've set, it excepts data encoded in JSON.
To encode the data of the form in JSON, you can use the following Guzzle snippet:
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'json' => $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Authorization'=> '...'
]
]);
Alternatively, you can configure API Platform to accept form data, but I would not recommend going this way (it's better to only deal with JSON API-side).

How to get paymentMethodNonce in Braintree API?

I'm working in laravel 5.4
My transactions are successfull when I try a 'fake_nonce' type of string provided by the braintree docs. But when I tried to get the paymentMethodNonce it always gives me error like nonce not found. And sometimes http error!!! If I try to configure it by myself!
Take a look at my controller function below
public function addOrder(Request $request){
$customer = Braintree_Customer::create([
'firstName' => $request->guest_name,
'email' => $request->guest_email,
'phone' => $request->guest_phone
]);
$customer->success;
$customer->customer->id;
$find = Braintree_Customer::find($customer->customer->id);
$nonceFromTheClient = Braintree_PaymentMethodNonce::find($find);
$result = Braintree_Transaction::sale([
'amount' => $request->subtotal,
'paymentMethodNonce' => $nonceFromTheClient,
'options' => [
'submitForSettlement' => True
]
]);
if ($result->success) {
$settledTransaction = $result->transaction;
} else {
print_r($result->errors);
}
Cart::destroy();
return view('guest/track', compact('result'));
}
$nonceFromTheClient = Braintree_PaymentMethodNonce::find($find);
Your using the wrong nonce, this nonce must come from the DropIn ui and not be generated on your code.
Please check the onPaymentMethodReceived() method provided in the JS SDK.
Please check this reference

Resources