繁体   English   中英

当我尝试使用带有沙箱的本地主机中的 php file_get_contents() 获取 OAuth2 令牌时,Paypal Rest Api 返回 401 Unauthorized ,但在 ajax 中有效

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM