Laravel 5.1 Guzzle - Undefined offset: 0 - api

I need to access an API so I use guzzle6 and I write a function:
public function test()
{
$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
try {
$res = $client->post('https://example.com/api/v2/oauth/token?grant_type=client_credentials', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'auth' => [
'Username' => 'user_5639',
'Password' => 'pass_asdhbas67yausihd7qaw8'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
but I got error:
ErrorException in Client.php line 346: Undefined offset: 0
When I try at POSTMAN the same request everything is fine:
How to solve my problem?

If you have a look at the Guzzle Manual for the auth-option, you'll see it expects a numerically indexed array, with the username on index 0 and the password on index 1.
So this should work:
$res = $client->post('https://example.com/api/v2/oauth/token?grant_type=client_credentials', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'auth' => [
'user_xxxx', 'pass_xxxxx'
]
]);

Related

Problem to upload file with from-param in Laravel 8 external api with guzzle or HTTP client

I am using Mirakl api. I faced an issue with the file upload with form-peram in Laravel 8 external api with guzzle or HTTP client.I got 400 Bad Request.The api expects file with from-param like this
{
"order_documents": [{
"file_name": String,
"type_code": String
}]
}
The documentation of my endpoint can be found from this link (http://185.29.149.41/eci/mir/doc/api/OR74.html) and here is my codes --
public function upload_order(Request $request)
{
$order_id = $request->order_id;
if ($files = $request->file('files')) {
$name = $files->getClientOriginalName();
Storage::disk('invoice')->put($name, file_get_contents($files->getRealPath()));
$path = Storage::disk('invoice')->path($name);
}
$file['order_documents'][] = [
'file_name' => $name,
'type_code' => $request->type_code,
];
$json = json_encode($file);
$data = [
['name' => 'order_documents','contents' => $json],
];
$data[] = [
'name' => 'files',
'contents' => mb_convert_encoding($path, 'UTF-8', 'UTF-8'),
'filename' => $name,
];
$body['multipart'] = $data;
$configApi = $this->configApi($this->getMarketplaceID($request->marketplace), auth()->user()->id);
$url = $configApi['url'].'/api/orders/'.$order_id.'/documents';
$client = new Client(['verify' => false]);
$response = $client->request(
'POST',
$url,
[
'multipart' => $data,
'headers' => $configApi['headers']
]);
return json_decode($response->getBody(), true);
}

cakephp 3.8.13 add admad/cakephp-jwt-auth

This question is asked many times in the stack overflow but I tried every accepted solution.
I'm new to cake PHP and I was assigned to add JWT in our application. Previously the team used the default cake sessions. In order to integrate, I used admad/cakephp-jwt-auth. So In the AppController
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Recurring');
$this->loadComponent('Auth', [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'user_name',
'password' => 'password',
],
'contain' => ['Roles']
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'CbEmployees',
'fields' => [
'username' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
]);
}
I have to use CbEmployees which is our user model.
Then in my custom controller, I add my login function
public function login()
{
$user = $this->Auth->identify();
if (!$user) {
$data = "Invalid login details";
} else {
$tokenId = base64_encode(32);
$issuedAt = time();
$key = Security::salt();
$data = JWT::encode(
[
'alg' => 'HS256',
'id' => $user['id'],
'sub' => $user['id'],
'iat' => time(),
'exp' => time() + 86400,
],
$key
);
}
$this->ApiResponse([
"data" => $data
]);
}
Then I call this function using postman with body
{
"username": "developer",
"password": "dev2020"
}
I always get the response as Invalid login details. So the suggested solution is to check the password data type and length. The password is varchar(255). Another solution is to check the password in the entity. In the entity I have
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return Security::hash($password, 'sha1', true);
// return (new DefaultPasswordHasher)->hash($password);
}
}
I specifically asked why the team is using Security::hash($password, 'sha1', true); due to migration from cake 2 to cake 3 they have to use the same.
Why I'm getting always Invalid login details? What I'm doing wrong here? I can log in the using the same credentials when I'm using the application.

How to call an API using raw input using Guzzle

I have an API which is working well with Postman but upon trying to call it in code, I get errors. See below
In Postman
Below is how I am calling the API in code:
In Code
public function pay_bill(Request $request){
$client = new Client(); //GuzzleHttp\Client
$username = 'xxxx';
$password = 'xxx#2020*';
$credentials = base64_encode("$username:$password");
$transaction_id = intval($request->input('transaction_id'));
$amount = (int)$request->input('amount');
$bill_number = (int)$request->input('bill_number');
$return_url = $request->input('return_url');
$response = $client->post('https://gatewaytest.e.com:5000/gateway/initialize', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Basic ' . $credentials,
'X-API-KEY' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
'form_params' => [
'transaction_id' => $transaction_id,
'total_amount' => $amount,
'bills' => ["bill_ref" => $bill_number, "amount" => $amount],
'return_url'=> $return_url
],
'verify' => true
]);
$transaction_data = $response->getBody();
return $transaction_data;
}
What am I doing wrong? How do I send body as raw like is done in postman? I imagine the problem could be due to using form_params
I finally found the solution as shown below:
'bills' => [["bill_ref" => $bill_number, "amount" => $amount]]

Laravel 5.5 BroadcastException with Pusher

I have create the chat application in laravel with Brodecast+Vue so when trying to my test broadcast class its getting error "BroadcastException in PusherBroadcaster.php (line 106)" I have double checked all configurations and api authentications are correct. but getting error and pusher debug console do not display and request.
driver :
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => true
],
],
event :
public $message;
public $user;
public function __construct($message, User $user)
{
$this->message = $message;
$this->user = $user;
}
test function :
public function test()
{
$user = User::find(Auth::id());
event(new ChatEvent('Hello pusher', $user));
return response('done');
}
i think you need to make encrypted = false.
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => false
],
],

How actionError() function will call in my controller in yii2?

backend/controllers/AccessController.php
public function actionFault(){
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
$statusCode = $exception->statusCode;
$name = $exception->getName();
$message = $exception->getMessage();
$this->layout = 'layout';
return $this->render('error', [
'exception' => $exception,
'statusCode' => $statusCode,
'name' => $name,
'message' => $message
]);
}
backend/config/main.php
'components' => [
// ...
'errorHandler' => [
'errorAction' => 'access/fault',
],
// ...
],
If I am not wrong than actionError() will call when any error comes am i right ?
But in my case actionError is not calling what i am doing wrong ?