簡體   English   中英

如何使用節點檢索 PayPal REST Api 訪問令牌

[英]How to retrieve PayPal REST Api access-token using node

如何通過使用節點獲取利用 REST Api 所需的 PayPal 訪問令牌?

擁有 PayPal 客戶端 ID 和客戶端密鑰后,您可以使用以下內容:

var request = require('request');

request.post({
    uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
    headers: {
        "Accept": "application/json",
        "Accept-Language": "en_US",
        "content-type": "application/x-www-form-urlencoded"
    },
    auth: {
    'user': '---your cliend ID---',
    'pass': '---your client secret---',
    // 'sendImmediately': false
  },
  form: {
    "grant_type": "client_credentials"
  }
}, function(error, response, body) {
    console.log(body);
});

如果成功,響應將如下所示:

{
    "scope":"https://api.paypal.com/v1/payments/.* ---and more URL callable with the access-token---",
    "access_token":"---your access-token---",
    "token_type":"Bearer",
    "app_id":"APP-1234567890",
    "expires_in":28800
}

此外,您可以使用axiosasync/await

const axios = require('axios');

(async () => {
  try {
    const { data: { access_token } } = await axios({
      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',
      },
      auth: {
        username: client_id,
        password: client_secret,
      },
      params: {
        grant_type: 'client_credentials',
      },
    });

    console.log('access_token: ', access_token);
  } catch (e) {
    console.error(e);
  }
})();

現代問題需要現代解決方案:

const fetch = require('node-fetch');
const authUrl = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
const clientIdAndSecret = "CLIENT_ID:SECRET_CODE";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')

fetch(authUrl, { 
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Accept-Language': 'en_US',
        'Authorization': `Basic ${base64}`,
    },
    body: 'grant_type=client_credentials'
}).then(function(response) {
    return response.json();
}).then(function(data) {
    console.log(data.access_token);
}).catch(function() {
    console.log("couldn't get auth token");
});

您可以使用PayPal-Node-SDK調用 PayPal Rest API。 它為您處理所有授權和身份驗證。

這是我使用 superagent 獲取 access_token 的方法

        superagent.post('https://api.sandbox.paypal.com/v1/oauth2/token')
        .set("Accept","application/json")
        .set("Accept-Language","en_US")
        .set("content-type","application/x-www-form-urlencoded")
        .auth("Your Client Id","Your Secret")
        .send({"grant_type": "client_credentials"})
        .then((res) => console.log("response",res.body))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM