> For the complete documentation index, see [llms.txt](https://docs.appfarm.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.appfarm.io/how-to/integrations/integrate-with-a-payment-provider.md).

# Integrate with a payment provider

## Stripe Prebuilt Checkout page

This guide will describe how to set up payment using the third-party payment service Stripe. As an example, we will use a one-time payment of multiple items (e.g. a user purchasing several items from a web store).

To complete this guide, you'll need a Stripe account. If you don't have that already, go to [Stripe to register a new account](https://dashboard.stripe.com/register). We'll use the Stripe test environment for this guide, but the setup would be the same for a production environment.

### Step 1

Create your web store as an app in Appfarm. Make sure you have a data source with all the products that can be purchased (e.g. products), and one with all the products the user wants to purchase (i.e. "shopping cart" or "order items").

Furthermore, you'll need two landing views with the URL Path Key set; one for payment success and one for payment failure (e.g. `https://[HOSTNAME].appfarm.app/[APPNAME]/success`)

### Step 2

Go to <https://dashboard.stripe.com/test/products>. For each product you want to sell, click add product. Then, copy the Pricing API ID (e.g. `price_1LVDmlCKVzgiw1WewxzdGvQl`) and save it to a property on the corresponding product object.

You may also add these products dynamically using the [Stripe Products API](https://stripe.com/docs/api/products).

### Step 3

Go to <https://dashboard.stripe.com/test/apikeys>. Under "Secret key" click "Reveal test key". Copy the key, and save it as a secret under Appfarm Create -> **Security** > **Secrets**.

### Step 4

Go to Appfarm Create -> App Data -> App Variables, and add a new Runtime Property named "URL".

### Step 5

{% hint style="warning" %}
**Important**

Values sent from the browser can be changed by the user. With the setup below, a user can change the items, price IDs or quantities sent to Stripe. For production, create the checkout session in a [Flow](https://docs.appfarm.io/reference/flows.md) action started with Run Flow:

* Pass only the order ID to the Flow.
* In the Flow, read the order items, check that the order belongs to the user in the Flow variable **Current User ID**, and look up the Stripe price IDs from your products.
* Encode each value with `encodeURIComponent`.
* Return only the checkout URL.

Give the Flow action permissions only for the roles that check out.
{% endhint %}

Go to your checkout in your app, and create a new action. Add the action node web request with the following properties:

* **Base URL:** `https://api.stripe.com`
* **Path:** `/v1/checkout/sessions`
* **Query Parameters:**
  * success\_url: *Success URL from Step 1*
  * cancel\_url: *Failure URL from Step 1*
  * Mode: Payment
* **Request Headers:**
  * Content-Type: application/x-www-form-urlencoded
* **Authorization:**
  * **Type:** Basic Auth
  * **Username:** *The test key from Step 3*
  * **Password:** `Null`
* **Method:** POST
* **Body Type:** Raw
* **Body Content:** Function:

```javascript
// We will create a string with each order item displayed in the following format: 
// &line_items[0][price]=price_1LVDltCK&line_items[0][quantity]=1

let string = ''
let orderItems = {{INSERT DATA SOURCE WITH ORDER ITEMS}}

// Iterate all items in the data source
orderItems.forEach((item, index) => {
    // Add price API ID to string
    string += `&line_items[${index}][price]=${item.{{PRICING API ID PROPERTY}} }`
    // Add quantity to string
    string += `&line_items[${index}][quantity]=${item.{{QUANTITY PROPERTY}} }`
})

return string
```

* **Content-Type:** Custom
* **Result Mapping:**
  * **Data Source:** App Variables
  * **URL:** url

{% hint style="info" %}
**Good to know**

The function above builds the form-encoded body by hand because the number of order items varies. When the body has a fixed set of fields, set **Body type** to `URL-encoded` instead and add each field as form data. The web request then encodes the body and sets the content type for you.
{% endhint %}

### Step 6

Add action node *Open URL* and set the Value to *App Variables.URL.* The payment flow should now work.

### Step 7

You may now create the logic in Appfarm to process the status of the payment in Stripe (e.g. to handle a successful payment). This is done with an [API endpoint](https://docs.appfarm.io/reference/flows/api-endpoints.md) in a [Flow](https://docs.appfarm.io/reference/flows.md). Stripe sends the payment result to the endpoint, and the endpoint's action handles and saves the result.

Go to **Flows** and create a new Flow (or open an existing one). Give the Flow a root path: when you create an API Endpoints Flow you enter it as **Root path**, and it shows under the Flow name. Add a new endpoint under **API Endpoints**. In the endpoint's **Endpoint config**, set **Methods** to `POST`, note the **Path**, and use **Body data** to define a schema for the fields you need from Stripe's event. Then add the logic that handles the payment to the endpoint's action.

{% tabs %}
{% tab title="Example setup" %}
Here is an example setup of this endpoint, with mapping of incoming JSON to our internal data source `Payment`. The property `Payment status` is used in the action to handle whether the payment was successful or not ("paid" is received upon successful payment). The screenshot shows the same mapping on a Service endpoint, which older solutions may still use.

<figure><img src="https://29237295-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MiLU-xcHu0eLZiTxcmZ%2Fuploads%2F89Nvrzgx5P7g8DYaUw3E%2Fimage.png?alt=media&amp;token=0b55de9c-0ab8-4dda-8369-a389f3b2aa40" alt=""><figcaption><p>Example setup - Service Endpoint (webhook for Stripe)</p></figcaption></figure>
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
**Important**

Anyone who has the endpoint URL and key can call it. Don't mark an order as paid only because the request says so. Before you update the order, check the payment with Stripe, for example by fetching the checkout session from the Stripe API with a web request.
{% endhint %}

### Step 8

Set up a new Role with permission to run the Flow endpoint, and add a Service Account with that role. Create an API key for the Service Account, and copy the key to your notepad. Give the key access to this Flow only, and set an expiry date.

### Step 9

This step is for telling Stripe where to send the payment status. Go to <https://dashboard.stripe.com/webhooks> and add a new endpoint.

Under *Endpoint URL*, put the following URL: `https://[HOSTNAME].appfarm.app/api/flows/[API root path]/[endpoint path]?token=[API key]`

Under *Select events to listen to* add `checkout.session.completed`.

{% hint style="warning" %}
**Important**

Stripe can't add custom headers to webhook requests, so the API key goes in the URL here. Keys in URLs can end up in logs and browser history. Where a caller supports it, send the key in an `Authorization: Bearer` header instead. Use a dedicated key for Stripe that can only run this Flow, and replace it if it leaks.
{% endhint %}

### Testing

You can now test your application. If set up correctly, the payment should work as expected.

##


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.appfarm.io/how-to/integrations/integrate-with-a-payment-provider.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
