Skip to content

Commit

Permalink
feat(firestore-stripe-payments): remove trial_from_plan, add trial_pe…
Browse files Browse the repository at this point in the history
…riod_days
  • Loading branch information
jauntybrain committed Jan 28, 2024
1 parent 973cf93 commit e9ee79e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 69 deletions.
4 changes: 2 additions & 2 deletions firestore-stripe-payments/POSTINSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ docRef.onSnapshot((snap) => {

#### Handling trials

By default, the trial period days that you've specified on the pricing plan will be applied to the checkout session. Should you wish to not offer the trial for a certain user (e.g. they've previously had a subscription with a trial that they canceled and are now signing up again), you can specify `trial_from_plan: false` when creating the checkout session doc:
You can specify subscription trial period when creating the checkout session by using the `trial_period_days` parameter. Refer to the [docs](https://stripe.com/docs/payments/checkout/free-trials) for a detailed guide on free trials and how to set them up.

```js
const docRef = await db
Expand All @@ -272,7 +272,7 @@ const docRef = await db
.collection("checkout_sessions")
.add({
price: "price_1GqIC8HYgolSBA35zoTTN2Zl",
trial_from_plan: false,
trial_period_days: 7,
success_url: window.location.origin,
cancel_url: window.location.origin,
});
Expand Down
43 changes: 0 additions & 43 deletions firestore-stripe-payments/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,49 +60,6 @@ Then, in the [Stripe Dashboard](https://dashboard.stripe.com):

- Create a new [restricted key](https://stripe.com/docs/keys#limit-access) with write access for the "Customers", "Checkout Sessions" and "Customer portal" resources, and read-only access for the "Subscriptions" and "Prices" resources.

#### Installing via Firebase CLI

When installing via the CLI, be sure to pin the version.

```
firebase ext:install invertase/firestore-stripe-payments --project=projectId_or_alias
Alternatively for local source:
firebase ext:install . --project=projectId_or_alias
```

The current version can be found in [extension.yaml](extension.yaml).

#### Using webhooks locally

If you wish to test the webhooks **locally**, use the following command to configure the extension:

```
firebase ext:configure firestore-stripe-payments --local
```

Be sure to configure your test mode [API Key](https://stripe.com/docs/keys) and webhook [signing secret](https://stripe.com/docs/webhooks/signatures#:~:text=Before%20you%20can%20verify%20signatures,secret%20key%20for%20each%20endpoint.) when prompted.

Start the firebase emulator with:

```
firebase emulators:start --project=projectId_or_alias
```

Find the functions path associated with the stripe extension, typically it looks like this:

- `http://192.0.0.1:5001/{projectId}/{region}/ext-firestore-stripe-payments-handleWebhookEvents`

- You can tunnel your local endpoint using a tool like [ngrok](https://ngrok.com/). In this case you will tunnel the localhost domain and port `http://127.0.01:5001`. Replace `127.0.0.1:5001` with your tunnel url. The end result would look something like:

```
https://1234-1234-1234.ngrok.io/{projectId}/{region}/ext-firestore-stripe-payments-handleWebhookEvents
```

- Configure your test mode stripe [webhook endpoint](https://stripe.com/docs/webhooks) with the url you just constructed.

- Your local webhooks are now set up.


#### Billing

This extension uses the following Firebase services which may have associated charges:
Expand Down
50 changes: 26 additions & 24 deletions firestore-stripe-payments/functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ const createCustomerRecord = async ({
if (email) customerData.email = email;
if (phone) customerData.phone = phone;
const customer = await stripe.customers.create(customerData);

// Add a mapping record in Cloud Firestore.
const customerRecord = {
email: customer.email,
stripeId: customer.id,
stripeLink: `https://dashboard.stripe.com${
customer.livemode ? '' : '/test'
}/customers/${customer.id}`,
stripeLink: `https://dashboard.stripe.com${customer.livemode ? '' : '/test'
}/customers/${customer.id}`,
};
if (phone) (customerRecord as any).phone = phone;
await admin
Expand Down Expand Up @@ -133,7 +133,7 @@ exports.createCheckoutSession = functions
tax_rates = [],
tax_id_collection = false,
allow_promotion_codes = false,
trial_from_plan = true,
trial_period_days,
line_items,
billing_address_collection = 'required',
collect_shipping_address = false,
Expand Down Expand Up @@ -169,15 +169,15 @@ exports.createCheckoutSession = functions
const shippingCountries: Stripe.Checkout.SessionCreateParams.ShippingAddressCollection.AllowedCountry[] =
collect_shipping_address
? (
await admin
.firestore()
.collection(
config.stripeConfigCollectionPath ||
config.productsCollectionPath
)
.doc('shipping_countries')
.get()
).data()?.['allowed_countries'] ?? []
await admin
.firestore()
.collection(
config.stripeConfigCollectionPath ||
config.productsCollectionPath
)
.doc('shipping_countries')
.get()
).data()?.['allowed_countries'] ?? []
: [];
const sessionCreateParams: Stripe.Checkout.SessionCreateParams = {
billing_address_collection,
Expand All @@ -188,11 +188,11 @@ exports.createCheckoutSession = functions
line_items: line_items
? line_items
: [
{
price,
quantity,
},
],
{
price,
quantity,
},
],
mode,
success_url,
cancel_url,
Expand All @@ -209,9 +209,11 @@ exports.createCheckoutSession = functions
sessionCreateParams.payment_method_collection =
payment_method_collection;
sessionCreateParams.subscription_data = {
trial_from_plan,
metadata,
metadata
};
if (trial_period_days) {
sessionCreateParams.subscription_data.trial_period_days = trial_period_days;
}
if (!automatic_tax) {
sessionCreateParams.subscription_data.default_tax_rates = tax_rates;
}
Expand Down Expand Up @@ -301,6 +303,7 @@ exports.createCheckoutSession = functions
const subscription = await stripe.subscriptions.create({
customer,
items: [{ price }],
trial_period_days: trial_period_days,
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent'],
metadata: {
Expand Down Expand Up @@ -558,9 +561,8 @@ const manageSubscriptionStatusChange = async (
metadata: subscription.metadata,
role,
status: subscription.status,
stripeLink: `https://dashboard.stripe.com${
subscription.livemode ? '' : '/test'
}/subscriptions/${subscription.id}`,
stripeLink: `https://dashboard.stripe.com${subscription.livemode ? '' : '/test'
}/subscriptions/${subscription.id}`,
product: admin
.firestore()
.collection(config.productsCollectionPath)
Expand Down Expand Up @@ -965,4 +967,4 @@ export const onCustomerDataDeleted = functions.firestore
if (!config.autoDeleteUsers) return;
const { stripeId } = snap.data();
await deleteStripeCustomer({ uid: context.params.uid, stripeId });
});
});

0 comments on commit e9ee79e

Please sign in to comment.