【问题标题】:How to call to API with axios in NodeJS with Authorization Basic如何使用授权基础在 NodeJS 中使用 axios 调用 API
【发布时间】:2021-03-20 15:56:07
【问题描述】:

我有一个从贝宝​​获取令牌的 API。

curl -v POST 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"

我正在使用 axios 拨打电话,类似这样,但我在身份验证时遇到错误。

axios.post("https://api.sandbox.paypal.com/v1/oauth2/token", {}, {
      auth: {
        username: "xxxx, // clientId
        password: "xxxx"  // client Secret
      }
    }).then(function(response) {
      result = response;
      console.log('Authenticated' + response);
    }).catch(function(error) {
      console.log('Error on Authentication' + error);
    });

可能是我错过了“grant_type”之类的内容...如何在此调用中传递这些参数。请你纠正一下?非常感谢你

【问题讨论】:

    标签: javascript express axios paypal-sandbox paypal-rest-sdk


    【解决方案1】:

    Client ID 和 Client Secret 不能是您的用户名和密码。 curl 中的 -u 标志用于用户名和密码,但在 axios 中,这可能会有所不同。对于卷曲知识follow this。 如果你很挣扎,那么一切都有一些选择,那么你可以去这个库。 PayPal-node-SDK。或者在 youtube 上关注一些教程。

    【讨论】:

      【解决方案2】:
      axios({
           method: 'POST',
           url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
           headers: {
             'Authorization': `Basic ${clientId}:${secretKey}`,
             'Content-type': 'application/json'
           },
        data: `grant_type=authorization_code&code=${authorizationCode}`
      })
      

      【讨论】:

      【解决方案3】:

      ${clientId}:${secretKey}需要base64编码

      在 JavaScript 中,您可以使用 btoa()、toString('base64') 或使用 axios 设置身份验证密钥。

      使用 curl 可以使用 -u 命令行参数。


      对于一般的 REST API 使用,当以这种方式将基本身份验证传递给 oauth2/token 端点时,您的查询字符串应该是 grant_type=client_credentials,如 documented here。这将返回您可以在所有其他 API 调用中使用的 access_token。

      您链接到的“Connect with PayPal”文档是针对特定集成的,您需要授权码,但没有其他 API 使用它。

      【讨论】:

        猜你喜欢
        • 2022-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 2020-06-05
        • 2017-10-29
        • 2021-04-15
        相关资源
        最近更新 更多