Mark As Completed Discussion

To integrate a third-party payment gateway into your app, you need to follow the provider's documentation and use their SDK or API. Let's take the example of integrating the Stripe payment gateway.

  1. First, you need to install the Stripe package using a package manager like npm or yarn. Replace YOUR_STRIPE_API_KEY with your actual API key.
JAVASCRIPT
1const stripe = require('stripe')(process.env.YOUR_STRIPE_API_KEY);
  1. Next, you can create a payment intent using the stripe.paymentIntents.create method. Specify the amount, currency, description, and any metadata you want to associate with the payment.
JAVASCRIPT
1const paymentIntent = await stripe.paymentIntents.create({
2  amount: 1000, // Amount in cents
3  currency: 'usd',
4  description: 'Payment for Order #123',
5  metadata: {
6    orderId: '123',
7    customerName: 'John Doe'
8  }
9});
  1. Retrieve the client secret from the payment intent. The client secret is a unique identifier for the payment intent and should be passed to the front-end.
JAVASCRIPT
1const clientSecret = paymentIntent.client_secret;
  1. Render the payment form on the front-end and collect the payment details from the user. You can use Stripe's pre-built Checkout or Elements components to handle this step.

  2. Once the user submits the payment form, retrieve the payment method details (e.g., card number, expiry date, CVV) from the form.

  3. Confirm the payment intent using the stripe.paymentIntents.confirm method. Pass the client secret and the payment method details to the method.

JAVASCRIPT
1const confirmedPaymentIntent = await stripe.paymentIntents.confirm(
2  clientSecret,
3  {
4    payment_method: {
5      card: {
6        number: '4242424242424242',
7        exp_month: 12,
8        exp_year: 2023,
9        cvc: '123'
10      }
11    }
12  }
13);
  1. Handle the payment confirmation response. If the payment is successful, the status property of the confirmed payment intent will be 'succeeded'. Otherwise, you can check the last_payment_error property for more details about the failure.
JAVASCRIPT
1if (confirmedPaymentIntent.status === 'succeeded') {
2  // Payment succeeded
3  console.log('Payment succeeded!');
4} else {
5  // Payment failed
6  console.log('Payment failed: ', confirmedPaymentIntent.last_payment_error ? confirmedPaymentIntent.last_payment_error.message : 'Unknown error');
7}
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment