Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions netlify/functions/createCheckout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

const extrovert = require('extrovert');

module.exports = extrovert.toNetlifyFunction(require('../../src/actions/createCheckout'));
74 changes: 74 additions & 0 deletions src/actions/createCheckout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
'use strict';

const Archetype = require('archetype');
const connect = require('../db');
const recaptcha = require('../integrations/recaptcha');
const stripe = require('../integrations/stripe');

const CreateCheckoutParams = new Archetype({
name: {
$type: 'string',
$required: true
},
email: {
$type: 'string',
$required: true
},
plan: {
$type: 'string',
$required: true,
$enum: ['solo', 'pro']
},
Comment thread
vkarpov15 marked this conversation as resolved.
website: {
$type: 'string'
},
response: {
$type: 'string'
}
Comment thread
vkarpov15 marked this conversation as resolved.
}).compile('CreateCheckoutParams');

const priceIds = {
solo: process.env.STRIPE_SOLO_PRICE_ID,
pro: process.env.STRIPE_PRO_PRICE_ID
};

module.exports = async function createCheckout(params) {
const { name, email, plan, website, response } = new CreateCheckoutParams(params);

if (website) {
throw new Error('This request was flagged as spam. If this is an error, please refresh and try again.');
}

const recaptchaResult = await recaptcha.verify(response);
console.log(recaptchaResult);
Comment thread
vkarpov15 marked this conversation as resolved.
if (!recaptchaResult.success || recaptchaResult.score < 0.7 || recaptchaResult.action !== 'checkout') {
throw new Error('Captcha verification failed');
}
Comment thread
vkarpov15 marked this conversation as resolved.

const db = await connect();
const { Contact } = db.models;

await Contact.findOneAndUpdate(
{ email: email.toLowerCase() },
{ $set: { name }, $setOnInsert: { email: email.toLowerCase() } },
{ upsert: true }
);

const priceId = priceIds[plan];
if (!priceId) {
throw new Error('Price not configured for plan: ' + plan);
}

const returnUrl = (process.env.PUBLIC_APP_BASE_URL || 'https://studio.mongoosejs.io') + '/my-account.html';

const session = await stripe.client.checkout.sessions.create({
ui_mode: 'embedded',
mode: 'subscription',
customer_email: email,
line_items: [{ price: priceId, quantity: 1 }],
Comment on lines +64 to +68
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Set client_reference_id on checkout session

stripeWebhook can only attach a successful checkout to an existing workspace when data.object.client_reference_id is present; otherwise it always creates a new workspace. This checkout creation payload never sets client_reference_id, so any purchase initiated for an existing workspace will be processed as a brand-new workspace instead of an upgrade, leading to duplicate workspaces and the original workspace remaining unsubscribed.

Useful? React with 👍 / 👎.

return_url: returnUrl,
metadata: { name, plan }
});

return { clientSecret: session.client_secret };
};
12 changes: 12 additions & 0 deletions src/db/Contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const mongoose = require('mongoose');

const contactSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
name: { type: String },
company: { type: String },
deletedAt: { type: Date, default: null }
}, { timestamps: true });

module.exports = contactSchema;
2 changes: 2 additions & 0 deletions src/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const mongoose = require('mongoose');

const accessTokenSchema = require('./AccessToken');
const contactSchema = require('./Contact');
const contentSchema = require('./content');
const dashboardResultSchema = require('./DashboardResult');
const invitationSchema = require('./invitation');
Expand All @@ -20,6 +21,7 @@ module.exports = async function connect() {
await mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });
if (Object.keys(mongoose.models).length === 0) {
mongoose.model('AccessToken', accessTokenSchema, 'AccessToken');
mongoose.model('Contact', contactSchema, 'Contact');
mongoose.model('Content', contentSchema, 'Content');
mongoose.model('DashboardResult', dashboardResultSchema, 'DashboardResult');
mongoose.model('Invitation', invitationSchema, 'Invitation');
Expand Down
2 changes: 1 addition & 1 deletion src/db/workspace.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const workspaceSchema = new mongoose.Schema({
},
subscriptionTier: {
type: String,
enum: ['', 'free', 'pro']
enum: ['', 'free', 'solo', 'pro']
},
stripeCustomerEmail: {
type: String,
Expand Down
36 changes: 36 additions & 0 deletions src/integrations/recaptcha.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const qs = require('querystring');

const verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';

exports.verify = async function verify(response, remoteIp) {
if (!response) {
return { success: false, score: 0 };
}

const secret = process.env.RECAPTCHA_SECRET_KEY;

const body = qs.stringify({
secret,
response,
remoteip: remoteIp
});
Comment thread
vkarpov15 marked this conversation as resolved.

const res = await fetch(verifyUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body
});

if (!res.ok) {
console.log('Error verifying reCAPTCHA', await res.text());
Comment thread
vkarpov15 marked this conversation as resolved.
throw new Error('Failed to verify reCAPTCHA');
}

const data = await res.json();

return data;
};
Loading