This is the completed code from our Stripe guide, available at https://autocode.com/stripe/threads/how-to-sell-digital-products-online-using-stripe-and-autocode-9f447421/. It automatically generates a personalized Christmas card image based off the purchaser's name (pulled from their billing details), then emails it to them.
// Import the packges we'll need for this project
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const {registerFont, createCanvas, loadImage} = require('canvas');
// Pull the metadata about this order from Stripe
let checkoutData = await lib.stripe.checkout[
'@2020.8.27-1'
].sessions.lineItems.list({
session: `${context.params.checkout_session.id}`,
});
// Loop through all products that were ordered in this checkout session
for (let i = 0; i < checkoutData.data.length; i++) {
// If the user ordered a Christmas Card, run our custom logic to give it to them
if (checkoutData.data[i].description == 'Christmas Card') {
// Use Canvas (an NPM library) to automatically generate our image
registerFont(require('@canvas-fonts/comic-sans-ms'), {
family: 'Comic Sans',
}); // register Helvetica as our font
const canvas = createCanvas(960, 540); // Create a canvas for us to draw on
const ctx = canvas.getContext('2d');
let background = await loadImage(
'https://autocode.autocode.dev/sample-images/stripe/christmas-card.png'
); // download our template image
ctx.drawImage(background, 0, 0, 960, 540); // set the template image as our background
ctx.font = 'bold 32px "Comic Sans"'; // setup our text settings
ctx.fillStyle = 'white';
ctx.textAlign = 'left';
ctx.strokeStyle = 'black';
ctx.lineWidth = 4;
ctx.strokeText(
`from ${context.params.event.data.object.customer_details.name}`,
37,
187
);
ctx.fillText(
`from ${context.params.event.data.object.customer_details.name}`,
37,
187
); // write the customer's name onto the image
// Email our image to the purchaser
let data = await lib.gmail.messages['@0.2.8'].create({
to: `${context.params.event.data.object.customer_details.email}`,
subject: `Your Christmas Card is here!`,
html: `Hey ${context.params.event.data.object.customer_details.name}!
Thanks so much for buying a customized Christmas card from us! Your image to send to your friends is attached to this email.
`,
attachments: [
{
filename: `christmascard.png`,
url: canvas.toDataURL(),
},
],
});
}
}