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
Instead of file_get_contents I uses GuzzleHttp And It Worked With Me , Here is the code
The ajax function is converting the data to url encoded format for you here:
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)
You must supply a form url-encoded body string as the API call requires:
"grant_type=client_credentials"