--- title: Build an offsite payments extension with Shopify CLI description: Learn how to build a Shopify payments extension using Polaris and Prisma. source_url: html: https://shopify.dev/docs/apps/build/payments/offsite/use-the-cli?framework=remix md: https://shopify.dev/docs/apps/build/payments/offsite/use-the-cli.md?framework=remix --- # Build an offsite payments extension with Shopify CLI Tip Ensure you have the [latest version of Shopify CLI](https://shopify.dev/docs/api/shopify-cli#upgrade) installed to access all payment extension features. Offsite payments extension redirect customers to an app-hosted website to complete the payment process with the payment methods supported by the payments extension. When a store enables your offsite payments extension and a customer selects your payment method, the customer is redirected to a webpage specified by your payments extension where you can collect the customer's payment information, confirm the payment, and then redirect the customer back to Shopify to finalize the order. This tutorial provides step-by-step instructions on how to create and test an offsite payments app and payments extension. This tutorial is exclusively for testing and should be replaced with your own payment processing logic in a production extension. To make a production-ready extension, you need to make several changes to the template code to include your own payment processing capabilities. This tutorial highlights the areas you need to edit or extend with your own functionality. ## What you'll learn In this tutorial, you'll learn how to do the following tasks: * Set up your app * Create an offsite payments extension * Explore the payment, refund, void, reject and capture session flows, and how to implement them yourself ## Requirements [Create a Partner account](https://www.shopify.com/partners) [Create a development store](https://shopify.dev/docs/apps/tools/development-stores) The development store should be pre-populated with test data. [Become a Payments Partner](https://shopify.dev/docs/apps/build/payments/payments-extension-review#payments-partner-application-review) Apply and receive approval to become a Payments Partner. ## Project ![](https://shopify.dev/images/logos/Remix.svg)![](https://shopify.dev/images/logos/Remix-dark.svg) Remix [View on GitHub](https://github.com/Shopify/example-app--payments-app-template--remix/blob/main-js) ## Scaffold an app Scaffold a new payments app using [Shopify CLI](https://shopify.dev/docs/api/shopify-cli). ### Scaffold an app using Shopify CLI 1. Run the following command to start creating your app: ## Terminal ```bash npm init @shopify/app@latest ``` 2. When prompted, enter the name of your app. 3. When prompted for the approach, select the option to add your first extension ## Terminal ```bash Build a Remix app (recommended) > Build an extension-only app ``` ## Create a payments extension Your Shopify app becomes a payments app after you've created and configured your payments extension. 1. Run the following command to start generating your payment extension: ## Terminal ```bash pnpm shopify app generate extension ``` 2. When prompted, choose your organization & create this as a new app 3. When prompted for "Type of extension", select "Payments App Extension > Offsite" and name your extension ## Configure your payments extension When you [generate an app extension](https://shopify.dev/docs/api/shopify-cli/app/app-generate-extension), a TOML configuration file named `shopify.extension.toml` is automatically generated in your app's extension directory. You can find your extension configuration in `extensions//shopify.extensions.toml`. | Property name | Description | | - | - | | `payment_session_url` required | The URL that receives payment and order details from the checkout. | | `refund_session_url` required | The URL that refund session requests are sent to. | | `capture_session_url` optional | The URL that capture session requests are sent to. This is only used if your payments app supports merchant manual capture. | | `void_session_url` optional | The URL that void session requests are sent to. This is only used if your payments app supports merchant manual capture or void payments. | | `confirmation_callback_url` optional | The URL that confirm session requests are sent to. This URL is required if your payments app supports inventory confirmation. | | `supported_countries` required | The countries where your payments app is available. Refer to the [list of ISO 3166 (alpha-2) country codes](https://www.iso.org/iso-3166-country-codes.html) where your app is available for installation by merchants. | | `supports_3ds` required | 3-D Secure support is mandated in some instances. For example, you must enable the 3-D Secure field if you plan to support payments in countries which have mandated 3-D Secure. | | `supports_oversell_protection` optional | Enforces inventory confirmation. If set to `true`, then the payments app must use the [`paymentSessionConfirm`](https://shopify.dev/docs/api/payments-apps/latest/mutations/paymentSessionConfirm) mutation to confirm with Shopify whether to proceed with the payment request. Refer to [Explore confirm sessions](#explore-confirm-sessions) section to learn more. | | `supported_payment_methods` required | The payment methods (for example, Visa) that are available with your payments app. [Learn more](https://github.com/activemerchant/payment_icons/blob/master/db/payment_icons.yml). | | `supports_installments` required | Enables installments | | `supports_deferred_payments` required | Enables deferred payments | | `merchant_label` required | The name for your payment provider extension. This name is displayed to merchants in the Shopify admin when they search for payment methods to add to their store. Limited to 50 characters. | | `buyer_label` optional | The name of the method. Your checkout name can be the same as your merchant admin name or it can be customized for customers. This name is displayed with the payment methods that you support in the customer checkout. After a checkout name has been set, translations should be provided for localization. | | `test_mode_available` required | Enables merchants using your payments app to test their setup by simulating transactions. To test your app on a development store, your payment provider in the Shopify admin must be set to test mode. | | `api_version` required | The Payments Apps GraphQL API version used by the payment provider app to receive requests from Shopify. You must use the same API version for sending GraphQL requests. You must not use unstable in production. API versions are updated in accordance with Shopify's general [API versioning timelines](https://shopify.dev/docs/api/usage/versioning). | | `multiple_capture` optional, closed beta | Enables merchants using your payment provider app to partially capture an authorized payment multiple times up to the full authorization amount. This is used only if your payments app supports merchant manual capture. | ## Set up your payments app ### Disable embedding Shopify apps are embedded by default, but payments apps are an exception to this, because they don't need to render anything in Shopify admin. In `shopify.app.toml`, update the `embedded` and set it to false. ### Configure basic app settings In `shopify.app.toml`, update the `name` and `client_id` to match the information about the app that you manually created. You can find the `client_id` in the **Client credentials** section of your app's overview page in the [Partner Dashboard](https://partners.shopify.com/apps/). ### Push the configuration changes to your app and start your server In a terminal, run the following commands to push the configuration changes to your app: 1. Install the packages required to run the payments app: ## Terminal ```bash npm install ``` ```bash yarn install ``` ```bash pnpm install ``` 2. Deploy your app to update the config, which is defined in `shopify.app.toml`: ## Terminal ```bash shopify app deploy ``` ### Start your development server To run the app locally, start your development server: 1. ## Terminal ```bash shopify app dev ``` Info You might be prompted to log in to your Partner account. In your terminal, select your development store. You can use the generated URL to test your payments app by using it in your [payments app configuration](#configure-your-payments-app-extension). If you want a consistent tunnel URL, then you can use the `--tunnel-url` flag with your own tunnel when starting your server. 2. Press `p` to open the app in your browser. This brings you to your development store's admin, where you can install your payments app. ## Explore payment sessions In this step, you'll explore the flows that an app needs to implement to process a payment. In the app template, the endpoint that handles start payment session requests is predefined, and will automatically resolve or reject the payment by calling the Payments Apps API, based on the customer's name. Note that this behavior is exclusively for testing and should be replaced with your own payment processing logic in a production app. ### Start the payment session When a customer selects your payment provider, Shopify sends an HTTP `POST` request to the payment session URL for the app. The request contains information about the customer and the order. To learn more about the request body and header, refer to the [Offsite payment request reference](https://shopify.dev/apps/build/payments/request-reference#offsite-payment). When the `POST` request is received, the payments app returns an HTTP `2xx` response with a `redirect_url` in the body. The `redirect_url` should be less than `8192 bytes` in length. This response and parameter are required for the payment session creation to be successful. If the request fails, then it's retried several times. If the request still fails, then the customer needs to retry their payment through Shopify checkout. If there's an error on the payments app's side, then return an appropriate error status code instead. *** You configure the payment session URL for your app as part of the [app extension configuration](#configure-your-payments-extension). ## /app/routes/app.payment\_session.jsx ```jsx import { createPaymentSession } from "~/payments.repository"; /** * Saves and starts a payment session. * Redirects back to shop if payment session was created. */ export const action = async ({ request }) => { const requestBody = await request.json(); const shopDomain = request.headers.get("shopify-shop-domain"); const paymentSession = await createPaymentSession(createParams(requestBody, shopDomain)); if (!paymentSession) throw new Response("A PaymentSession couldn't be created.", { status: 500 }); return { "redirect_url": buildRedirectUrl(request, paymentSession.id) }; } const createParams = ({id, gid, group, amount, currency, test, kind, customer, payment_method, proposed_at, cancel_url}, shopDomain) => ( { id, gid, group, amount, currency, test, kind, customer, paymentMethod: payment_method, proposedAt: proposed_at, cancelUrl: cancel_url, shop: shopDomain } ) const buildRedirectUrl = (request, id) => { return `${request.url.slice(0, request.url.lastIndexOf("/"))}/payment_simulator/${id}` } ``` ### Resolve a payment The payments app uses the `paymentSessionResolve` mutation after the customer has successfully gone through the payment process to complete the payment. The `id` argument corresponds to the global identifier (`gid`) of the payment. *** In the referenced code, `this.resolveMutation` corresponds to the `paymentSessionResolve` mutation. [![](https://shopify.dev/images/logos/GraphQL.svg)![](https://shopify.dev/images/logos/GraphQL-dark.svg)](https://shopify.dev/docs/api/payments-apps/latest/mutations/paymentSessionResolve) [payment​Session​Resolve](https://shopify.dev/docs/api/payments-apps/latest/mutations/paymentSessionResolve) ## /app/payments-apps.graphql.js ```javascript import schema from "./payments-apps.schema"; import { updatePaymentSessionStatus, updateRefundSessionStatus, updateCaptureSessionStatus, updateVoidSessionStatus, RESOLVE, REJECT, PENDING } from "./payments.repository"; /** * Client to interface with the Payments Apps GraphQL API. * * paymentsAppConfigure: Configure the payments app with the provided variables. * paymentSessionResolve: Resolves the given payment session. * paymentSessionReject: Rejects the given payment session. * refundSessionResolve: Resolves the given refund session. * refundSessionReject: Rejects the given refund session. */ export default class PaymentsAppsClient { constructor(shop, accessToken, type) { this.shop = shop; this.type = type || PAYMENT; // default this.accessToken = accessToken; this.resolveMutation = ""; this.rejectMutation = ""; this.pendingMutation = ""; this.dependencyInjector(type); } /** * Generic session resolution function * @param {*} session the session to resolve upon * @returns the response body from the Shopify Payments Apps API ``` ### Reject a payment The payments app should reject a payment if the customer can't complete a payment with the provider. The rejected payment tells Shopify that the checkout process will be halted. For example, if you don't want to process a high-risk payment, then you can reject the payment using the `paymentSessionReject` mutation. Rejecting a payment is final. You can't call other actions on a payment after it has been rejected. The payments app should retry a failed user attempt and complete the payment before calling `paymentSessionReject`. For example, if any of the following conditions are met, then you don't need to reject the payment: * The user doesn't interact with your payments app * The user cancels the payment * The user needs to retry the payment because of specific errors, such as the user entering the wrong CVV *** In the referenced code, `this.rejectMutation` corresponds to the `paymentSessionReject` mutation. [![](https://shopify.dev/images/logos/GraphQL.svg)![](https://shopify.dev/images/logos/GraphQL-dark.svg)](https://shopify.dev/docs/api/payments-apps/latest/mutations/paymentSessionReject) [payment​Session​Reject](https://shopify.dev/docs/api/payments-apps/latest/mutations/paymentSessionReject) ## /app/payments-apps.graphql.js ```javascript import schema from "./payments-apps.schema"; import { updatePaymentSessionStatus, updateRefundSessionStatus, updateCaptureSessionStatus, updateVoidSessionStatus, RESOLVE, REJECT, PENDING } from "./payments.repository"; /** * Client to interface with the Payments Apps GraphQL API. * * paymentsAppConfigure: Configure the payments app with the provided variables. * paymentSessionResolve: Resolves the given payment session. * paymentSessionReject: Rejects the given payment session. * refundSessionResolve: Resolves the given refund session. * refundSessionReject: Rejects the given refund session. */ export default class PaymentsAppsClient { constructor(shop, accessToken, type) { this.shop = shop; this.type = type || PAYMENT; // default this.accessToken = accessToken; this.resolveMutation = ""; this.rejectMutation = ""; this.pendingMutation = ""; this.dependencyInjector(type); } /** * Generic session resolution function * @param {*} session the session to resolve upon * @returns the response body from the Shopify Payments Apps API ``` ### Cancel the payment If a customer wants to cancel a payment on your provider page, then they are redirected to the merchant's website or store by using the `cancel_url`. The `cancel_url` is sent to your payments app in the payment request request-body that was sent from Shopify. Don't use the `paymentSessionReject` mutation to cancel the payment, otherwise the customer will be unable to pay again with your provider. ## /app/routes/app.payment\_simulator.$paymentId.jsx ```jsx import { Button, Card, FooterHelp, FormLayout, Layout, Page, Text, Select, BlockStack, Link, Banner, } from "@shopify/polaris"; import { useEffect, useState } from "react"; import { Form, useLoaderData, useActionData, } from "@remix-run/react"; import { json, redirect } from "@remix-run/node"; import { sessionStorage } from "../shopify.server"; import { getPaymentSession, RESOLVE, REJECT, PENDING } from "~/payments.repository"; import PaymentsAppsClient, { PAYMENT } from "~/payments-apps.graphql"; /** * Loads the payment session being simulated. */ export const loader = async ({ params: { paymentId } }) => { const paymentSession = await getPaymentSession(paymentId); return json({ paymentSession }); } /** * Completes a payment session based on the simulator's form. */ export const action = async ({ request, params: { paymentId } }) => { const formData = await request.formData(); const resolution = formData.get("resolution"); const paymentSession = await getPaymentSession(paymentId); const session = (await sessionStorage.findSessionsByShop(paymentSession.shop))[0]; const client = new PaymentsAppsClient(session.shop, session.accessToken, PAYMENT); let response; switch(resolution) { case RESOLVE: response = await client.resolveSession(paymentSession); break; case REJECT: response = await client.rejectSession(paymentSession); break; case PENDING: response = await client.pendSession(paymentSession); break; } const userErrors = response.userErrors; if (userErrors?.length > 0) return json({ errors: userErrors }); return redirect(response.paymentSession.nextAction.context.redirectUrl); } export default function PaymentSimulator() { const action = useActionData(); const { paymentSession } = useLoaderData(); const [resolution, setResolution] = useState('resolve'); const [errors, setErrors] = useState([]); useEffect(() => { if (action?.errors.length > 0) setErrors(action.errors); }, [action]); const errorBanner = () => ( errors.length > 0 && ( { setErrors([]) }} > { errors.map(({message}, idx) => ( {message} )) } ) ) const resolutionOptions = [ {value: RESOLVE, label: 'Resolve'}, {value: REJECT, label: 'Reject'}, {value: PENDING, label: 'Pending'} ]; const cancelUrl = paymentSession.cancelUrl; return ( {errorBanner()}
setResolution(change)} value={resolution} />
Learn more about payment sessions
); } ``` ### Process next action Upon receiving the response from either the `paymentSessionResolve`, `paymentSessionReject`, or `paymentSessionPending` mutations, the next action that the payments app performs is specified under `nextAction`. The `nextAction will either be `nil`or contain two fields. In the case where it is`nil\`, no next action is expected of the payments app. Otherwise, the fields are as follows: * `action`: A `PaymentSessionNextActionAction` enum that specifies the type of the action the app must perform. * `context`: A union type requiring inline fragments to access data on the underlying type. Takes a type of `PaymentSessionActionsRedirect`. [![](https://shopify.dev/images/logos/GraphQL.svg)![](https://shopify.dev/images/logos/GraphQL-dark.svg)](https://shopify.dev/docs/api/payments-apps/latest/objects/PaymentSessionNextAction) [next​Action](https://shopify.dev/docs/api/payments-apps/latest/objects/PaymentSessionNextAction) [![](https://shopify.dev/images/logos/GraphQL.svg)![](https://shopify.dev/images/logos/GraphQL-dark.svg)](https://shopify.dev/docs/api/payments-apps/latest/enums/PaymentSessionNextActionAction) [Payment​Session​Next​Action​Action](https://shopify.dev/docs/api/payments-apps/latest/enums/PaymentSessionNextActionAction) [![](https://shopify.dev/images/logos/GraphQL.svg)![](https://shopify.dev/images/logos/GraphQL-dark.svg)](https://shopify.dev/docs/api/payments-apps/latest/objects/PaymentSessionActionsRedirect) [Payment​Session​Actions​Redirect](https://shopify.dev/docs/api/payments-apps/latest/objects/PaymentSessionActionsRedirect) ## /app/routes/app.payment\_simulator.$paymentId.jsx ```jsx import { Button, Card, FooterHelp, FormLayout, Layout, Page, Text, Select, BlockStack, Link, Banner, } from "@shopify/polaris"; import { useEffect, useState } from "react"; import { Form, useLoaderData, useActionData, } from "@remix-run/react"; import { json, redirect } from "@remix-run/node"; import { sessionStorage } from "../shopify.server"; import { getPaymentSession, RESOLVE, REJECT, PENDING } from "~/payments.repository"; import PaymentsAppsClient, { PAYMENT } from "~/payments-apps.graphql"; /** * Loads the payment session being simulated. */ export const loader = async ({ params: { paymentId } }) => { const paymentSession = await getPaymentSession(paymentId); return json({ paymentSession }); } /** * Completes a payment session based on the simulator's form. */ export const action = async ({ request, params: { paymentId } }) => { const formData = await request.formData(); const resolution = formData.get("resolution"); const paymentSession = await getPaymentSession(paymentId); const session = (await sessionStorage.findSessionsByShop(paymentSession.shop))[0]; const client = new PaymentsAppsClient(session.shop, session.accessToken, PAYMENT); let response; switch(resolution) { case RESOLVE: response = await client.resolveSession(paymentSession); break; case REJECT: response = await client.rejectSession(paymentSession); break; case PENDING: response = await client.pendSession(paymentSession); break; } const userErrors = response.userErrors; if (userErrors?.length > 0) return json({ errors: userErrors }); return redirect(response.paymentSession.nextAction.context.redirectUrl); } export default function PaymentSimulator() { const action = useActionData(); const { paymentSession } = useLoaderData(); const [resolution, setResolution] = useState('resolve'); const [errors, setErrors] = useState([]); useEffect(() => { if (action?.errors.length > 0) setErrors(action.errors); }, [action]); const errorBanner = () => ( errors.length > 0 && ( { setErrors([]) }} > { errors.map(({message}, idx) => ( {message} )) } ) ) const resolutionOptions = [ {value: RESOLVE, label: 'Resolve'}, {value: REJECT, label: 'Reject'}, {value: PENDING, label: 'Pending'} ]; const cancelUrl = paymentSession.cancelUrl; return ( {errorBanner()}