skip to Main Content

Paypal Rest Api returns 401 Unauthorized when i try to get OAuth2 token using php file_get_contents() in localhost with sandbox

    $client_id = env('PAYBAL_CLIENT');
    $client_secret = env('PAYPAL_SECRET');

    $opts = array('http' =>
        array(
            'method' => 'POST',
            "headers" => [
                "Content-Type" => "application/x-www-form-urlencoded",
                "Authorization" => "Basic " . base64_encode("$client_id:$client_secret")
            ],
            'body' => "{'grant_type' : 'client_credentials'}"
        )
    );

    $context = stream_context_create($opts);

    $url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";

    $result = file_get_contents($url, false, $context);

the same requeste worked fine with me in ajax

$.ajax(
{
    url: "https://api-m.sandbox.paypal.com/v1/oauth2/token",
    type:"post",
    headers:{
        "Authorization": "Basic 'XXXbase64_encodedXXX'"
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data:{
        "grant_type":"client_credentials"
    },
    success:function (data){
        console.log(data);
    },
    complete:function (data,status){
        console.log(status);
    }
}

);

2

Answers


  1. Chosen as BEST ANSWER

    Instead of file_get_contents I uses GuzzleHttp And It Worked With Me , Here is the code

            $client_id = env('PAYBAL_CLIENT');
        $client_secret = env('PAYPAL_SECRET');
        
        $client = new GuzzleHttpClient();
        $response = $client->request('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', [
            'headers' => [
                'Content-type' => 'application/x-www-form-urlencoded',
                'Authorization' => "Basic " . base64_encode("$client_id:$client_secret")
            ],
            'body' => 'grant_type=client_credentials'
        ]);
    

  2. The ajax function is converting the data to url encoded format for you here:

            "Content-Type": "application/x-www-form-urlencoded"
        },
        data:{
            "grant_type":"client_credentials"
        },
    

    PHP’s curl does not do that (or especially when you give it a string instead of an array/object, there’s no way it can guess that it needs to be converted; it will assume any string you pass is the string you intend to post)

    'body' => "{'grant_type' : 'client_credentials'}"
    

    You must supply a form url-encoded body string as the API call requires: "grant_type=client_credentials"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search