GithubHelp home page GithubHelp logo

vercel / nextjs-subscription-payments Goto Github PK

View Code? Open in Web Editor NEW
5.3K 46.0 1.1K 1.07 MB

Clone, deploy, and fully customize a SaaS subscription application with Next.js.

Home Page: https://subscription-payments.vercel.app/

License: MIT License

JavaScript 0.77% PLpgSQL 10.52% CSS 2.32% TypeScript 86.39%
supabase stripe-customer-portal stripe-checkout nextjs-starter vercel

nextjs-subscription-payments's Introduction

Next.js Subscription Payments Starter

The all-in-one starter kit for high-performance SaaS applications.

Features

Demo

Screenshot of demo

Architecture

Architecture diagram

Step-by-step setup

When deploying this template, the sequence of steps is important. Follow the steps below in order to get up and running.

Initiate Deployment

Vercel Deploy Button

Deploy with Vercel

The Vercel Deployment will create a new repository with this template on your GitHub account and guide you through a new Supabase project creation. The Supabase Vercel Deploy Integration will set up the necessary Supabase environment variables and run the SQL migrations to set up the Database schema on your account. You can inspect the created tables in your project's Table editor.

Should the automatic setup fail, please create a Supabase account, and a new project if needed. In your project, navigate to the SQL editor and select the "Stripe Subscriptions" starter template from the Quick start section.

Configure Auth

Follow this guide to set up an OAuth app with GitHub and configure Supabase to use it as an auth provider.

