ServerException in RequestException.php line 107: 500 Internal Server Error - php

I am using laravel framework.
I am trying to update an existing data using api (kinda new to this).
So this is my route
Route::group(['middleware' => 'web'], function () {
Route::post('/update_supplier_details/{id}', "UpdateController#update_supplier_details");
});
This is my Controller
public function update_supplier_details(Request $request, $id){
$details = $request->all();
$client = new CharmeAPI;
$token = Session::get('token');
$url = "https://api.charmeapp.com/api/v1/suppliers/{$id}?token={$token}";
$response = $client->request('POST', $url,['form_params' => $details])->getBody();
echo $response;
$data = json_decode($response, true);
$status = array_get($data, 'status');
$message = array_get($data, 'error.msg');
if($status == 'error'){
session(['update_supplier_details_error' => $status]);
return redirect()->back()->with('supplier_details_msg', $message);
}
else if($status == 'ok') {
session(['update_supplier_details_error' => $status]);
session(['supplier_details_first_name' => array_get($data, 'data.Supplier.first_name')]);
session(['supplier_details_last_name' => array_get($data, 'data.Supplier.last_name')]);
$first_name = session('supplier_details_first_name');
$last_name = session('supplier_details_last_name');
return $first_name.$last_name;
return redirect()->back()->with('supplier_details_msg', $first_name.' '.$last_name.' added successfully');
}
}
}
and I am getting this error -
ServerException in RequestException.php line 107:
Server error: POST https://api.charmeapp.com/api/v1/suppliers/139?token=Q8vJLPvpnRImoz5Li4tVfGtGliyGBQcx3NdqYbNdRaYYvsaoLncyDvFHkriS resulted in a 500 Internal Server Error response:
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex,nofollow" />
<style>
(truncated...)
But if I use postman to call the api url I get the desired data
Any help pls

Make sure you pass the correct parameters and token to the api.

Related

is that possible sending http request from lumen using guzzlehttp?

actually i want to validate given token .. the validate code written in another lumen package. i have got some issues when i send request to validate token. i dont know why it's not working. cant use another api inside lumen ?
if i use that check token api in postman https://i.stack.imgur.com/kSpJt.png. it works fine. it's thrown error when i call that api inside other lumen package
this is what i got when use this api in postman https://i.stack.imgur.com/hfFzk.png
error log https://i.stack.imgur.com/ds0oR.png
<?php
namespace App\Helpers;
use App\Helpers\ResponseBuilder;
class check_customer_token_verification
{
public static function check($token, $vendor_id)
{
$client = new \GuzzleHttp\Client();
$result = $client->post('dev.adiswar-crm.local/customer/crm/v-1-0-0/check-token', [
'form_params' => [
'token' => isset($token)?$token:'',
'vendor_id' => $vendor_id,
]
]);
$res_data = json_decode($result->getBody()->getContents()); dd($res_data);
if ($res_data->http_code == 401) {
return ResponseBuilder::responseResult(400, $res_data->message);
}
return $res_data;
}
} ```
dump this api in postman. i got issue which is below
^ {#120
+"http_code": 400
+"message": """
Server error: `POST dev.adiswar-crm.local/customer/crm/v-1-0-0/check-token` resulted in a `500 Internal Server Error` response:
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex,nofollow" />
<style>
(truncated...)
"""
}```
You need to define your form_params, though your code can work but I would also suggest using try catch blocks and adding your 401 exception in catch block (& other 400 in there), see the changes I have made
public static function check($token, $vendor_id)
{
try{
$client = new \GuzzleHttp\Client();
define("form_params", \GuzzleHttp\RequestOptions::FORM_PARAMS );
$guzzleResponse = $client->post('dev.adiswar-crm.local/customer/crm/v-1-0-0/check-token', [
'form_params' => [
'token' => isset($token) && !empty($token) ? $token : '',
'vendor_id' => $vendor_id,
]
]);
if ($guzzleResponse->getStatusCode() == 200) {
$result = json_decode($guzzleResponse->getBody(),true);
// dd($result);
}
return $result;
}catch(\GuzzleHttp\Exception\RequestException $e){
// Catch all 4XX errors
dd($e->getMessage, $e->getTraceAsString());
// To catch exactly error 401 use
if ($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '401') {
return ResponseBuilder::responseResult(400, $e->getMessage());
}
}
}catch(Exception $e){
//other errors
}
}

Jwt Token decode - Symfony 4

I am trying to solve a problem related with token request. It is my newArticle function (to add new article) in the controller:
public function newArticle(Request $request, EntityManagerInterface $entityManager): View
{
$data = json_decode($request->getContent(), true);
$title = $data['title'];
$content = $data['content'];
//$published_at = $data['published_at'];
$authorizationHeader = $request->headers->get('Authorization');
list(,$token) = explode(' ', $authorizationHeader);
$jwtToken = $this->JWTEncoder->decode($token);
$user_id = $data[$jwtToken];
$userId = $this->userRepository->findOneBy(['id' => $user_id['id']]);
$article = new Article();
$article->setTitle($title);
$article->setContent($content);
$article->setPublishedAt(new \DateTime());
$article->setUser($userId);
// Todo: 400 response - Invalid input
// Todo: 404 response - Response not found
// Incase our Post was a success we need to return a 201 HTTP CREATED response with the created object
if(in_array('ROLE_USER', $article->getUser()->getRoles(), true)) {
$entityManager->persist($article);
$entityManager->flush();
return View::create("You added an article successfully!", Response::HTTP_OK);
} else {
return View::create(["You are not a user! So please register to add an article!"], Response::HTTP_BAD_REQUEST);
}
}
It is working before adding token header authorization and now I got this error:
"error": {
"code": 500,
"message": "Internal Server Error",
"message": "Notice: Undefined offset: 1",
Can someone give me any suggestions?
I thing your problem is this line:
$user_id = $data[$jwtToken];
You should refactor that, think it should be something like:
$user_id = $data['user_id'];
or
$user_id = $jwtToken['user_id'];
Depending on what data contain each object/array is where you should look foor. In first place the error is for calling an offset on an array, so fixing that should be fine (or have a clearer error message from the log)

Guzzle returns 500 error

So im new to guzzle and building API's , I have used Laravel Passport and on one GET call its fine. I have written a POST call and getting a 500 error in return
Post function
public function newsSingle() {
$request = (new GuzzleHttp\Client)->post('http://138.68.180.100/news/article/single', [
'headers' => [
'Authorization' => 'Bearer '.session()->get('token.access_token'),
'post_id' => $_POST['post_id']
]
]);
$news = json_decode((string)$request->getBody());
return view('pages.newsingle', compact('news'));
}
Which does add the post item
POST Data
post_id
"3"
on the other end I have
Route:
Route::post('news/article/single', 'ApiController#singlePost')->middleware('auth:api');
Controller function:
public function singlePost(Request $request) {
$article = Articles::where('id', $request['post_id'])->get();
return $article;
}
my error:
Server error: `POST http://ipaddress/news/article/single` resulted in a `500 Internal Server Error` response: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="robots" content="noindex,nofollow (truncated...)
We found the similar issue with Guzzle for External API calls when response code is 500 and got Server error: and exception is thrown. There is a work around to do a bypass mechanism by catching the exception due to BadResponseException to return as response. below is the code for performing this. :)
catch (\GuzzleHttp\Exception\BadResponseException $e) {
return $e->getResponse()->getBody()->getContents();
}

Notice: Undefined offset: 0 in C:\wamp64\www\lynda2\src\Chatter\Middleware\Authentication.php on line 12

