# Fulfill orders

Fulfill orders on your server after customers pay with Mobile Checkout Elements.

Mobile Checkout Elements payments might require you to take action to fulfill orders. For example, you might need to grant them access to a service, or you might need to ship them physical goods. You have two ways to handle this process:

- **Manually**: You can manually fulfill orders using information that Stripe makes available to you. For example, you can monitor the [Dashboard](https://docs.stripe.com/dashboard/basics.md), check payment notification emails, or look at reports and then fulfill orders.
- **Automatically**: You can build an automated fulfillment system. (Recommended)

The first option works for low volume or experimental ventures, but for most situations we recommend automating fulfillment. The rest of this guide shows you how to build an automatic fulfillment system.

> #### Fulfillment requires webhooks
> 
> Automatic fulfillment requires webhooks if you accept payment methods with [delayed success notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification), because their subsequent state changes only after the Checkout Session completes.

## Automatic fulfillment 

The automatic fulfillment system outlined below uses *webhooks* (A configurable endpoint that executes when it receives certain event notifications from an event destination) to trigger fulfillment. You must use webhooks to make sure fulfillment happens for every payment.

## Create a fulfillment function [Server-side]

Create a function on your server to fulfill successful payments. Webhooks trigger this function. This guide refers to this function as `fulfill_checkout`, but you can name the function whatever you wish.

Perform fulfillment only once per payment. Because of how this integration and the internet work, your `fulfill_checkout` function might be called multiple times, possibly concurrently, for the same Checkout Session. Performing checkout only once ensures this won’t cause undesired behavior.

Your `fulfill_checkout` function must:

1. Correctly handle being called multiple times with the same Checkout Session ID.
2. Accept a *Checkout Session* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription) ID as an argument.
3. Retrieve the Checkout Session from the API.
4. Check the [payment_status](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-payment_status) property to determine if it requires fulfillment.
5. Perform fulfillment of the purchased items.
6. Record fulfillment status for the provided Checkout Session.

Use the code below as a starting point for your `fulfill_checkout` function. The `TODO` comments indicate any functionality you must implement.

