gpt4 book ai didi

curl - 将以下 Paypal curl 命令转换为 axios?

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:47 27 4
gpt4 key购买 nike

如何将此 paypal curl 命令转换为 Axios?

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "client_id:secret" \
-d "grant_type=client_credentials"

我在 vue 中使用 vueAxios,因此是“this.”。

this.axios.post('https://api.sandbox.paypal.com/v1/oauth2/token',
{'Accept': "application/json", 'Accept-Language': "en_US",
'XXXXXX': 'XXXXX', // my paypal client ID and client secret
'grant_type':'client_credentials'}
)
.then( response => {
console.log("Response is: ", response);
})
.catch( error => {
console.log("Error is :", error);
});

我收到这个错误:

 Error is : Error: Request failed with status code 401
at createError (createError.js?16d0:16)
at settle (settle.js?db52:18)
at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)

我也试过这个(这似乎更好,但我仍然收到 400 错误):

 this.axios({ 
method: 'POST',
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type':'application/x-www-form-urlencoded'
},
auth: {
username: '<XXXX My paypal client ID>',
password: '<XXXX My paypal secret>'
} ,
data: {
grant_type: 'client_credentials'
},
})
.then(function(response) {console.log(response);})
.catch(function(response) {console.log(response);});

更新——在一些帮助形成评论后,我尝试了以下代码, Paypal 有一个问题 CORS 错误(我已经安装了一个 npm 包“cors”并且 cors 错误仍然存​​在(本地和部署时))。

这回答了我的问题,但是,as stated here ,似乎 Paypal 不允许直接从浏览器请求。

this.axios({
withCredentials: true,
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'post',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type':'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
},
data: { 'grant_type':'client_credentials' },
auth: {
username: 'XXXXXXXX',
password: 'XXXXXXXX'
}
})

相关文档:

CORS:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

VueAxios:https://www.npmjs.com/package/vue-axios

Paypal 开发者:https://developer.paypal.com/docs/api/overview/#make-your-first-call

最佳答案

这是一个很老的话题。我在 node.js 上也为此苦苦挣扎。我以后的解决方案。希望这有帮助:

const res = await axios(
{
method: 'post',
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
data: 'grant_type=client_credentials', // => this is mandatory x-www-form-urlencoded. DO NOT USE json format for this
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',// => needed to handle data parameter
'Accept-Language': 'en_US',
},
auth: {
username: clientId,
password: clientSecret
},

});

console.log(JSON.stringify(res.data)); // => be sure to handle res.data, otherwise you will have a circular json error. The token you need is res.data.access_token.

关于curl - 将以下 Paypal curl 命令转换为 axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53378792/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com