In this document, we'll explore about how we can integrate stripe with supabase using edge function in flutterflow. We will learn how to create edge function how to deploy them and use it as a API in flutterflow. By the end, you'll be able to create edge functions and stripe checkout link.
Edge functions are small pieces of code that run on servers close to the user, allowing developers to add custom logic to their applications. They're a type of serverless computing that can improve application performance, scalability, and security.
How they work
Use Cases of Edge Functions:
Benefits of Edge Functions:
Popular Edge Function Providers:
Before we proceed, please follow the steps to get started:-
Create edge function
Now let’s start creating our new edge function for stripe checkout link. Firstly, create a folder at your desired destination with any name you want. Here I’m naming my folder as edge_function.
Ok, so let’s open this folder in VS code. Now open terminal and run below commands to move forward
Now all the required files will be created in your folder edge_function\supabase\functions\stripe-checkout. index.ts is our main file in which we will code to generate our checkout link.
Let’s login in our supabase account before proceeding further. Run this command to your terminal to log in supabase account.
npx supabase login
The provider which we are gonna use in our edge function is deno sp let’s add as extension in VS code. In the left menu bar in vs code.
Now let’s setup our local server, Docker desktop. Open Docker and navigate to settings then select general select ‘expose daemon on tcp’ right there.
Hoorah, all setup is now done.
It’s time to start coding for our stripe integration in supabase.
import { serve } from "<https://deno.land/std@0.176.0/http/server.ts>";
import Stripe from "<https://esm.sh/stripe@12.0.0>";
const stripe = new Stripe('stripe_live_key', {
apiVersion: "2022-11-15",
});
// To remove CORS error in web platform.
const corsHeaders = {
"Access-Control-Allow-Origin": "*", // Allow all origins (change for security)
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true",
"Content-Type": "application/json",
};
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers: corsHeaders });
}
if (req.method === "POST") {
try {
const body = await req.json();
if (!body.amount || body.amount <= 0) {
return new Response(
JSON.stringify({ error: "Invalid amount provided." }),
{ status: 400, headers: corsHeaders },
);
}
const amount = body.amount;
const userId = body.user_id;
const orderId = body.order_id;
// Create a Checkout Session
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "ron",
product_data: {
name: "Amount",
},
unit_amount: amount, // Amount in cents
},
quantity: 1,
},
],
mode: 'payment',
phone_number_collection: {
enabled: true, // Enable phone number collection
},
success_url: 'success_url',
cancel_url: 'cancel_url',
expires_at: Math.floor(Date.now() / 1000) + 1800, // Expires in 5 minutes (300 seconds)
});
return new Response(
JSON.stringify({
url: session.url
}),
{ status: 200, headers: corsHeaders },
);
} catch (err) {
console.error(err);
return new Response(
JSON.stringify({ error: "Failed to create checkout session" }),
{ status: 500, headers: corsHeaders },
);
}
} else {
return new Response("Method Not Allowed", { status: 405 });
}
});
Just change the ‘stripe_live_key’ with your live key along with ‘success_url’ and ‘cancel_url’, and now your edge function is ready. You can make other changes according to your requirements.
Let’s run the function locally to test. To do so run the following commands
It will create a localhost for you with this you can test it in your local environment.
http://your_local_host/functions/v1/stripe-checkout
This will be your complete url and in body you can pass amount, user_id and order_id along with any other field you require.
Also pass a header for authorization:
Authorization: Bearer supabase_public_key
To find this public key, go to your supabase project settings then select Data API and under Project API Keys section you’ll find you public key.
As we’re done with our local testing. Let’s deploy it to supabase. Deploying it is very much simple just run below command and you are done.
npx supabase functions deploy stripe-checkout --project-ref project_id
Replace project_id with your actual project id which you find in supabase project settings.
Congratulation 🎊, Your edge function is now live. Go to supabase open your project and in left navigation menu you can find one tab named Edge Functions. Click on it and you can find your newly deployed edge function. Copy the url from there and this will be your api URL.
Now simply use it in your flutterflow project and you are good to go.
Throughout this journey, we've gained valuable insights into Supabase Edge Functions, exploring how they provide a powerful and scalable way to enhance our applications. We also learned how to set up a local testing environment, allowing us to debug and refine our functions efficiently before deployment.
Additionally, we successfully integrated Stripe with Supabase in FlutterFlow, enabling seamless payment processing within our app. This combination of serverless functions, database interactions, and payment integration empowers us to build feature-rich, dynamic applications with minimal backend complexity.