![](/img/trans.png)
[英]file_get_contents('php://input') Returns empty for one user, but works fine for others
[英]Paypal Rest Api returns 401 Unauthorized when i try to get OAuth2 token using php file_get_contents() in localhost with sandbox , but works in ajax
當我嘗試使用帶有沙箱的本地主機中的 php file_get_contents() 獲取 OAuth2 令牌時,Paypal Rest Api 返回 401 Unauthorized
$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);
同一個請求者在 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);
}
}
);
ajax 函數在這里為您將數據轉換為 url 編碼格式:
"Content-Type": "application/x-www-form-urlencoded"
},
data:{
"grant_type":"client_credentials"
},
PHP 的 curl 不會這樣做(或者特別是當您給它一個字符串而不是數組/對象時,它無法猜測它需要轉換;它會假定您傳遞的任何字符串都是您打算發布的字符串)
'body' => "{'grant_type' : 'client_credentials'}"
您必須按照 API 調用的要求提供表單 url 編碼的正文字符串: "grant_type=client_credentials"
我使用 GuzzleHttp 而不是 file_get_contents 並且它與我一起工作,這是代碼
$client_id = env('PAYBAL_CLIENT');
$client_secret = env('PAYPAL_SECRET');
$client = new \GuzzleHttp\Client();
$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'
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.