In your Supabase project, navigate to auth > URL configuration and set your main production URL (e.g. https://your-deployment-url.vercel.app) as the site url.

Next, in your Vercel deployment settings, add a new Production environment variable called NEXT_PUBLIC_SITE_URL and set it to the same URL. Make sure to deselect preview and development environments to make sure that preview branches and local development work correctly.

[Optional] - Set up redirect wildcards for deploy previews (not needed if you installed via the Deploy Button)

If you've deployed this template via the "Deploy to Vercel" button above, you can skip this step. The Supabase Vercel Integration will have set redirect wildcards for you. You can check this by going to your Supabase auth settings and you should see a list of redirects under "Redirect URLs".

Otherwise, for auth redirects (email confirmations, magic links, OAuth providers) to work correctly in deploy previews, navigate to the auth settings and add the following wildcard URL to "Redirect URLs": https://*-username.vercel.app/**. You can read more about redirect wildcard patterns in the docs.

If you've deployed this template via the "Deploy to Vercel" button above, you can skip this step. The Supabase Vercel Integration will have run database migrations for you. You can check this by going to the Table Editor for your Supabase project, and confirming there are tables with seed data.

Otherwise, navigate to the SQL Editor, paste the contents of the Supabase schema.sql file, and click RUN to initialize the database.

[Maybe Optional] - Set up Supabase environment variables (not needed if you installed via the Deploy Button)

If you've deployed this template via the "Deploy to Vercel" button above, you can skip this step. The Supabase Vercel Integration will have set your environment variables for you. You can check this by going to your Vercel project settings, and clicking on 'Environment variables', there will be a list of environment variables with the Supabase icon displayed next to them.

Otherwise navigate to the API settings and paste them into the Vercel deployment interface. Copy project API keys and paste into the NEXT_PUBLIC_SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY fields, and copy the project URL and paste to Vercel as NEXT_PUBLIC_SUPABASE_URL.

Congrats, this completes the Supabase setup, almost there!

Configure Stripe

Next, we'll need to configure Stripe to handle test payments. If you don't already have a Stripe account, create one now.

For the following steps, make sure you have the "Test Mode" toggle switched on.

Create a Webhook

We need to create a webhook in the Developers section of Stripe. Pictured in the architecture diagram above, this webhook is the piece that connects Stripe to your Vercel Serverless Functions.

  1. Click the "Add Endpoint" button on the test Endpoints page.
  2. Enter your production deployment URL followed by /api/webhooks for the endpoint URL. (e.g. https://your-deployment-url.vercel.app/api/webhooks)
  3. Click Select events under the Select events to listen to heading.
  4. Click Select all events in the Select events to send section.
  5. Copy Signing secret as we'll need that in the next step (e.g whsec_xxx) (/!\ be careful no to copy the webook id we_xxxx).
  6. In addition to the NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY and the STRIPE_SECRET_KEY we've set earlier during deployment, we need to add the webhook secret as STRIPE_WEBHOOK_SECRET env var.

Redeploy with new env vars

For the newly set environment variables to take effect and everything to work together correctly, we need to redeploy our app in Vercel. In your Vercel Dashboard, navigate to deployments, click the overflow menu button and select "Redeploy" (do NOT enable the "Use existing Build Cache" option). Once Vercel has rebuilt and redeployed your app, you're ready to set up your products and prices.

Create product and pricing information

Your application's webhook listens for product updates on Stripe and automatically propagates them to your Supabase database. So with your webhook listener running, you can now create your product and pricing information in the Stripe Dashboard.

Stripe Checkout currently supports pricing that bills a predefined amount at a specific interval. More complex plans (e.g., different pricing tiers or seats) are not yet supported.

For example, you can create business models with different pricing tiers, e.g.:

  • Product 1: Hobby
    • Price 1: 10 USD per month
    • Price 2: 100 USD per year
  • Product 2: Freelancer
    • Price 1: 20 USD per month
    • Price 2: 200 USD per year

Optionally, to speed up the setup, we have added a fixtures file to bootstrap test product and pricing data in your Stripe account. The Stripe CLI fixtures command executes a series of API requests defined in this JSON file. Simply run stripe fixtures fixtures/stripe-fixtures.json.

Important: Make sure that you've configured your Stripe webhook correctly and redeployed with all needed environment variables.

Configure the Stripe customer portal

  1. Set your custom branding in the settings
  2. Configure the Customer Portal settings
  3. Toggle on "Allow customers to update their payment methods"
  4. Toggle on "Allow customers to update subscriptions"
  5. Toggle on "Allow customers to cancel subscriptions"
  6. Add the products and prices that you want
  7. Set up the required business information and links

That's it

I know, that was quite a lot to get through, but it's worth it. You're now ready to earn recurring revenue from your customers. 🥳

Develop locally

If you haven't already done so, clone your Github repository to your local machine.

Install dependencies

Ensure you have pnpm installed and run:

pnpm install

Next, use the Vercel CLI to link your project:

pnpm dlx vercel login
pnpm dlx vercel link

pnpm dlx runs a package from the registry, without installing it as a dependency. Alternatively, you can install these packages globally, and drop the pnpm dlx part.

If you don't intend to use a local Supabase instance for development and testing, you can use the Vercel CLI to download the development env vars:

pnpm dlx vercel env pull .env.local

Running this command will create a new .env.local file in your project folder. For security purposes, you will need to set the SUPABASE_SERVICE_ROLE_KEY manually from your Supabase dashboard (Settings > API). If you are not using a local Supabase instance, you should also change the --local flag to --remote in the supabase:generate-types script in package.json.

Local development with Supabase

It's highly recommended to use a local Supabase instance for development and testing. We have provided a set of custom commands for this in package.json.

First, you will need to install Docker. You should also copy or rename:

  • .env.local.example -> .env.local
  • .env.example -> .env

Next, run the following command to start a local Supabase instance and run the migrations to set up the database schema:

pnpm supabase:start

The terminal output will provide you with URLs to access the different services within the Supabase stack. The Supabase Studio is where you can make changes to your local database instance.

Copy the value for the service_role_key and paste it as the value for the SUPABASE_SERVICE_ROLE_KEY in your .env.local file.

You can print out these URLs at any time with the following command:

pnpm supabase:status

To link your local Supabase instance to your project, run the following command, navigate to the Supabase project you created above, and enter your database password.

pnpm supabase:link

If you need to reset your database password, head over to your database settings and click "Reset database password", and this time copy it across to a password manager! 😄

🚧 Warning: This links our Local Development instance to the project we are using for production. Currently, it only has test records, but once it has customer data, we recommend using Branching or manually creating a separate preview or staging environment, to ensure your customer's data is not used locally, and schema changes/migrations can be thoroughly tested before shipping to production.

Once you've linked your project, you can pull down any schema changes you made in your remote database with:

pnpm supabase:pull

You can seed your local database with any data you added in your remote database with:

pnpm supabase:generate-seed
pnpm supabase:reset

🚧 Warning: this is seeding data from the production database. Currently, this only contains test data, but we recommend using Branching or manually setting up a preview or staging environment once this contains real customer data.

You can make changes to the database schema in your local Supabase Studio and run the following command to generate TypeScript types to match your schema:

pnpm supabase:generate-types

You can also automatically generate a migration file with all the changes you've made to your local database schema with the following command:

pnpm supabase:generate-migration

And push those changes to your remote database with:

pnpm supabase:push

Remember to test your changes thoroughly in your local and staging or preview environments before deploying them to production!

Use the Stripe CLI to test webhooks

Use the Stripe CLI to login to your Stripe account:

pnpm stripe:login

This will print a URL to navigate to in your browser and provide access to your Stripe account.

Next, start local webhook forwarding:

pnpm stripe:listen

Running this Stripe command will print a webhook secret (such as, whsec_***) to the console. Set STRIPE_WEBHOOK_SECRET to this value in your .env.local file. If you haven't already, you should also set NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY and STRIPE_SECRET_KEY in your .env.local file using the test mode(!) keys from your Stripe dashboard.

Run the Next.js client

In a separate terminal, run the following command to start the development server:

pnpm dev

Note that webhook forwarding and the development server must be running concurrently in two separate terminals for the application to work correctly.

Finally, navigate to http://localhost:3000 in your browser to see the application rendered.

Going live

Archive testing products

Archive all test mode Stripe products before going live. Before creating your live mode products, make sure to follow the steps below to set up your live mode env vars and webhooks.

Configure production environment variables

To run the project in live mode and process payments with Stripe, switch Stripe from "test mode" to "production mode." Your Stripe API keys will be different in production mode, and you will have to create a separate production mode webhook. Copy these values and paste them into Vercel, replacing the test mode values.

Redeploy

Afterward, you will need to rebuild your production deployment for the changes to take effect. Within your project Dashboard, navigate to the "Deployments" tab, select the most recent deployment, click the overflow menu button (next to the "Visit" button) and select "Redeploy" (do NOT enable the "Use existing Build Cache" option).

To verify you are running in production mode, test checking out with the Stripe test card. The test card should not work.

nextjs-subscription-payments's People

Contributors

chriscarrollsmith avatar cjavilla-stripe avatar dalkommatt avatar dbredvick avatar dijonmusters avatar graysoncampbell avatar guylepage3 avatar hahlh avatar irvile avatar joe-bell avatar kiwicopple avatar kripod avatar leerob avatar maxleiter avatar medkrimi avatar mildtomato avatar needcaffeine avatar nezdemkovski avatar regalstreak avatar rprwhite avatar shsunmoonlee avatar thorwebdev avatar tonoli avatar victorperalta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nextjs-subscription-payments's Issues

Flicker on Sign In Page

If you already in a Sign Up page or in a Sign In page and click a Account Link the screen flickers (one time) with a Sign In Page

This happens before the user can sign in.

Reading from the code and trying to do this don't work, instead the Sign In page flashing, now it's the footer flashing

if (!user) return <>Loading...</>;

Vercel Deployment fails due to i18n incompatibility

Bug report

Describe the bug

While trying to deploy my app on vercel I encountered a problem that caused the deployment to crash. I received this error in the deployment log from Vercel:

`

21:40:23.338 info - No "exportPathMap" found in "next.config.js". Generating map from "./pages"
21:40:23.339 Error: i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/deployment
21:40:23.339 at exportApp (/vercel/workpath0/node_modules/next/dist/export/index.js:14:322)
21:40:23.352 error Command failed with exit code 1.

`

NOTE: I did have to change the 'Framework Preset' under 'Build & Development Settings' to get it to deploy without it showing the directory in the first place (https://vercel.com/docs/directory-listing), so could be related to this - But that in itself was a blocker to deploying :)

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Clone the repository
  2. Follow the integrations steps with Vercel
  3. Push a branch to master
  4. See a directory (not the served site)
  5. Change the 'Framework Preset' to Next.js
  6. Try push to master again
  7. Receive the above error
  8. Remove the i18n in the next.config file
  9. Re-deploy - great success (Although no i18n config 🤔 )

Expected behavior

  • I wouldn't have to change the config on Vercel to Next.js (It should pick up it be default right?)
  • I wouldn't have to remove the i18n config to get a successful deploy

System information

  • OS: MacOS Big Sur
  • Google Chrome
  • Yarn package manager

Additional context

This is perhaps a documentation thing, more than technical - But for a newbie to Next.js, and Vercel it was a little tricky - I'm happy to go through the flow again (re-clone a repo etc) if needed

Thanks for the fantastic template! 🎉

Convert repository to template?

Is it possible to convert this repository from a conventional repo to a GitHub template? It provides better workflows for creating private copies.

Consider using `stripe-sync-engine`

I learned that supabase is developing https://github.com/supabase/stripe-sync-engine. It seems that this could replace the code in ./utils/useDatabase.js, is that correct?

This comment in that file might be relevant:

// This entire file should be removed and moved to supabase-admin
// It's not a react hook, so it shouldn't have useDatabase format
// It should also properly catch and throw errors

Since this is a supabase integration, it might make sense to use that sync engine.

Stripe webhook failing

When I'm adding a new product on Stripe, the webhook hits my API route, but gives me the following error:

❌ Error message: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing

Has anyone else encountered this?

Cannot read property 'currency' of undefined

Hello I am using Euro currency and looks like it's problem.
Any idea how to manage it

Best regards

Unhandled error during request: TypeError: Cannot read property 'currency' of undefined
    at /vercel/path0/.next/serverless/pages/index.js:1820:29
    at Array.map (<anonymous>)
    at Pricing (/vercel/path0/.next/serverless/pages/index.js:1814:28)
    at d (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
    at bb (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
    at a.b.read (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
    at exports.renderToString (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (/vercel/path0/node_modules/next/dist/next-server/server/render.js:54:851)
    at Function.getInitialProps (/vercel/path0/.next/serverless/pages/index.js:2108:19)
Error occurred prerendering page "/". Read more: https://err.sh/next.js/prerender-error
TypeError: Cannot read property 'currency' of undefined
    at /vercel/path0/.next/serverless/pages/index.js:1820:29
    at Array.map (<anonymous>)
    at Pricing (/vercel/path0/.next/serverless/pages/index.js:1814:28)
    at d (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
    at a.b.render (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
    at a.b.read (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
    at exports.renderToString (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (/vercel/path0/node_modules/next/dist/next-server/server/render.js:54:851)
    at Function.getInitialProps (/vercel/path0/.next/serverless/pages/index.js:2108:19)
> Build error occurred
info  - Generating static pages (5/5)
Error: Export encountered errors on following paths:
	/
    at exportApp (/vercel/path0/node_modules/next/dist/export/index.js:30:1103)
    at async /vercel/path0/node_modules/next/dist/build/index.js:39:69
    at async /vercel/path0/node_modules/next/dist/build/tracer.js:1:525
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command "yarn run build" exited with 1

Deployment in Vercel fails in CHF currency

Bug report

Describe the bug

I set up products in CHF currency in Stripe, unfortunately the build in Vercel then doesn't succeed.
Upon changing them to USD, the build works.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Set products in Stripe as CHF
  2. Deploy in Vercel as suggested

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

17:24:45.574  	Cloning gitlab.com/balthasars/k_coffee (Branch: master, Commit: cdbb4fb)
17:24:46.360  	Cloning completed in 786ms
17:24:46.364  	Analyzing source code...
17:24:48.045  	Installing build runtime...
17:24:48.659  	Build runtime installed: 614.116ms
17:24:49.876  	Installing dependencies...
17:24:50.181  	yarn install v1.22.4
17:24:50.273  	[1/4] Resolving packages...
17:24:50.710  	[2/4] Fetching packages...
17:25:01.999  	info [email protected]: The platform "linux" is incompatible with this module.
17:25:01.999  	info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
17:25:02.008  	info [email protected]: The platform "linux" is incompatible with this module.
17:25:02.008  	info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
17:25:02.013  	[3/4] Linking dependencies...
17:25:02.025  	warning " > [email protected]" has unmet peer dependency "autoprefixer@^10.0.2".
17:25:07.488  	[4/4] Building fresh packages...
17:25:09.354  	Done in 19.18s.
17:25:09.382  	Running "yarn run build"
17:25:09.729  	yarn run v1.22.4
17:25:09.765  	$ next build
17:25:10.749  	info  - Creating an optimized production build...
17:25:10.768  	Attention: Next.js now collects completely anonymous telemetry regarding usage.
17:25:10.769  	This information is used to shape Next.js' roadmap and prioritize features.
17:25:10.769  	You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
17:25:10.769  	https://nextjs.org/telemetry
17:25:34.031  	info  - Compiled successfully
17:25:34.031  	info  - Collecting page data...
17:25:34.671  	info  - Generating static pages (0/9)
17:25:35.114  	info  - Generating static pages (2/9)
17:25:35.146  	info  - Generating static pages (4/9)
17:25:35.180  	info  - Generating static pages (6/9)
17:25:35.476  	Unhandled error during request: TypeError: Cannot read property 'currency' of undefined
17:25:35.476  	    at /vercel/workpath0/.next/serverless/pages/index.js:2380:29
17:25:35.476  	    at Array.map (<anonymous>)
17:25:35.476  	    at Pricing (/vercel/workpath0/.next/serverless/pages/index.js:2374:28)
17:25:35.476  	    at d (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
17:25:35.476  	    at bb (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
17:25:35.476  	    at a.b.render (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
17:25:35.476  	    at a.b.read (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
17:25:35.476  	    at exports.renderToString (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
17:25:35.476  	    at Object.renderPage (/vercel/workpath0/node_modules/next/dist/next-server/server/render.js:53:851)
17:25:35.476  	    at Function.getInitialProps (/vercel/workpath0/.next/serverless/pages/index.js:2749:19)
17:25:35.476  	Error occurred prerendering page "/en-US". Read more: https://err.sh/next.js/prerender-error
17:25:35.476  	TypeError: Cannot read property 'currency' of undefined
17:25:35.476  	    at /vercel/workpath0/.next/serverless/pages/index.js:2380:29
17:25:35.477  	    at Array.map (<anonymous>)
17:25:35.477  	    at Pricing (/vercel/workpath0/.next/serverless/pages/index.js:2374:28)
17:25:35.477  	    at d (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
17:25:35.477  	    at bb (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
17:25:35.477  	    at a.b.render (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
17:25:35.477  	    at a.b.read (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
17:25:35.477  	    at exports.renderToString (/vercel/workpath0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
17:25:35.477  	    at Object.renderPage (/vercel/workpath0/node_modules/next/dist/next-server/server/render.js:53:851)
17:25:35.477  	    at Function.getInitialProps (/vercel/workpath0/.next/serverless/pages/index.js:2749:19)
17:25:35.477  	> Build error occurred
17:25:35.477  	info  - Generating static pages (9/9)
17:25:35.483  	Error: Export encountered errors on following paths:
17:25:35.483  		/en-US
17:25:35.483  	    at exportApp (/vercel/workpath0/node_modules/next/dist/export/index.js:30:1103)
17:25:35.483  	    at runMicrotasks (<anonymous>)
17:25:35.483  	    at processTicksAndRejections (internal/process/task_queues.js:97:5)
17:25:35.483  	    at async build (/vercel/workpath0/node_modules/next/dist/build/index.js:39:69)
17:25:35.519  	error Command failed with exit code 1.
17:25:35.519  	info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
17:25:35.531  	Error: Command "yarn run build" exited with 1
17:25:39.929  	Done with "package.json"

Deployment fails.

After setting up stripe, I try to deploy and it fails.
The error is as follows

Unhandled error during request: FetchError: invalid json response body at https://---.supabase.co/rest/v1/products?

It seems that there is a problem with the supabase setting, please let me know how to solve it.

Page reloads completely upon refresh_token updates

I am trying to build an app based on this template and I noticed that my app's page reloads completely every now and then. It seems that it happens when Supabase is trying to refresh the auth token by fetching from this URL:
https://****.supabase.co/auth/v1/token?grant_type=refresh_token
But why does it lead to complete page reloads? Is it by design or am I doing something wrong?

Would appreciate any help on this issue!

getUserDetails returns first subscription result but not the actual user of subscription

inside of UserContext.js, getUserDetails selects a single record, just the first one.
const getUserDetails = () => supabase.from('users').select('*').single();

this will work for the first user but for the subsequent signups, the /account page will show the subscription for the first signup user. also, when clicking the customer portal to manage the account, it will not work.

stipe/supabase sync problem

there is a problem where stripe and supbase don't sync plans also when u add a new price to a product it syncs without the price which gives me this error .

Test coverage?

Hey guys,

I'm looking to use this as a starting point for a project very soon and was wondering if there are any plans to add test coverage to the project as this seems quite important for a commerce project :)

Pros/cons of syncing stripe data

Hi, first of all, great sample project!

Now, while browsing the code some questions came up.
For context, I'm currently running a small side project that requires more or less the same stack. Only difference is that I use next-auth w/ mongoDB currently. I now think about switching to supabase to simplify things even more.

However, I noticed a small difference between our projects. I see that you do a full sync between stripe data (products, subscriptions) and your own database. I'm wondering if this is necessary - or in other words, what are pro / cons of doing so? In comparison, I only save the stripe customer ID (and a role, after a subscription is active) and fetch products, etc. on the fly. I see the upside of having e.g. products in your own DB to not rely on the stripe API (and maybe do less requests) but is it worth the extra effort? In the end, should stripe be down, you couldn't do subscriptions anyways…

I'd be happy for your thoughts/wisdom…

Prices of products only partially syncing

First off, thanks for this wonderful and thoughtfully-written sample project! We're very grateful for it and hope this bug report helps.

@pydanny and I followed the setup instructions from the README very carefully. We ran into trouble with our prices not syncing from Stripe correctly:

  • In our Stripe dashboard, we have 2 products, each with 2 prices (monthly and yearly, similar to your example)
  • In our Next.js app running locally, it says "No subscription pricing plans found. Create them in your Stripe Dashboard."
  • When we add console.log(products) to Pricing.js after line 61, we see 2 products logged. The first strangely has only 1 price, and the second correctly has 2 prices. It looks like:
[
  {
    id: 'prod_blahblah1',
    active: true,
    name: 'Hobby',
    description: 'All the basics for starting a new business',
    image: 'blahblah',
    metadata: {},
    prices: [ [Object] ]
  },
  {
    id: 'prod_blahblah2',
    active: true,
    name: 'Freelancer',
    description: "All the basics for starting a new business",
    image: 'blahblah',
    metadata: {},
    prices: [ [Object], [Object] ]
  }
]

Expanding those price array entries, we see:

  • The first matches our Hobby year price 🎉
  • The Hobby month price is missing ❓
  • The third and fourth match our Freelancer month and year prices 🎉

Troubleshooting this, some further info:

  • https://dashboard.stripe.com/test/webhooks correctly lists our computer under “Devices receiving events with the Stripe CLI", last seen “Currently connected” to the correct Stripe account
  • We have the same exact products and prices in test and live mode
  • We're experienced at working with Stripe (we wrote/maintained a popular Stripe integration for Django years ago)

Any ideas why the monthly price object for the Hobby product isn't syncing to our local Next.js app?

Anyone else running into this?

Account Details Update Buttons

Feature request

The account details page is set up to imply that you can update your account. Entry forms and buttons that actually update these things in the database would be nice.

Describe the solution you'd like

An example of updating the name (so I can implement the email update), or full implementation by default.

Describe alternatives you've considered

Currently going to try to write it myself based on the handleSignUp logic.

Additional context

Upon a local implementation and initial signup - the Full Name didn't get added to the database. When I went to manually do it in account details, there's no buttons - thus the request.

Thanks for the starter and the project. Solves some serious headaches and is very very cool.

TypeScript?

Is there any talk about converting this template to TypeScript?

Asking for a friend

Improve login page UI

  • Submit button should not be disabled
  • Or shouldn't be italic
  • Left input spacing for the input is a bit too much

The build fails when one try to deploy

Hello I tried to test this, but the build fails when I try to deploy.

An invalid response was received from the upstream server
22:50:31.844
Unhandled error during request: {
22:50:31.844
  message: 'An invalid response was received from the upstream server'
22:50:31.844
}
22:50:31.844
22:50:31.844
Error occurred prerendering page "/". Read more: https://err.sh/next.js/prerender-error
22:50:31.844
undefined
22:50:31.845
info  - Generating static pages (5/5)
22:50:31.845
22:50:31.845
> Build error occurred
22:50:31.847
Error: Export encountered errors on following paths:
22:50:31.847
	/
22:50:31.847
    at exportApp (/vercel/path0/node_modules/next/dist/export/index.js:30:1103)
22:50:31.847
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
22:50:31.847
    at async /vercel/path0/node_modules/next/dist/build/index.js:39:69
22:50:31.847
    at async /vercel/path0/node_modules/next/dist/build/tracer.js:1:525
22:50:31.886
error Command failed with exit code 1.
22:50:31.886
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
22:50:31.904
Error: Command "yarn run build" exited with 1

I'm honestly just trying to figure out how to integrate all three of these devices together on an existing Next project on Vercel, so maybe just show me how to add them to my project.

Can't see my Stripe products on Supabase & on my site

I followed the ReadMe perfectly to set up the project. However, even though everything is configured on Vercel, Supabase & Stripe (with registered products), I can't see my subscriptions and I'm left with the message: "No subscription pricing plans found. Create them in your Stripe Dashboard. "

I noticed that the products are not updating from Stripe and the Webhook is not working. I have the following error message on Stripe:

Webhook Error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing

Thanks for any help :)

Can it work without Stripe Go Live

I've noticed Stripe Go Live is a required plugin to deploy this to Vercel. Is it possible to deploy without connecting Stripe to Vercel?

Incorrect interfaces

In these two files:

components/Pricing.tsx
pages/account.tsx

We are using:

subscription?.prices?.products?.[0]?.name

Which is incorrect as subscription.prices.products is not an array

Our current database relations are:

  • subscriptions (many to one) prices
  • prices (many to one) products

I'm not sure if the current relations are correct as I think Stripe allows to have multiple products connected with one subscription

My question is how should we fix this?

  • Should we update data base relations and getSubscription query?
  • Or should we just update how we access object property and update Price interface
subscription?.prices?.products?.name
export interface Price {
  ...
  products?: Product
}

But then I think the properties should be singular (price and product)

Is stripe sync with the database happening on the front end?

Hello
I'm trying to understand how the sync is automatically happening between stripe and supabase.

As I understood we have a webhook to stripe. So when a change is happening from stripe, we are handling the change and updating the database.

But isn't this webhook connection happening from the front end?

In other words, is there a chance for a user that goes through the payment to disconnect from the front end before the sync happens through the webhook?

In that case the user has paid but the database is not updated.

Implementing paid content page

how would i go about authenticating a user and the pricing plan they purchased to then show them the content they paid for in like a dashboard page?

Redeployment Failed

21:27:21.697 | Could not find a relationship between products and prices in the schema cache
-- | --
21:27:21.699 | Unhandled error during request: {
21:27:21.699 | hint: 'If a new foreign key between these entities was created in the database, try reloading the schema cache.',
21:27:21.700 | message: 'Could not find a relationship between products and prices in the schema cache'
21:27:21.700 | }
21:27:21.700 | Error occurred prerendering page "/". Read more: https://err.sh/next.js/prerender-error
21:27:21.701 | undefined
21:27:21.701 | info  - Generating static pages (5/5)
21:27:21.702 | > Build error occurred
21:27:21.705 | Error: Export encountered errors on following paths:
21:27:21.705 | /
21:27:21.705 | at exportApp (/vercel/path0/node_modules/next/dist/export/index.js:30:1103)
21:27:21.706 | at processTicksAndRejections (internal/process/task_queues.js:95:5)
21:27:21.706 | at async /vercel/path0/node_modules/next/dist/build/index.js:39:69
21:27:21.706 | at async /vercel/path0/node_modules/next/dist/build/tracer.js:1:525
21:27:21.748 | error Command failed with exit code 1.
21:27:21.748 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
21:27:21.769 | Error: Command "yarn run build" exited with 1

Screen Shot 2021-09-20 at 9 32 25 PM

Screen Shot 2021-09-20 at 9 36 02 PM

I followed the README to configure Stripe, but it is not working. I get the above error when trying to redeploy. I attached additional screenshots showing that I have added the environment variables and have the Stripe webhook setup.

Deploy failed

Used the deploy button from the Github readme, set up supabase, etc and got:

08:53:11.177 | Analyzing source code...
08:53:12.472 | Installing build runtime...
08:53:14.674 | Build runtime installed: 2.202s
08:53:17.285 | Looking up build cache...
08:53:17.415 | Build Cache not found
08:53:18.766 | Installing dependencies...
08:53:19.080 | yarn install v1.22.17
08:53:19.167 | [1/4] Resolving packages...
08:53:19.550 | [2/4] Fetching packages...
08:53:30.868 | [3/4] Linking dependencies...
08:53:30.872 | warning " > [email protected]" has unmet peer dependency "autoprefixer@^10.0.2".
08:53:35.432 | [4/4] Building fresh packages...
08:53:38.080 | Done in 19.01s.
08:53:38.101 | Detected Next.js version: 10.0.5
08:53:38.104 | Running "yarn run build"
08:53:38.447 | yarn run v1.22.17
08:53:38.487 | $ next build
08:53:39.321 | Browserslist: caniuse-lite is outdated. Please run:
08:53:39.322 | npx browserslist@latest --update-db
08:53:39.467 | info - Creating an optimized production build...
08:53:39.498 | Attention: Next.js now collects completely anonymous telemetry regarding usage.
08:53:39.499 | This information is used to shape Next.js' roadmap and prioritize features.
08:53:39.499 | You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
08:53:39.499 | https://nextjs.org/telemetry
08:53:39.800 | Browserslist: caniuse-lite is outdated. Please run:
08:53:39.801 | npx browserslist@latest --update-db
08:53:39.801 | Why you should do it regularly:
08:53:39.801 | https://github.com/browserslist/browserslist#browsers-data-updating
08:53:40.904 | Browserslist: caniuse-lite is outdated. Please run:
08:53:40.905 | npx browserslist@latest --update-db
08:53:40.905 | Why you should do it regularly:
08:53:40.906 | https://github.com/browserslist/browserslist#browsers-data-updating
08:54:02.348 | info - Compiled successfully
08:54:02.350 | info - Collecting page data...
08:54:02.894 | info - Generating static pages (0/5)
08:54:03.232 | info - Generating static pages (1/5)
08:54:03.311 | info - Generating static pages (2/5)
08:54:03.343 | info - Generating static pages (3/5)
08:54:03.555 | Could not find a relationship between products and prices in the schema cache
08:54:03.558 | Unhandled error during request: {
08:54:03.561 | hint: 'If a new foreign key between these entities was created in the database, try reloading the schema cache.',
08:54:03.561 | message: 'Could not find a relationship between products and prices in the schema cache'
08:54:03.561 | }
08:54:03.562 | Error occurred prerendering page "/". Read more: https://err.sh/next.js/prerender-error
08:54:03.562 | undefined
08:54:03.562 | > Build error occurred
08:54:03.562 | info - Generating static pages (5/5)
08:54:03.565 | Error: Export encountered errors on following paths:
08:54:03.565 | /
08:54:03.566 | at exportApp (/vercel/path0/node_modules/next/dist/export/index.js:30:1103)
08:54:03.567 | at processTicksAndRejections (internal/process/task_queues.js:95:5)
08:54:03.567 | at async /vercel/path0/node_modules/next/dist/build/index.js:39:69
08:54:03.567 | at async /vercel/path0/node_modules/next/dist/build/tracer.js:1:525
08:54:03.606 | error Command failed with exit code 1.
08:54:03.606 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
08:54:03.628 | Error: Command "yarn run build" exited with 1

full_name not saved when doing signup with email verification

The signup works fine, and I see the name and the user printed out (I added the log statements). However, the patch request to update the name on the user table returns a 404:

got user {id: "f79d6fce-6a19-4712-a8d5-00a2563eacf8", aud: "authenticated", role: "authenticated", email: "`[email protected]", phone: "", …}app_metadata: {provider: "email"}aud: "authenticated"confirmation_sent_at: "2021-08-19T11:56:42.870927667Z"created_at: "2021-08-19T11:56:42.867851Z"email: "[email protected]" id: "f79d6fce-6a19-4712-a8d5-00a2563eacf8"phone: ""role: "authenticated"updated_at: "2021-08-19T11:56:45.036149Z"user_metadata: null[[Prototype]]: Object
signup.js:32 

got name Adrian Krebs

PATCH https://nqltpulqdgngkiwpnjkj.supabase.co/rest/v1/users?id=eq.f79d6fce-6a19-4712-a8d5-00a2563eacf8 404

The user exists, so why is the update failing with a 404?

const handleSignup = async (e) => {
    e.preventDefault();

    setLoading(true);
    setMessage({});
    const { error, user } = await signUp({ email, password });
    if (error) {
      setMessage({ type: 'error', content: error.message });
    } else {
      if (user) {
        console.log('got user', user)
        console.log('got name', name)
        await updateUserName(user, name);
        setUser(user);
      } else {
        setMessage({
          type: 'note',
          content: 'Check your email for the confirmation link.'
        });
      }
    }
    setLoading(false);
  };

is the schema.sql automatically being import in vercel?

I would like to know if when deploying in vercel and adding supabase integration will automatically
migrate the schema.sql to my supabase account

I would want to automate the process in deploying a website database with supabase with vercel
by abstracting it to the user,

If this is possible, then its awesome, i would migrate all my netlify sites to vercel for this reason :)

Connectivity to subscription table

Connectivity to subscriptions table

Hi Thor! Thank you for the excellent tutorial!

I was able to successfully deploy and setup products/pricing through Stripe and Vercel.

When testing a subscription transaction just now in live mode, i was able to process a credit card.

Customers and Users table on supabase updates updates stripe customer id and table id, but nothing gets updated on the Subscription table.

I'd like to have my app behave accordingly based on the subscription table and its columns, but missing this integration, so just curious if i'm missing an important detail somewhere.. or if it needs to be implemented.

Appreciate your help very much!

quantity

const subscription = await stripe.subscriptions.retrieve(...) returns a subscription which does not have quantity. Guessing the relevant line should instead be: quantity: subscription.items.data[0].quantity

Supabase not saving full_name when user signs up

Hi!
I was doing a project on my own and when trying to update the users table it gives a 404 supabase error.
I have seen that it happens to more people but I cannot see why, it seems that it is related to the policies of the table, but I have tried everything and nothing works.

Desperate I have created a new project in supabase, I have cloned this repo and executed the SQL schema, but it also gives the same error.

image
image
image

I also tried with Postman but returns the same error.
Maybe is a bug with supabase or something bad configured.

Update: I disabled Row Level Policy and it worked but that's not secure

Someone else happens?

Could you add the supabase table schema to the README?

This is my first time implementing payments with all of these technologies and this repo is helping me out A LOT.

It would go even faster if I could see the schemas for all your supabase tables at a glance. It seems like many of them are complete copies of the Stripe objects, but as a new Stripe user I don't really know what those should look like. I'm particularly interested in how you are mapping stripe customers to supabase users.

Thanks for this great resource!

Question about raw_user_meta_data

What's the purpose of copying the raw_user_meta_data column value to full_name and avatar_url? Couldn't these be set just to f.ex. an empty string? Is this just a leftover or does do you do this for a reason?

values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');

How do I refresh JWT token automatically?

The JWT access token only gets refreshed on page reload.

This leads to a frustrating user experience as the access tokens expire frequently.

Any tips on how to handle token refresh without requiring the user to reload the page?

Storing billing address and payment method

In stripe, the customer portal contains information for both billing address and payment method so why is there a need to store it in supabase user's table? Is the data redundant?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.