Use the Stripe client you configured when [creating the Session](https://docs.stripe.com/payments/mobile/checkout-sessions/build-a-checkout-page.md#create-checkout-session).

```node
async function fulfillCheckout(sessionId) {
  console.log('Fulfilling Checkout Session ' + sessionId);

  // TODO: Make this function safe to run multiple times,
  // even concurrently, with the same session ID

  // TODO: Make sure fulfillment hasn't already been
  // performed for this Checkout Session

  // Retrieve the Checkout Session from the API
  const checkoutSession = await stripe.checkout.sessions.retrieve(sessionId);

  // Check the Checkout Session's payment_status property
  // to determine if fulfillment should be performed
  if (checkoutSession.payment_status !== 'unpaid') {
    // TODO: Perform fulfillment of the purchased items

    // TODO: Record/save fulfillment status for this
    // Checkout Session
  }
}
```

Depending on the payment methods you accept and your business needs, you might want to have your `fulfill_checkout` function do the following:

- Provision access to services.
- Trigger shipment of goods.
- Save a copy of the payment details and line items in your own database.
- Send the customer a custom receipt email if you don’t have [Stripe receipts](https://docs.stripe.com/receipts.md) enabled.
- Reconcile line items and quantities purchased if you allow customers to adjust quantities in your app.
- Update inventory or stock records.

## Create a payment event handler [Server-side]

To trigger fulfillment, create a webhook event handler to listen for payment events and trigger your `fulfill_checkout` function.

When someone pays you, it creates a `checkout.session.completed` event. Set up an endpoint on your server to accept, process, and confirm receipt of these events.

### Immediate versus delayed payment methods

Some payment methods aren’t [instant](https://docs.stripe.com/payments/payment-methods.md#payment-notification), such as [ACH direct debit](https://docs.stripe.com/payments/ach-direct-debit.md) and other bank transfers. This means, funds won’t be immediately available when Checkout completes. Delayed payment methods generate a [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) event when payment succeeds later. The status of the object is in processing until the payment status either succeeds or fails.

> The webhook secret (`whsec_...`) shown in the code below comes from either the Stripe CLI or your webhook endpoint. You can use the Stripe CLI for local testing, and Stripe uses a webhook endpoint to send events to your handler when it’s running on a server. See the next section for more details.

#### Ruby

```ruby
require 'sinatra'

# Use the secret provided by Stripe CLI for local testing
# or your webhook endpoint's secret.
endpoint_secret = 'whsec_...'

post '/webhook' do
  event = nil

  # Verify webhook signature and extract the event
  # See https://stripe.com/docs/webhooks#verify-events for more information.
  begin
    sig_header = request.env['HTTP_STRIPE_SIGNATURE']
    payload = request.body.read
    event = Stripe::Webhook.construct_event(payload, sig_header, endpoint_secret)
  rescue JSON::ParserError => e
    # Invalid payload
    return status 400
  rescue Stripe::SignatureVerificationError => e
    # Invalid signature
    return status 400
  end

  if event['type'] == 'checkout.session.completed' ||
  event['type'] == 'checkout.session.async_payment_succeeded'
    fulfill_checkout(event['data']['object']['id'])
  end

  status 200
end
```

You might also want to listen for and handle `checkout.session.async_payment_failed` events. For example, you can send an email to your customer when a delayed payment fails.

### Use Workflows to notify your team about payment failures 

To notify your team about failed delayed payments without writing code, use [Workflows](https://docs.stripe.com/workflows.md) with the [Notify your team when a delayed Checkout payment fails](https://dashboard.stripe.com/workflows/create?workflow=eyJkZWVwX2xpbmtfdmVyc2lvbiI6MSwibmFtZSI6Ik5vdGlmeSB5b3VyIHRlYW0gd2hlbiBhIGRlbGF5ZWQgQ2hlY2tvdXQgcGF5bWVudCBmYWlscyIsImRlZmluaXRpb24iOiJDdDRDRXFzQ0NoRmxiV0ZwYkY5MFpXRnRYMjFsYldKbGNoQUJHcE1DQ2lwemRISnBjR1V1YzJWdVpGOXRaWEpqYUdGdWRGOXViM1JwWm1sallYUnBiMjVmWlcxaGFXeGZkaklTNUFFSzRRRUtCRzFsYlc4UzJBRWExUUZCSUdSbGJHRjVaV1FnUTJobFkydHZkWFFnY0dGNWJXVnVkQ0JtWVdsc1pXUXVJRkpsZG1sbGR5QjBhR1Z6WlNCa1pYUmhhV3h6SUdKbFptOXlaU0JtZFd4bWFXeHNhVzVuSUhSb1pTQnZjbVJsY2k0S1EyaGxZMnR2ZFhRZ1UyVnpjMmx2YmlCSlJEb2dKSHQ3SUhSeWFXZG5aWEl1YVdRZ2ZYMEtRM1Z6ZEc5dFpYSWdaVzFoYVd3NklDUjdleUIwY21sbloyVnlMbU4xYzNSdmJXVnlYMlJsZEdGcGJITXVaVzFoYVd3Z2ZYMEtRVzF2ZFc1ME9pQWtlM3NnZEhKcFoyZGxjaTVoYlc5MWJuUmZkRzkwWVd3Z2ZYMGFMZ2dDRWlvS0pXTm9aV05yYjNWMExuTmxjM05wYjI0dVlYTjVibU5mY0dGNWJXVnVkRjltWVdsc1pXUWFBUUVTRVRJd01qWXRNRGt0TXpBdVpXNWthWFpsIiwic3RyaXBlX2FwaV92ZXJzaW9uIjoiMjAyNi0wOS0zMC5lbmRpdmUifQ) template. It triggers when a delayed Checkout payment fails and emails your team the customer’s email, the amount, and the Checkout Session ID. Choose the team members to notify before publishing the workflow.

## Test your event handler locally

The quickest way to develop and test your webhook event handler is with the [Stripe CLI](https://docs.stripe.com/cli.md). If you don’t have the Stripe CLI, follow the [install guide](https://docs.stripe.com/cli/install) to get started.

When the Stripe CLI is installed, you can test your event handler locally. Run your server (for example, on `localhost:4242`), then run the [stripe listen](https://docs.stripe.com/cli/listen) command to have the Stripe CLI forward events to your local server:

```bash
stripe listen --forward-to localhost:4242/webhook

Ready! Your webhook signing secret is 'whsec_<REDACTED>' (^C to quit)
```

Add the webhook secret (`whsec_...`) to your event handling code, then test fulfillment by going through checkout in your app as a customer:

- Open checkout in your app
- Provide the following test data in your app:
  - Enter `4242 4242 4242 4242` as the card number
  - Enter any future date for card expiration
  - Enter any 3-digit number for CVV
  - Enter any billing postal code (`90210`)
- Press the **Pay** button

When the payment completes, verify the following:

- On your command line, where `stripe listen` is running, it shows a `checkout.session.completed` event forwarded to your local server.
- Your server logs show the expected output from your `fulfill_checkout` function.

## Create a webhook endpoint

After testing locally, get your webhook event handler up and running on your server. Next, [create a webhook endpoint](https://docs.stripe.com/webhooks.md#register-webhook) to send `checkout.session.completed` events to your server, then test the checkout flow in your app again. If you accept delayed payment methods, also subscribe to `checkout.session.async_payment_succeeded`.
