Skip to content

Latest commit

 

History

History
185 lines (143 loc) · 6.4 KB

README.md

File metadata and controls

185 lines (143 loc) · 6.4 KB

Stripe Checkout For ApostropheCMS


License

Unit Tests


This module adds a custom route to initiate a Stripe Checkout instance and another route triggered by a webhook listener for incoming completed session events and to save them in the database as a piece type that can be easily accessible via the admin UI.


Checkout
Admin UI 1 Admin UI 2 Admin UI 3

Installation

Use your preferred package manager to install the module. You'll also need to install the read-only-field package alongside it:

npm install stripe-checkout@npm:@stepanjakl/apostrophe-stripe-checkout

npm install read-only-field@npm:@stepanjakl/apostrophe-read-only-field

Examples

It is highly recommended to explore the apostrophe-stripe-examples repository, which offers a comprehensive set of examples and full configurations demonstrating how to set up a complete e-commerce store experience.


Usage

First, add installed modules to your configuration in the app.js root file:

require('apostrophe')({
  shortName: 'project-name',
  modules: {
    // Custom fields
    'read-only-field': {},

    // Stripe Checkout
    'stripe-checkout': {},
    'stripe-checkout/session': {}
  }
});

Then, set global variables inside the .env file. It's important to set the STRIPE_TEST_MODE variable to anything other than false to enable test mode.

PORT='4000'
APOS_BASE_URL='http://localhost:4000'
APOS_RELEASE_ID='a4-boilerplate'
APOS_MONGODB_URI='mongodb://localhost:27017/a4-boilerplate'

STRIPE_KEY='sk_test_xyz'
STRIPE_TEST_MODE='false'
STRIPE_DASHBOARD_BASE_URL='https://dashboard.stripe.com'
STRIPE_WEBHOOK_ENDPOINT_SECRET='whsec_xyz'

Read more on how to create a secret Stripe API key

The webhook signing secret is generated and displayed on the initial output of the listen command - more on this below.


API Routes

The stripe-checkout module comes with two custom API routes:


'/api/v1/stripe-checkout/sessions/create':

This API route handles POST requests to create a new Stripe Checkout Session. It is a central piece of the module and facilitates initiating payment transactions through Stripe. Here's an example of a request using the Fetch API directly in the browser:

const requestOptions = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    line_items: [
      {
        price: 'price_test_abc',
        quantity: 2
      },
      {
        price: 'price_test_xyz',
        quantity: 1
      }
    ],
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/cancel'
  })
};

fetch('/api/v1/stripe-checkout/sessions/create', requestOptions)
  .then(response => {
    if (!response.ok) {
      throw new Error('Failed to create checkout session');
    }
    return response.json();
  })
  .then(data => {
    // Handle the response data, e.g., redirect to the checkout URL
    const checkoutUrl = data.url;
    console.log('Checkout URL:', checkoutUrl);
    // Example: Redirecting to the checkout URL
    window.location.href = checkoutUrl;
  })
  .catch(error => {
    console.error('Error:', error);
    // Handle errors, e.g., show an error message to the user
  });

'/api/v1/stripe-checkout/webhook':

This API route is used by the local listener to receive asynchronous Stripe events and save the completed checkout sessions to the database.

Set up event forwarding with the Stripe CLI and send all Stripe events to your local webhook endpoint for testing and/or monitoring purposes:

stripe listen --events=payment_intent.succeeded --forward-to localhost:5000/api/v1/stripe-checkout/webhook

Use the PM2 process manager to run the listen command in production:

pm2 start --name stripe-listener "stripe listen --events=checkout.session.completed --forward-to localhost:5000/api/v1/stripe-checkout/webhook"

Read more about the Stripe webhooks


TODOs (Improvements)

  • Enable checkout session with more than 99 products