Hi i'm created a web service with Slim from a course of lynda "Building APIs in PHP Using the Slim Micro Framework" but when i want login, this error Occurs
Notice: Undefined offset: 0 in C:\wamp64\www\lynda2\src\Chatter\Middleware\Authentication.php on line 12
Authentication
namespace Chatter\Middleware;
use Chatter\Models\User;
class Authentication
{
public function __invoke($request, $response, $next)
{
$auth = $request->getHeader('Authorization');
$_apikey = $auth[0];
$apikey = substr($_apikey, strpos($_apikey, ' ') + 1);
$user = new User();
if (!$user->authenticate($apikey)) {
$response->withStatus(401);
return $response;
}
$response = $next($request, $response);
return $response;
}
}
User.php
<pre><code>
namespace Chatter\Models;
class User extends \Illuminate\Database\Eloquent\Model
{
public function authenticate($apikey)
{
$user = User::where('apikey', '=', $apikey)->take(1)->get();
$this->details = $user[0];
return ($user[0]->exists) ? true : false;
}
}
</code></pre>
index.php
<pre><code>
require 'vendor/autoload.php';
include 'bootstrap.php';
use Chatter\Models\Message;
use Chatter\Middleware\Logging as ChatterLogging;
use Chatter\Middleware\Authentication as ChatterAuth;
$app = new \Slim\App();
$app->add(new ChatterAuth());
$app->add(new ChatterLogging());
$app->get('/messages', function ($request, $response, $args) {
$_message = new Message();
$messages = $_message->all();
$payload = [];
foreach($messages as $_msg) {
$payload[$_msg->id] = ['body' => $_msg->body, 'user_id' => $_msg->user_id, 'created_at' => $_msg->created_at];
}
return $response->withStatus(200)->withJson($payload);
});
$app->get('/', function ($request, $response, $args) {
return "This is a catch all route for the root that doesn't do anything useful.";
});
// Run app
$app->run();
</code></pre>
The error is stating that when you "login" there is no Authorization header present.
$request->getHeader('Authorization') returns an empty array, so when you attempting to access the first element of the array, you get your error:
$_apikey = $auth[0]; // Will trigger error, since there are no elements in the array
Thus to aviod this error, get $apikey like this:
public function __invoke($request, $response, $next)
{
$auth = $request->getHeader('Authorization');
$_apikey = array_shift($auth);
if ($_apikey) {
$apikey = substr($_apikey, strpos($_apikey, ' ') + 1);
$user = new User();
if (!$user->authenticate($apikey)) {
return $response->withStatus(401);
} else {
return $next($request, $response);
}
} else {
// Authorization header is missing, therefore unauthorized access
return $response->withStatus(401);
}
}
This is an older thread, but in case anyone else is following this tutorial ... the code the OP posted was supposed to do exactly what it does - to fail if there is no authorization header present.
Looks like the OP missed one step: adding the bearer token to the request. In Postman, go to Authorization > Type > Bearer Token and paste a valid token in the input field. I believe that it was clearly stated in the tutorial. Afterward, everything works as expected.

Guzzle post gives me error 500, get works fine

I'm trying to build an API with api key and secret using laravel and guzzle. I am building both the api and the client using laravel.
I have a problem when I try to access a simple controller to get a json with a list of users from the database. It works fine when I'm not using the authentication, it fails when I do beacause I need to change to using post method so that the api gets the secret and the app_id:
GuzzleHttp \ Exception \ ServerException (500)
Server error response [url] http://myapi.api/api/v1/users [status code] 500 [reason phrase] Internal Server Error
On my client:
$_app_id = 'APP001';
$_app_key = '28e336ac6c9423d946ba02d19c6a2632';
$_api_url = 'http://myapi.api/api/v1/users';
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
$params = array();
$params['enc_request'] = $enc_request;
$params['app_id'] = $_app_id;
$client = new GuzzleHttp\Client();
$result = $client->post($_api_url, array(
'body' => $params
));
$res=$result->json();
var_dump($res);
On my API:
Route::group(array('prefix' => 'api/v1'), function(){
Route::resource('users', 'UsersController');
});
Route::filter('my.filter', function()
{
$applications = array(
'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //randomly generated app key
);
try {
$enc_request = $_REQUEST['enc_request'];
$app_id = $_REQUEST['app_id'];
if( !isset($applications[$app_id]) ) {
throw new Exception('Application does not exist!');
}
$params = json_decode(trim(mcrypt_decrypt( MCRYPT_RIJNDAEL_256, $applications[$app_id], base64_decode($enc_request), MCRYPT_MODE_ECB )));
if( $params == false ){
throw new Exception('Request is not valid');
$result['success'] = false;
}else{
$result['success'] = true;
}
} catch( Exception $e ) {
$result = array();
$result['success'] = false;
$result['errormsg'] = $e->getMessage();
}
if($result['success']==false){
return Response::make('Unauthorized', 401);
//I have tested and the APP never gets inside here, authentication is correct
}
});
My controller:
class UsersController extends BaseController {
public function index()
{
$users = User::orderBy('username', 'asc');
return Response::json(array(
'error' => false,
'users' => $users->get()->toArray()),
200
);
}
}
If I remove the filter and simply change post to get on my client, I can see the json that comes from my users controller. As soon as I change it back to post, I get my error again.
Route resource uses the store method to post to the same uri as the index method. As stated within here and scrolling down to the 'Actions Handled By Resource Controller' part.
I ended up changeing body to query and it worked fine as it was and could use the resource classes and guzzle at the same time.

Categories