提问者:小点点

如何向Paypal的誓言API(v2)发送获取请求?


我花了几天时间试图找出在我的网站上获得一个有效的支付门户。我不是直接从网站上销售产品,但我确实想通过我的网站从我的贝宝商业账户接受发票问题的付款。为了做到这一点,我需要能够检索与其电子邮件地址相关的发票列表,以便他们可以选择一个并付款,我可以通过发票API来完成。为了做到这一点,我需要打电话给身份验证API以获得访问令牌。

身份验证API留档为我提供了通过cURLPostman发出请求的说明,我以前都没有使用过。我找到了一个可以将cURL请求转换为fetch请求的站点,这给了我以下信息:

fetch("https://api-m.sandbox.paypal.com/v1/oauth2/token", {
  body: "grant_type=client_credentials",
  headers: {
    Authorization: "Basic PENMSUVOVF9JRD46PENMSUVOVF9TRUNSRVQ+",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  method: "POST"
})

我认为Authoration属性中的字符串是基于原始-u"

    const token = await fetch("https://api-m.sandbox.paypal.com/v1/oauth2/token", {
        body: "grant_type=client_credentials",
        headers: {
            Authorization: `Bearer ${clientID}:${secret}`,
            "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST"
    })

    console.log(await token)

并打印出以下内容:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://api-m.sandbox.paypal.com/v1/oauth2/token',
    status: 401,
    statusText: 'Unauthorized',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}
{
  name: 'AUTHENTICATION_FAILURE',
  message: 'Authentication failed due to invalid authentication credentials or a missing Authorization header.',
  links: [
    {
      href: 'https://developer.paypal.com/docs/api/overview/#error',
      rel: 'information_link'
    }
  ]
}


共1个答案

匿名用户

使用axios而不是fetch

您需要将Client idClient Secret部分编码为Base64格式。它有助于一点保护,而不是直接文本。

Base64. encode(client_id":"client_secret)

授权:BasicBase64结果

示例:

客户端ID:bHRpY3VsdHwuY29tcH

客户端密钥:pQaE-ceDi3nFz

编码库64(bHRpY3VsdHwuY29tcHpQaE-ceDi3nFz)-

授权基本YkhScFkzVnNkSHd1WTI5dGNIOnBRYUtY2VEaTNuRno=

详细信息在这里

const axios = require("axios")
const base64 = require('base-64');

const getToken = async () => {
    try {
        const client_id = 'Aeb...your-client-id...s-q'
        const client_secret = 'EDM...your-secret...ZXv'

        const response = await axios.post('https://api-m.sandbox.paypal.com/v1/oauth2/token',
            new URLSearchParams({
                'grant_type': 'client_credentials'
            }),
            {
                headers:
                {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Basic ' + base64.encode(client_id + ":" + client_secret)
                }
            })
        return Promise.resolve(response.data.access_token);
        // for debugging
        // return Promise.resolve(response.data);

    } catch (error) {
        return Promise.reject(error);
    }
}

getToken()
    .then(token => {
        console.log("access token: " + token)
        // for debugging
        // console.log("response: " + JSON.stringify(token, null, 4))
    })
    .catch(error => {
        console.log(error.message);
    });
npm install axios base-64
node get-token.js

这里有详细信息

如果您还有一些错误,请检查您的权限