贝宝订阅

时间:2019-03-13 17:57:25

标签: paypal

我正在尝试使用以下网址上的说明获取PayPal访问令牌:https://developer.paypal.com/docs/api/overview/#get-an-access-token

我已经按照字母的URL上的说明进行操作,并使用JavaScript构建了以下示例代码。当我运行它时,出现401错误-用户未授权。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>Get Access Token</h1>
    <script>
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log(xhttp.responseText);
            }
            else {
               console.log("Status: " + xhttp.status)
            }
        };
        url = "https://api.sandbox.paypal.com/v1/oauth2/token"
        clientID = "AY_6HpYodeIdCyCSWmIuTTX6P4PfcO1tcehekaSk9uwSBhav1SILCD0MZ_E3dRMVXiPdmE-YimahYtQy"
        secret = "EHLlKnunCQtuTdqjnl6QX9ZnuQgMllZKozf-VNHeys9tDssQc0xlXi4_0se1M-VxT8gOHGaSVS3M-2an"
        xhttp.open("post", url, false, clientID, secret);
        xhttp.setRequestHeader("Accept", "application/json");
        xhttp.setRequestHeader("Accept-Language", "en_US");
        xhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhttp.send("grant_type=client_credentials");
        console.log(xhttp.status);
    </script>
</body>
</html>

clientID和机密来自“贝宝我的应用和凭据”链接:

PayPal My Apps and Credentials Page

有人可以帮忙吗?谢谢

1 个答案:

答案 0 :(得分:0)

我找到了答案。以下代码有效。客户端ID和密码不应以我所拥有的方式作为参数传递给Open命令。

相反,它们必须彼此连接,中间用一个冒号连接,然后(信不信由你)对64位编码并在Authorization标头中传递,如下所示:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>Get Access Token</h1>
    <script>
        clientID = "AY_6HpYodeIdCyCSWmIuTTX6P4PfcO1tcehekaSk9uwSBhav1SILCD0MZ_E3dRMVXiPdmE-YimahYtQy"
        secret = "EHLlKnunCQtuTdqjnl6QX9ZnuQgMllZKozf-VNHeys9tDssQc0xlXi4_0se1M-VxT8gOHGaSVS3M-2an"
        var authorizationString = btoa(clientID + ':' + secret);
        /////////////////////////////////////////////////////////////////////////////////////////////
        var xhttp = new XMLHttpRequest();
        var createPlanResults = ""
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                document.write(xhttp.responseText)
            }
        };
        url = "https://api.sandbox.paypal.com/v1/oauth2/token"
        xhttp.open("post", url, false);
        xhttp.setRequestHeader("Accept", "application/json");
        xhttp.setRequestHeader("Accept-Language", "en_US");
        xhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhttp.setRequestHeader("Authorization", "Basic " + authorizationString);
        xhttp.send("grant_type=client_credentials");
    </script>
</body>
</html>