Stripe Checkout Session for custom products
Dave Jodhan
Posted on October 24, 2024
As far as payment processors are concerned, Stripe is definitely up there as far as ease of implementation is concerned.
They've done an excellent job at providing extensive documentation and code samples, which, makes simple transactions almost a copy/paste activity.
Stripe's quick start guide provides an opportunity to select your front end language, your back end language and you can simply copy/paste the samples.
However, the kicker is that their guide relies on setting up inventory on their platform.
Let's take a look at the checkout_session object, specifically, the 'price' key in the line_items list of price dictionaries :
checkout_session = stripe.checkout.Session.create(
line_items=[
{
# Provide the exact Price ID (for example, pr_1234) of the product you want to sell
'price': '{{PRICE_ID}}',
'quantity': 1,
},
],
mode='payment',
success_url=YOUR_DOMAIN + '?success=true',
cancel_url=YOUR_DOMAIN + '?canceled=true',
)
A valid PRICE_ID is one defined on Stripe's platform.
What if, for example, you wish to maintain your own inventory, while still leveraging Stripe as a payment processor? Do you manage two sets of inventories, one on Stripe and your own (totally viable programmatically)? Do you migrate your entire inventory to Stripe?
Well, it is possible to simply manage your own inventory and just leverage the checkout function on Stripe. It's not immediately obvious reading through the documentation. However, buried in the API docs is an alternative method of defining a product, along with price and description using a price_data dictionary (in place of the price key), which looks something like this.
"price_data" : {
"currency" : "usd",
"product_data":{
"name": "bead necklace"
},
"unit_amount": 2000,
}
A complete checkout session object will then look like this:
checkout_session = stripe.checkout.Session.create(
line_items=[
{
"price_data" : {
"currency" : "usd",
"product_data":{
"name": "bead necklace"
},
"unit_amount": 20000,
},
"quantity": 1
}
],
mode="payment",
success_url="?success=true",
cancel_url="?canceled=true"
)
A more scalable approach would be to populate the line_items list with values from your own inventory database, if maintaining your own inventory is part of your overall system design.
Happy coding!!
Posted on October 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.