I've been working on a project where I need to generate and send PayPal invoices. I wrote a function using PayPal's NodeJS SDK to create invoices, but for some reason, the drafted invoices don't show up in the sandbox dashboard.
Currently, I'm developing a Discord bot that handles PayPal invoices!
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)
UPDATE After examining the fetch result, it appears that I am getting this error message:
{"error":"invalid_token", "error_description":"Token signature verification failed"}
This is the getAccessToken() function that I have been using.
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;
});
}
I made some changes to my getAccessToken() function, but unfortunately, I am still encountering the invalid_token error.
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;
}