json 使用paypal的REST API有问题

4dc9hkyq  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(107)

我试图创建和发送贝宝发票。我编写了一个函数来使用贝宝的nodejs sdk创建它们,但它不起作用,我没有看到沙盒 Jmeter 板中的起草发票。
我正在做一个不和谐的机器人管理贝宝发票!

function createInvoice(item_name,item_description, quantity, cost, payer_email){ 

    let invoiceNumber = generateInvoiceNumber()

    fetch('https://api-m.sandbox.paypal.com/v2/invoicing/invoices', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${getAccessToken()}`,
            'Content-Type': 'application/json',
            'Prefer': 'return=representation'
        },
        body: JSON.stringify({
            "detail": {
              "invoice_number": generateInvoiceNumber(),
              "currency_code": "USD", 
            },
            "invoicer": {
               "email_address": config.emailAddress, 
            },
            "primary_recipients": [
              {
                "billing_info": {
                  "email_address": payer_email,
                }, 
              }
            ],
            "items": [
              {
                "name": item_name,
                "description": item_description,
                "quantity": quantity,
                "unit_amount": {
                  "currency_code": "USD",
                  "value": cost, 
                },
                "unit_of_measure": "QUANTITY"
              }, 
            ], 
          })
    }); 
    
    sendInvoice(invoiceNumber)

字符串
编辑我检查了提取结果,它返回了这个错误。
{“error”:“invalid_token”,“error_description”:“令牌签名验证失败”}
这是getAccessToken()函数。

function getAccessToken(){
    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': config.clientId,
        'pass': config.clientSecret,
        // 'sendImmediately': false
      },
      form: {
        "grant_type": "client_credentials"
      }
    }, function(error, response, body) {
        let { access_token } = JSON.parse(body)
        console.log(access_token)
        return access_token;
    });
  
}


我更新了我的getAccessToken函数,但它仍然给我invalid_token错误。

async function getAccessToken(){

    const response = await fetch('https://api-m.sandbox.paypal.com/v1/oauth2/token', {
        method: "post",
        body: "grant_type=client_credentials",
        headers:{
            Authorization:
                "Basic " + Buffer.from(config.clientId + ":" + config.clientSecret).toString("base64")
        },
    });
    
    const data = await response.json();
    console.log(data)
    return data;
        
}

5us2dqdw

5us2dqdw1#

Request.post 是异步的。getAccessToken函数不会等到你收到响应,它只会完成函数并返回undefined。使用async/await还要注意,目前getAccessToken函数本身没有返回值。返回值在回调函数中。

相关问题