How to create a Stripe payment link on client side without exposing secret key

1.1k Views Asked by At

I am trying to make a simple website to sell various products that does not rely at all on a backend server. The goal is to make the end website completely static, meaning it is able to be served by something like GitHub pages. I am trying to use Stripe payment links for users to checkout. The following process is what I am trying to do -

  1. user navigates the website adding various products to a cart (cart info is stored in browser local storage)
  2. user clicks the checkout button which makes a post request to https://api.stripe.com/v1/payment_links to create a new Stripe payment link with the correct body corresponding to the items in the user's cart
  3. response comes from back from Stripe with the new payment link, redirect the user here to checkout with Stripe

The problem I am facing is that in order to make this request a secret key has to be used. So in the client side code I could have the following -

fetch("https://api.stripe.com/v1/payment_links", {
    method: "POST", 
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer {{STRIPE_SECRET_KEY}}',
    },
    body: makeBody(),
})

This is not good because it reveals to anyone using the website the Stripe secret key. Is there anyway to get this functionality I am looking for without having to run a server and without revealing any secret API keys?

One approach that I tried is to use a restricted API key (https://stripe.com/docs/keys#limit-access), which only has write access to payment links. Unfortunately, anyone with this key could also do something malicious like deactivate all payment links as soon as they are created.

1

There are 1 best solutions below

0
Nolan H On

You can't. Creating a new Payment Link via the API requires a secret key, and there is no way to do this safely client side.

You need to either: 1/ Generate/create fixed payment links ahead of time to let your users access when needed

2/ Set up a back end to generate payment links dynamically. If you're creating this bespoke for each customer based on some highly variable "cart" of products, you likely want to use Checkout Sessions directly instead of Payment Links.