Home > OS >  Is there a way to pay by amount on stripe using JS?
Is there a way to pay by amount on stripe using JS?

Time:07-07

Is there a way to initiate a stripe payment from the front end using stripe and js (I'm currently using Vue) without specifying products on the stripe dashboard. I would like something where I just the total amount and a payment page of that total amount gets charged to the dummy account. totalAmount = $100, description: 'Donation details',

function charge() { --- initiates a payment of 100 USD ---- } I was wondering if there is a package that could help me out with this. I'm new to front end development and wanted to check this out, feels like the answer is simple but I can't seem to find it. Thanks

CodePudding user response:

If you're using Checkout Session (hosted payment page by Stripe), you can:

  1. Ask user for the donation amount at client/frontend
  2. Send the donation amount to backend to create a Checkout Session with ad-hoc price_data instead of price under line_items: https://stripe.com/docs/products-prices/manage-prices#ad-hoc-prices
  3. Redirect user to the Checkout Session URL

Example in Step 2,

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    line_items: [
      {
        price_data: {
          unit_amount: 10000,
          currency: 'usd',
          product_data: {
            name: 'Donation',
          },
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/cancel',
  });

  res.redirect(303, session.url);
});

Reference: https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=checkout

Please note that client-only Checkout integration doesn't support ad-hoc price using price_data param, so it's not possible to do with client/frontend only. Ad-hoc price is only supported in server/backend Checkout integration.


Alternatively, you can create a price with pay-what-you-want in Dashboard, i.e. amount entered by customer in Checkout Session page: https://stripe.com/docs/payments/checkout/pay-what-you-want

After that, client-only Checkout integration provided by community library, vue-stripe with pay-what-you-want price ID can be used: https://docs.vuestripe.com/vue-stripe/stripe-checkout/one-time-payment

  • Related