Notes
This Stripe function allows you to create an invoice via the Stripe API.
Like the `Stripe Checkout Session` function, this is ideally used after a user has submitted a form indicating what they want to purchase.
Code
Language: JavaScript
// Front-end code
function createStripeInvoice() {
let pricePerUnit = 100;
let quantOfUnit - 1;
let unitName = "Name of line item";
let customerEmail = "bob@bobness.co.uk";
const apiUrl = 'FULL URL OF YOUR SERVERLESS FUNCTION GOES HERE';
const queryParams = {
pricePerUnit,
quantOfUnit,
unitName,
customerEmail
};
return $.ajax({
url: apiUrl,
method: 'GET',
data: queryParams,
dataType: 'json'
});
}
// Back end code
const stripeAccessToken = `Bearer 1234`;
const axios = require('axios');
const querystring = require('querystring');
// Define headers for API requests
const headers = {
'Authorization': stripeAccessToken,
'Stripe-Version': '2020-08-27',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Function to create an invoice
async function createInvoice(customerId, pricePerUnit, quantOfUnit, unitName) {
try {
console.log("Sending invoice line item");
const invoiceLineItemResponse = await axios.post('https://api.stripe.com/v1/invoiceitems', querystring.stringify({
customer: customerId,
amount: (pricePerUnit * quantOfUnit) * 100, // Calculate the total amount based on quantity of units
currency: 'gbp',
description: unitName
}), { headers });
console.log("Invoice line item created successfully");
// Retrieve the invoice line item ID from the response
const invoiceLineItemId = invoiceLineItemResponse.data.id;
console.log("Sending invoice");
const invoiceResponse = await axios.post('https://api.stripe.com/v1/invoices', querystring.stringify({
customer: customerId,
collection_method: 'send_invoice',
auto_advance: true,
days_until_due: 30
}), { headers });
console.log("Invoice created successfully");
return invoiceResponse.data;
} catch (error) {
throw new Error(error.message);
}
}
exports.main = async (context, sendResponse) => {
try {
let pricePerUnit = parseInt(context.params.pricePerUnit[0]);
let quantOfUnit = parseInt(context.params.quantOfUnit[0]);
let unitName = context.params.unitName[0];
let customerEmail = context.params.customerEmail[0];
let customerId;
console.log("pricePerUnit:", pricePerUnit);
console.log("quantOfUnit:", quantOfUnit);
console.log("unitName:", unitName);
console.log("customerEmail:", customerEmail);
// Check if the customer already exists
let customersResponse = await axios.get(`https://api.stripe.com/v1/customers?email=${customerEmail}`, { headers });
if (customersResponse.data.data.length > 0) {
// Use existing customer
customerId = customersResponse.data.data[0].id;
console.log("Existing customer found in Stripe");
console.log("customerId:", customerId);
} else {
// Create new customer
let customerResponse = await axios.post('https://api.stripe.com/v1/customers', querystring.stringify({ email: customerEmail }), { headers });
customerId = customerResponse.data.id;
console.log("Created new customer in Stripe");
console.log("customerId:", customerId);
}
// Create invoice using the createInvoice function
const invoiceData = await createInvoice(customerId, pricePerUnit, quantOfUnit, unitName);
sendResponse({ body: invoiceData, statusCode: 200 });
} catch (error) {
sendResponse({ body: error.message, statusCode: 400 });
}
};
How can SpotDev support your business?
HubSpot Migrations
Move from Salesforce, Dynamics, Pipedrive or any CRM to HubSpot with SpotDev.
Learn moreHubSpot Integrations
Add advanced functionality to your HubSpot portal with API development services.
Learn moreRevOps
Align your sales, marketing and service teams to break down silos and trigger growth.
Learn more