Skip to content

Commit

Permalink
initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
MNeverOff committed Feb 28, 2024
0 parents commit 3a5f7de
Show file tree
Hide file tree
Showing 9 changed files with 485 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*/node_modules
package-lock.json
.DS_Store
*.zip
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Mike Neverov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
![Cover Image](assets/cover.svg)

This is a simple serverless application that uses AWS Lambda, Stripe and Brevo to deliver files to customers after they have made a payment via your Stripe Payment Link.
Because Themeforest, Gumroad and KoFi may be nice, but why not manage your own payment links and have a straight-forward user experience?

## Demo

TODO: Insert GitHub Video

## In-depth guide

You can read a detailed guide on setting this up in [my blog](neveroff.dev/blog/download-file-stripe-payment-link/).

## Getting started without the guide

1. Check out the repository into a local folder, open the terminal at the root folder.
2. Do `cd email-delivery` followed by `npm install && zip -r ../email-delivery.zip .` and then `cd ../file-delivery` followed by `npm install && zip -r ../file-delivery.zip .`. This will generate the node_modules folders necessary for Lambdas to work.
3. Go to the AWS Console and create a new Lambda function for each of the zipped folders, using the `index.mjs` as the handler.
4. Configure the Environment and Stage variables as per the `index.mjs` files in both file and email delivery folders.
5. Configure the Stripe Payment Link to point to the API Gateway URL for the `file-delivery` Lambda.
6. Configure a new Stripe Webhook on the `checkout.session.completed` event to point to the API Gateway URL for the `email-delivery` Lambda.
7. Use the Stripe Test mode to ensure that your customer path is working as expected and an email is sent out with the file download link.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE.md) file for details.
288 changes: 288 additions & 0 deletions assets/cover.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/demo.webm
Binary file not shown.
80 changes: 80 additions & 0 deletions email-delivery/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import axios from 'axios';
import stripe from 'stripe';
import AWS from 'aws-sdk';

const s3 = new AWS.S3();

export const handler = async (event) => {
const body = event.body;
const signature = event.headers['Stripe-Signature'];
const endpointSecret = event.stageVariables.stripe_endpoint_secret_key;

let stripeEvent;
let recipientEmail;
let redirectUrl;

try {
stripeEvent = stripe.webhooks.constructEvent(body, signature, endpointSecret);
} catch (err) {
console.log(`Webhook signature verification failed.`, err.message);
return {
statusCode: 400,
body: `Webhook Error: ${err.message}`
};
}

if (stripeEvent.type === 'checkout.session.completed') {
const session = stripeEvent.data.object;

if (session.payment_status === 'paid') {
recipientEmail = session.customer_details.email;

if (!recipientEmail) {
recipientEmail = process.env.fallback_email;
}

const params = {
Bucket: process.env.bucket_name,
Key: process.env.object_key,
Expires: 60 * 60 * 24 * 30 // 30 days
};
const presignedUrl = s3.getSignedUrl('getObject', params);
redirectUrl = `${process.env.redirect_host}${encodeURIComponent(presignedUrl)}${process.env.utm_parameters}`;

const emailBody = {
templateId: 1,
to: [{ email: recipientEmail }], // use the email from the webhook
params: { downloadURL: redirectUrl }
};

try {
await axios.post('https://api.sendinblue.com/v3/smtp/email', emailBody, {
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'api-key': event.stageVariables.brevo_api_key
}
});

console.log(`Email sent for session id ${session.id}`);
} catch (err) {
console.log(`Failed to send email for session id ${session.id}`, err);
}
}
else {
console.log(`Payment status is different from paid: ${session.payment_status}.`);
return {
statusCode: 400,
body: `Received ${stripeEvent.type}, payment status is different from paid: ${session.payment_status}, handled by ${event.stageVariables.environment} env.`
};
}

} else {
console.log(`Unhandled event type ${stripeEvent.type}.`);
}

return {
statusCode: 200,
body: `Received ${stripeEvent.type}, sent an email to ${recipientEmail} with a redirect link ${redirectUrl} handled by ${event.stageVariables.environment} env.`
};
};
7 changes: 7 additions & 0 deletions email-delivery/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"dependencies": {
"aws-sdk": "^2.1563.0",
"axios": "^1.6.7",
"stripe": "^14.17.0"
}
}
53 changes: 53 additions & 0 deletions file-delivery/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import Stripe from 'stripe';
import AWS from 'aws-sdk';

const s3 = new AWS.S3();

export const handler = async (event) => {
const stripe = new Stripe(event.stageVariables.stripe_secret_api_key);
const sessionId = event.queryStringParameters.sessionId;

let chargeSucceeded = false;

for (let i = 0; i < 10; i++) {
try {
const session = await stripe.checkout.sessions.retrieve(sessionId);
if (session.payment_status === 'paid') {
chargeSucceeded = true;
break;
}
} catch (error) {
console.error(`Failed to retrieve session: ${error.message}. Environment: ${event.stageVariables.environment}.`);
return {
statusCode: 400,
body: `Failed to retrieve session: ${error.message}. Environment: ${event.stageVariables.environment}.`
};
}
await new Promise(resolve => setTimeout(resolve, 1000));
}

if (chargeSucceeded) {
const params = {
Bucket: process.env.bucket_name,
Key: process.env.object_key,
Expires: 60 * 60 * 24 * 30 // 30 days
};
const presignedUrl = s3.getSignedUrl('getObject', params);
const redirectUrl = `${process.env.redirect_host}${encodeURIComponent(presignedUrl)}${process.env.utm_parameters}`;

console.log(`Redirecting to ${redirectUrl} in environment ${event.stageVariables.environment}.`);
return {
statusCode: 302,
headers: {
Location: redirectUrl
},
body: ''
};
} else {
console.log(`Charge did not succeed for session id ${sessionId}. Environment: ${event.stageVariables.environment}.`);
return {
statusCode: 400,
body: `Charge did not succeed for session id ${sessionId}. Environment: ${event.stageVariables.environment}.`
};
}
};
6 changes: 6 additions & 0 deletions file-delivery/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"dependencies": {
"aws-sdk": "^2.1563.0",
"stripe": "^14.17.0"
}
}

0 comments on commit 3a5f7de

Please sign in to comment.