我正在尝试使用此URL上的说明获取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和secret来自PayPal My Apps and Credentials链接:
PayPal My Apps and Credentials Page
有人可以帮忙吗?谢谢
我找到了答案。以下代码有效。客户端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>