Bearer Token in Guzzle HTTP 6.1 not working - php

I have a problem with my Bearer-Authorization in Guzzle-HTTP.
I use it to test my PHP-REST-API with PHPUnit.
here is my test method:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = $responseJson->data->token;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
But if I set the token hard coded like this:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0NjQ5NzExMzQsImp0aSI6IjByR3FpOW15Rm1rRGo2TU9sMVhkK3dRU3p1V0pWejM1UEhiU2dTMmg5SEU9IiwiaXNzIjoiQXBwTmFtZSIsIm5iZiI6MTQ2NDk3MTE0NCwiZXhwIjoxNDY0OTczMTQ0LCJzdWIiOiJ0ZXN0QG1haWwuZGUifQ.yA4a_S6ILCeqENm00H712g9uF5g9eSz_BmnaMDdZ2r4p5e1q88g0T09IG2WKCi1oExoBfQ8VTmKeX6ZQv0RydQ;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
and also with Postman, it is working.
It's the same token which I receive from my REST-API.
Do you have any ideas what's wrong?

Related

How to display data from API and Database in the same page in laravel?

I am working on an API and MySQL project that will save some of the data in MySQL and some in the API
Controller (index function):
{
$response = Http::post('http://example.com/authenticate', [
'Username' => 'ADMIN',
'Password' => 'ADMIN',
'Token' => 'FK98D...',
]);
$token = json_decode($response, true);
$apiURL = 'http://example.com/api/SalesOrder/';
$headers = [
'Content-Type' => 'application/json',
'Authorization' => $token,
];
$response2 = Http::withHeaders($headers)->get($apiURL);
$data = $response2->json();
$jobdetail = JobDetail::all();
return view('api.auth.orders.index', compact('data','jobdetail'));
}
the above function is working correctly
Controller (store function):
public function store(Request $request)
{
$response = Http::post('http://example.com/authenticate', [
'Username' => 'ADMIN',
'Password' => 'ADMIN',
'Token' => 'FK98D...',
]);
$token = json_decode($response, true);
$request->validate([
'job_order_no' => 'required',
'sap_no' => 'required',
'pic_name' => 'required',
]);
JobDetail::create($request->all());
$store = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => $token,
])->post('http://example.com/api/SalesOrder/', [
'DocNo' => $request->job_order_no,
'TotalQty' => $request->TotalQty,
'TotalTransferredAOQty' => $request->TotalTransferredAOQty,
'SODTL' => array([
'DtlKey' => "",
'ItemCode' => $request->ItemCode,
])
]);
return $store;
}
and the above function is storing data to API and MySQL
note: that 'DocNo' is using the 'job_order_no' request so both will be the same value to be able to call it for show function (i am not sure if this is the best approach)
Controller (show function):
public function show($DocNo,JobDetail $company)
{
$client = new Client();
$headers = [
'Content-Type' => 'application/x-www-form-urlencoded'
];
$options = [
'form_params' => [
'Username' => 'ADMIN',
'Password' => 'ADMIN',
'Token' => 'FK98DL...'
]
];
$request = new Psr7Request('POST', 'http://example.com/authenticate', $headers);
$res = $client->sendAsync($request, $options)->wait();
$token = json_decode($res->getbody(),true);
$client = new Client();
$headers = [
'Authorization' => $token,
'Content-Type' => 'application/x-www-form-urlencoded'
];
$options = [
'form_params' => [
'DocNo' => $DocNo
]
];
$request = new Psr7Request('GET', 'http://example/api/SalesOrder/GetSalesOrder/', $headers);
$res = $client->sendAsync($request, $options)->wait();
$data = json_decode($res->getBody(),true);
return view('api.auth.orders.show', compact('data','company'));
}
view (to redirect to show page):
<td class="text-center"></td>
how to redirect the above "a" tag to get the data from API and MySQL from 'DocNo' ('DocNo' is 'job_order_no' in MySQL as i mentioned above in store function)
is there a query that i need to add to show function to get data from database where the DocNo from the API equals DocNo from MySQL?
SOLUTION:
i used query to get the same value from MySQL as showing below:
$jobs = DB::table('jobdetails')->where('job_order_no', $DocNo)->first();

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) {
}

API error no parameters when there are parameters given

This is the error I'm getting, as you can see there is a parameter in the URL, but the error says there weren't any parameters given. Can anbody help me out?
Client error: PUT https://webapi.teamviewer.com/api/v1/devices/d38237721?alias=laptop-test resulted in a 400 Bad Request response:
{"error":"invalid_request","error_description":"no parameters were given.","error_code":1}
This is my code
public function update($device_id, $options)
{
$token = 'thereisatokenhere';
$client = new Client(['base_uri' => 'https://webapi.teamviewer.com/api/v1/']);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept-Language' => 'en-US',
'Content-Type' => 'application/json'
];
$response = $client->request('PUT', 'devices/' . $options['device_id'], [
'headers' => $headers,
'form_params' => [
'alias' => $options['alias'],
],
]);
$response = json_decode($response->getBody()->getContents(), true);
$deviceIdsAPI = $response['devices'];
return $deviceIdsAPI;
}
2nd
$request = new Request('PUT', 'https://webapi.teamviewer.com/api/v1/devices/' . $options['device_id'], ['alias' => $options['alias']]);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
Here is an example of a PUT request in Guzzle:
$client->put('devices/' . $options['device_id'], [
'body' => [
'alias' => $options['alias'],
'other_field' => '123'
],
'headers' => $headers,
'allow_redirects' => false,
'timeout' => 5
]);
Update:
In the latest version (Guzzle 6) it should be like this:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put', ['test' => '123']);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
See this answer and here is the official Guzzle documentation

Missing argument 1 for App\Http\Controllers\CustomerController::postOptOut()

I'm looking for some advice as to how I might clean up these two methods and resolve this error? Right now, the getOptOut() is making a GET request to the API to obtain an email_token and returning the view and postOptOut() is making a POST request, with the email_token from the GET, and allowing a "customer" to opt out of the mailing list and then redirecting to customer home.
public function getOptOut(EmailOptingRequest $request)
{
$customer = Customer::find(Auth::id());
$email = $customer['attributes']['Email'];
$token = "9asdfj48asdj48adja4r8";
$client = new Client();
$res = $client->request('GET',
'https://www.example.com/api/Services/Email/Opting', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'email' => $email,
'http_errors' => false // add this to return errors in json
]);
$emailToken = json_decode($res->getBody()->getContents(), true);
$this->postOptOut($emailToken);
return view('customer.email-opting', array(
'customer' => $customer,
'email' => $email,
'token' => $token,
'client' => $client,
'res' => $res,
'emailToken' => $emailToken
));
}
public function postOptOut($emailToken)
{
$customer = Customer::find(Auth::id());
$email_token = $emailToken[0]['token'];
$client = new Client();
$res = $client->request('POST', 'https://www.example.com/api/Services/Email/Opting', [
'email_token' => $email_token,
'category' => 'promotional',
'status' => false
]);
return view('customer.show', array(
'customer' => $customer,
'email_token' => $email_token,
'client' => $client,
'res' => $res ))
->with('success', 'You were removed from our mailing list.');
}
And my routes:
Route::get( 'customer/email-opting', 'CustomerController#getOptOut');
Route::post( 'customer/post-opt-out', 'CustomerController#postOptOut');
The hard coded token is temporary. I'm running into issues with the timing of the GET and POST calls and when the views are returning. Thanks!
public function postOptOut(Request $request)
{
$customer = Customer::find(Auth::id());
$email_token = $request->emailToken[0]['token']; // this way you will get token
$client = new Client();
$res = $client->request('POST', 'https://www.example.com/api/Services/Email/Opting', [
'email_token' => $email_token,
'category' => 'promotional',
'status' => false
]);
return view('customer.show', array(
'customer' => $customer,
'email_token' => $email_token,
'client' => $client,
'res' => $res ))
->with('success', 'You were removed from our mailing list.');
}
Try this

Can't set Guzzle Content Type

I'm trying to request this way:
$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'defaults' => [
'auth' => [$publishable_key, ''],
],
'body' => json_encode($body),
]);
The problem is that this request is being set without Content-Type.
What am I doing wrong?
Ok .. the problem was that I was setting body and headers outside of defautls. the solution is:
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'defaults' => [
'auth' => [$publishable_key, ''],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($body),
],
]);
Guzzle 6
Guzzle will set the Content-Type header to
application/x-www-form-urlencoded when no Content-Type header is
already present.
You have 2 options.
Option 1: On the Client directly
$client = new GuzzleHttp\Client(
['headers' => [
'Content-Type' => 'application/json'
]
]
);
Option 2: On a Per Request basis
// Set various headers on a request
$client = new GuzzleHttp\Client();
$client->request('GET', '/whatever', [
'headers' => [
'Content-Type' => 'application/json'
]
]);
You can refer to Guzzle 6: Request Options
I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.
I fixed it this way
$client = new Client([
'base_uri' => 'https://api.hubapi.com/',
'timeout' => 5,
'headers' => ['Content-Type' => 'application/json']
]);
And then performing my requests the regular way
try
{
$response = $client->request('POST', '/contacts/v1/contact/email/test#test.com/profile',
['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }
I hope this helps.

Categories