POST API LARAVEL TO PHP NATIVE

Sisi Laravel

function insert(Request $req)
{      
    $client = new Client();

    $url = 'https://domain.com';
    $token = 'token';
    $data = [
        'param1' => $req->param1,
        'param2' => $req->param2,             
    ];

    try {
        $response = $client->request('POST', $url, [
            'headers' => [
                'Authorization' => "Bearer {$token}",
                'Accept' => 'application/json',
            ],
            'form_params' => $data
        ]);

        $body = $response->getBody()->getContents();

        $respon = json_decode($body, true);
        if ($respon['status_code'] == 200) {
           
        } else {
            return redirect()->back()->with('warning', $respon['message'])->withInput();
        }
    } catch (\Exception $e) {
        return redirect()->back()->with('warning', $e->getMessage())->withInput();
    }      
   


Sisi Php Native

<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  exit();
}

function getBearerToken() {
    $headers = null;

    // Check if the 'Authorization' header is set
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER["REDIRECT_HTTP_AUTHORIZATION"]);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }

    // If the headers are set, parse the bearer token
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }

    return null;
}

$token = getBearerToken();

if ($token !=  'token') {
            echo json_encode([
                'status_code' => 404,
                'message' => 'Invalid Token'
            ]);
    exit;
        }



$results = ["status_code" => 200,
            "message" => "Simpan Berhasil",
            "data" => [
        "param1" => $_POST['param1'],
        "param2" => $_POST['param2']
       
        ]];


echo json_encode($results);


?>

Comments

Popular Posts

My Channel