Created
August 7, 2020 18:37
-
-
Save robconery/dd24077aa60209bf752c1802ea7614c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require('firebase-functions'); | |
const stripe = require("./lib/stripe"); | |
exports.createCheckoutSession = functions.https.onCall(async (data, context) => { | |
console.log("Checkout session request incoming", data); | |
const res = await stripe.createSubscriptionCheckout(data); | |
return res; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require('firebase-functions'); | |
const publicKey = functions.config().stripe.public_key; | |
const secretKey = functions.config().stripe.secret_key; | |
var stripe = require('stripe')(secretKey) | |
const root_url = functions.config().app.root_url; | |
const createSession = async (payload) => { | |
const planId = payload.plan === "Monthly" ? functions.config().stripe.monthly : functions.config().stripe.yearly | |
//do we have a customer? | |
let customer = null; | |
const res = await stripe.customers.list({email: payload.email, limit: 1}); | |
if(res.data.length > 0) customer = res.data[0]; | |
if(!customer){ | |
customer = await stripe.customers.create({ | |
email: payload.email | |
}); | |
} | |
const stripeData = { | |
success_url: payload.success_url || `${root_url}/thanks-for-signing-up`, | |
cancel_url: payload.cancel_url || `${root_url}/maybe-next-time`, | |
payment_method_types: ['card'], | |
customer: customer.id, | |
allow_promotion_codes: true, | |
subscription_data: { | |
trial_from_plan: true, | |
items: [{ | |
plan: planId | |
}] | |
} | |
} | |
if(payload.coupon){ | |
stripeData.subscription_data.coupon = payload.coupon; | |
} | |
try{ | |
const session = await stripe.checkout.sessions.create(stripeData); | |
return { | |
success: true, | |
sessionId: session.id, | |
public_key: publicKey | |
}; | |
}catch(err){ | |
return { | |
success: false, | |
error: err.message | |
} | |
} | |
} | |
exports.createSubscriptionCheckout = function(payload){ | |
return createSession(payload); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment