Supabase

How to integrate Supabase with Stripe for payments?

Discover the effortless way to connect Supabase with Stripe for hassle-free payment processing. Enjoy clear, step-by-step instructions ensuring a smooth setup every step of the way.

Developer profile skeleton
a developer thinking

Overview

Connecting Supabase and Stripe for payments merges Supabase's database and authentication functionalities with Stripe's top-notch payment processing. This blend lets you handle user data smoothly while ensuring safe transactions. What does it usually involve? Setting up a Supabase project, configuring those Stripe API keys, creating webhooks for real-time updates, and syncing user and payment info. With this integration, you'll be able to create scalable, data-driven applications that come with full payment features.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to integrate Supabase with Stripe for payments?

Step 1: Set Up a Supabase Project

  1. Create a Supabase Account: Head over to the Supabase website and sign up for an account.
  2. Create a New Project: Once you're logged in, start a new project. You'll need to fill in some details like the project name, password, and pick a database region.
  3. Get API Keys: After your project is up and running, go to the API settings. Jot down the URL and Anon Key—you'll need these later.

Step 2: Set Up a Stripe Account

  1. Create a Stripe Account: Visit the Stripe website and sign up for an account.
  2. Create a New Project in Stripe: In your Stripe dashboard, create a new project.
  3. Get API Keys: Go to the API settings of your project and grab the Publishable Key and Secret Key for later use.

Step 3: Create a Database Table in Supabase

  1. Navigate to SQL Editor: Open the SQL editor in your Supabase dashboard.
  2. Create a Payments Table: Run this SQL script to set up a table for storing payment info:
    ```sql
    create table payments (
    id bigint generated by default as identity primary key,
    user_id uuid references auth.users (id),
    stripe_customer_id text,
    stripe_payment_id text,
    amount decimal,
    status text,
    created_at timestamp with time zone default current_timestamp
    );
    ```

Step 4: Configure Environment Variables

  1. Create a .env File: In your project directory, create a .env file.
  2. Add Keys to .env File: Put your Supabase and Stripe keys in there:
    ```env
    SUPABASE_URL=your_supabase_url
    SUPABASE_ANON_KEY=your_supabase_anon_key
    STRIPE_SECRET_KEY=your_stripe_secret_key
    ```

Step 5: Install Dependencies

npm install @supabase/supabase-js stripe

Step 6: Initialize Supabase and Stripe in Code

  1. Set Up Supabase Client:
    ```javascript
    const { createClient } = require('@supabase/supabase-js');
    const supabaseUrl = process.env.SUPABASE_URL;
    const supabaseAnonKey = process.env.SUPABASE_ANON_KEY;
    const supabase = createClient(supabaseUrl, supabaseAnonKey);
    ```

  2. Set Up Stripe Client:
    ```javascript
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    ```

Step 7: Handle Customer Creation

  1. Create a Function to Handle New Customers:
    ```javascript
    async function createCustomer(email) {
    const customer = await stripe.customers.create({ email });
    return customer.id;
    }
    ```

  2. Store Customer ID in Supabase:
    ```javascript
    async function saveCustomer(user_id, stripeCustomerId) {
    const { data, error } = await supabase
    .from('payments')
    .insert([{ user_id, stripe_customer_id: stripeCustomerId }]);
    if (error) throw error;
    }
    ```

  3. Link the Functions in Your Sign-Up Flow:

```javascript
async function signUpUser(email, password) {
const { user, error } = await supabase.auth.signUp({ email, password });
if (error) throw error;
const stripeCustomerId = await createCustomer(email);
await saveCustomer(user.id, stripeCustomerId);
}
```

Step 8: Handle Payments

  1. Create Payment Intent:
    ```javascript
    async function createPaymentIntent(amount, currency, customerId) {
    const paymentIntent = await stripe.paymentIntents.create({
    amount: Math.round(amount * 100), // Stripe accepts amount in cents
    currency,
    customer: customerId,
    });
    return paymentIntent.client_secret;
    }
    ```

  2. Save Payment Information:
    ```javascript
    async function savePayment(paymentIntent, userId, amount) {
    const { data, error } = await supabase
    .from('payments')
    .insert([{
    user_id: userId,
    stripe_payment_id: paymentIntent.id,
    amount,
    status: paymentIntent.status
    }]);
    if (error) throw error;
    }
    ```

Step 9: Integrate Webhooks for Stripe Events

  1. Set Up Express Server (or appropriate server middleware):
    ```javascript
    const express = require('express');
    const app = express();
    app.use(express.json());
    ```

  2. Create a Route to Handle Webhooks:
    ```javascript
    const endpointSecret = 'your_endpoint_secret';
    app.post('/webhook', express.raw({ type: 'application/json' }), (request, response) => {
    const sig = request.headers['stripe-signature'];
    let event;
    try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
    } catch (err) {
    return response.status(400).send(Webhook Error: ${err.message});
    }

    // Handle specific event
    if (event.type === 'payment_intent.succeeded') {
    const paymentIntent = event.data.object;
    updatePaymentStatus(paymentIntent.id, 'succeeded');
    }
    response.json({ received: true });
    });
    ```

  3. Update Payment Status Function:

```javascript
async function updatePaymentStatus(paymentId, status) {
const { data, error } = await supabase
.from('payments')
.update({ status })
.eq('stripe_payment_id', paymentId);
if (error) throw error;
}
```

  1. Start the Server:
    ```javascript
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => console.log(Server running on port ${PORT}));
    ```

Careful implementation of the above steps will integrate Supabase with Stripe for payments efficiently. Always ensure secure handling of API keys and sensitive information.

Explore more Supabase tutorials

Complete Guide to Supabase: Tutorials, Tips, and Best Practices

Explore our Supabase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.