Skip to main content

Create a post-purchase subscription

Beta

Post-purchase checkout extensions are in beta and can be used without restrictions in a development store. To use post-purchase extensions on a live store, you need to request access.

In this tutorial, you'll learn how to use Shopify Extensions to create a post-purchase offer that allows a buyer to add a subscription to their order.

Overview of a post-purchase subscription added to a single item

In this tutorial, you’ll learn how to do the following tasks:

  • Update your app with the required scopes to manage subscriptions
  • Add UI elements to allow buyers to select one time or subscription products
  • Update the app server to return subscription data


You can't create a post-purchase subscription that does any of the following things:

  • Modifies a subscription on an order with an existing subscription
  • Adds a subscription to an order with an existing subscription
  • Converts a one-time purchase into a subscription order

Anchor to Step 1: Add required dataStep 1: Add required data

To offer a customer a subscription, a product needs to have an associated selling plan group. Selling plans represent how products can be sold and purchased. When you create a selling plan, you can determine the policies under which a product can be sold. For example, you can create a selling plan where a customer can purchase a subscription on a monthly billing cycle, and where you offer a 15% discount for weekly deliveries of the product.

Note

If your app already has the capability to manage selling plans, or if you're integrating with an app that already has this capability, then you can skip to step 2. To complete this tutorial, the product on the store you will have in the upsell offer needs to be associated with a selling plan.

To create a selling plan and associate it to a product, you need to add the write_purchase_options scope to the app.

Update the app scopes in the shopify.app.toml file to include the write_purchase_options scope. This scope allows you to create selling plan groups.

After you update scopes, when you navigate to the app home in the Shopify admin, you should be prompted to reauthorize the app to allow editing of purchase options. If you're not prompted to reauthorize, restart your server, and then navigate to the app home in the Shopify admin.

shopify.app.toml

scopes = "write_products,write_purchase_options"

Anchor to Create a selling plan groupCreate a selling plan group

Use the GraphQL Admin API to create a selling plan group, and associate a product with the selling plan group. In the following cURL command, add the myshopify domain of your development store, the access token for the app, and the product and variant IDs of the product that you're offering in the upsell.

Note

You can run npm run prisma studio to view your data in your browser. The access token is stored in the Session table in the accessToken column.

Terminal

curl -X POST \
-H 'X-Shopify-Access-Token: <YOUR ACCESS TOKEN>' \
-H 'Content-Type: application/graphql' \
-d 'mutation {
sellingPlanGroupCreate(
input: {
name: "Subscribe and save"
merchantCode: "subscribe-and-save"
options: ["Delivery every"]
position: 1
sellingPlansToCreate: [
{
name: "Delivered every week"
options: "1 Week(s)"
position: 1
category: SUBSCRIPTION
billingPolicy: {
recurring: {
interval: WEEK,
intervalCount: 1
anchors: { type: WEEKDAY, day: 1 }
}
}
deliveryPolicy: {
recurring: {
interval: WEEK,
intervalCount: 1
anchors: { type: WEEKDAY, day: 1 }
preAnchorBehavior: ASAP
cutoff: 0
intent: FULFILLMENT_BEGIN
}
}
pricingPolicies: [
{
fixed: {
adjustmentType: PERCENTAGE
adjustmentValue: { percentage: 15.0 }
}
}
]
}
{
name: "Delivered every two weeks"
options: "2 Week(s)"
position: 2
category: SUBSCRIPTION
billingPolicy: {
recurring: {
interval: WEEK,
intervalCount: 2
anchors: { type: WEEKDAY, day: 1 }
}
}
deliveryPolicy: {
recurring: {
interval: WEEK,
intervalCount: 2
anchors: { type: WEEKDAY, day: 1 }
preAnchorBehavior: ASAP
cutoff: 0
intent: FULFILLMENT_BEGIN
}
}
pricingPolicies: [
{
fixed: {
adjustmentType: PERCENTAGE
adjustmentValue: { percentage: 10.0 }
}
}
]
}
{
name: "Delivered every month"
options: "1 Month"
position: 3
category: SUBSCRIPTION
billingPolicy: {
recurring: {
interval: MONTH,
intervalCount: 1
anchors: { type: MONTHDAY, day: 15 }
}
}
deliveryPolicy: {
recurring: {
interval: MONTH,
intervalCount: 1
anchors: { type: MONTHDAY, day: 15 }
preAnchorBehavior: ASAP
cutoff: 0
intent: FULFILLMENT_BEGIN
}
}
pricingPolicies: [
{
fixed: {
adjustmentType: PERCENTAGE
adjustmentValue: { percentage: 5.0 }
}
}
]
}
]
}
resources: { productIds: [\"gid://shopify/Product/<YOUR PRODUCT ID>\"], productVariantIds: [\"gid://shopify/ProductVariant/<YOUR VARIANT ID>\"] }
) {
sellingPlanGroup {
id
sellingPlans(first: 1) {
edges {
node {
id
}
}
}
}
userErrors {
field
message
}
}
}' \
'https://<YOUR SHOP DOMAIN>.myshopify.com/admin/api/2023-07/graphql.json'

Anchor to Step 2: Return subscription information from the app serverStep 2: Return subscription information from the app server

Update the OFFERS array in the app/offer.server.js file that you created in the previous tutorial to return an offer with the selling plan information that you created in the previous step.

app/offer.server.js

const OFFERS = [
{
id: 1,
title: "One time offer",
productTitle: "The S-Series Snowboard",
productImageURL: "https://cdn.shopify.com/s/files/1/", // Replace with product image's URL.
productDescription: ["This PREMIUM snowboard is so SUPER DUPER awesome!"],
originalPrice: "699.95",
discountedPrice: "699.95",
changes: [
{
type: "add_variant",
variantID: 123456789, // Replace with the variant ID.
quantity: 1,
discount: {
value: 15,
valueType: "percentage",
title: "15% off",
},
},
],
},
{
id: 2,
title: "Weekly subscription offer",
productTitle: "The S-Series Snowboard",
productImageURL: "https://cdn.shopify.com/s/files/1/0", // Replace with the product image's URL.
productDescription: ["This PREMIUM snowboard is so SUPER DUPER awesome!"],
originalPrice: "699.95",
discountedPrice: "699.95",
sellingPlanName: "Subscribe and save",
sellingPlanInterval: "WEEK",
changes: [
{
type: "add_subscription",
variantID: 123456789, // Replace with the variant ID.
quantity: 1,
sellingPlanId: "987654321", // Replace with the selling plan ID.
initialShippingPrice: 10,
recurringShippingPrice: 10,
discount: {
value: 15,
valueType: "percentage",
title: "15% off",
},
shippingOption: {
title: "Subscription shipping line",
presentmentTitle: "Subscription shipping line",
},
},
],
},
];

Anchor to Step 3: Update your extension code to offer subscriptionsStep 3: Update your extension code to offer subscriptions

Replace the content of your extension script with the following code.

src/index

src/index.jsx

import { useEffect, useState } from "react";
import {
extend,
render,
useExtensionInput,
BlockStack,
Button,
BuyerConsent,
CalloutBanner,
Heading,
Image,
Text,
TextContainer,
Separator,
Select,
Tiles,
TextBlock,
Layout,
} from "@shopify/post-purchase-ui-extensions-react";

// For local development, replace APP_URL with your local tunnel URL.
const APP_URL = "https://abcd-1234.trycloudflare.com";

// Preload data from your app server to ensure the extension loads quickly.
extend(
"Checkout::PostPurchase::ShouldRender",
async ({ inputData, storage }) => {
const postPurchaseOffer = await fetch(`${APP_URL}/api/offer`, {
method: "POST",
headers: {
Authorization: `Bearer ${inputData.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
referenceId: inputData.initialPurchase.referenceId,
}),
import {
extend,
BlockStack,
Button,
CalloutBanner,
Heading,
Image,
Text,
TextContainer,
Separator,
Tiles,
TextBlock,
Layout,
BuyerConsent,
Select,
} from "@shopify/post-purchase-ui-extensions";

// For local development, replace APP_URL with your local tunnel URL.
const APP_URL = "https://abcd-1234.trycloudflare.com";

// Preload data from your app server to ensure the extension loads quickly.
extend(
"Checkout::PostPurchase::ShouldRender",
async ({ inputData, storage }) => {
const postPurchaseOffer = await fetch(`${APP_URL}/api/offer`, {
method: "POST",
headers: {
Authorization: `Bearer ${inputData.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
referenceId: inputData.initialPurchase.referenceId,
}),
}).then((response) => response.json());

await storage.update(postPurchaseOffer);

Anchor to How the example extension code worksHow the example extension code works

The following sections explain how different parts of the example extension code in Step 2 works.

Anchor to Showing the selling plan optionsShowing the selling plan options

To show the selling plan options to buyers, you need to use the Select component. When a buyer selects a new selling plan, we update the value of the selected purchase option.

src/index

src/index.jsx

<Select
label="Purchase options"
onChange={(value) =>
setSelectedPurchaseOption(parseInt(value, 10))
}
value={selectedPurchaseOption.toString()}
options={purchaseOptions.map((option, index) => ({
label: option.title,
value: index.toString(),
}))}
/>
const purchaseOptionSelect = root.createComponent(Select, {
label: 'Purchase options',
value: selectedPurchaseOption.toString(),
options: purchaseOptions.map((option, index) => ({
label: option.title,
value: index.toString(),
})),
onChange: (value) => {
const previousPurchaseOption = purchaseOptions[selectedPurchaseOption];
selectedPurchaseOption = parseInt(value, 10);
updatePriceBreakdownUI(previousPurchaseOption);
},
});

if (purchaseOptions.length > 1) {
wrapperComponent.insertChildBefore(
purchaseOptionSelect,
priceBreakdownComponent
);
}

After you've updated the code, the selling plan option renders as follows:

Selling plan option picker

Anchor to Updating the price breakdownUpdating the price breakdown

To show the price breakdown matching the currently selected offer, you need to call calculateChangeset when the buyer selects a selling plan:

src/index

src/index.jsx

// Define the changes that you want to make to the purchase, including the discount to the product.
useEffect(() => {
async function calculatePurchase() {
// Call Shopify to calculate the new price of the purchase, if the above changes are applied.
const result = await calculateChangeset({
changes: purchaseOptions[selectedPurchaseOption].changes,
});

setCalculatedPurchase(result.calculatedPurchase);
setLoading(false);
}

calculatePurchase();

// Add the selectedPurchaseOption to the dependency of the useEffect.
// This will ensure that when the buyer selects a new purchase option, the price breakdown is recalculated.
}, [calculateChangeset, purchaseOptions, selectedPurchaseOption]);
// Request Shopify to calculate shipping costs and taxes for the upsell.
const result = await calculateChangeset({
changes: purchaseOptions[selectedPurchaseOption].changes,
});

After you've updated the code, the price breakdown renders as follows:

Price breakdown including subtotal, shipping and taxes

Anchor to Showing a recurring subtotalShowing a recurring subtotal

For subscription offers, you need to display the recurring subtotal of the order.

Note

The totalPriceSet for subscription items indicates the price of that item after discounts at each billing cycle, and not the total for the subscription duration.

src/index

src/index.jsx

function RecurringSummary({label, amount, interval}) {
return (
<BlockStack spacing="xtight">
<Tiles>
<TextBlock size="small">{label}</TextBlock>
<TextContainer alignment="trailing">
<TextBlock size="small" subdued>
{formatCurrency(amount)} {getBillingInterval(interval)}
</TextBlock>
</TextContainer>
</Tiles>
<TextBlock size="small" subdued>
Doesn&apos;t include shipping, tax, duties, or any applicable discounts.
</TextBlock>
</BlockStack>
);
}

const originalPrice = calculatedPurchase?.updatedLineItems[0].priceSet.presentmentMoney.amount;

// ...

{purchaseOption.sellingPlanInterval && (
<RecurringSummary
label="Recurring subtotal"
amount={originalPrice}
interval={purchaseOption.sellingPlanInterval}
/>
)}
const recurringSummary = root.createComponent(
BlockStack,
{spacing: 'xtight'},
[
root.createComponent(Tiles, {}, [
root.createComponent(
TextBlock,
{size: 'small'},
'Recurring subtotal'
),
root.createComponent(
TextContainer,
{alignment: 'trailing'},
root.createComponent(
TextBlock,
{subdued: true, size: 'small'},
recurringSummaryText
)
),
]),
root.createComponent(
TextBlock,
{size: 'small', subdued: true},
"Doesn't include shipping, tax, duties, or any applicable discounts."
),
]
);

if (
currentPurchaseOption?.changes[0].sellingPlanId &&
previousPurchaseOption?.changes[0].sellingPlanId
) {
// ...
priceBreakdownComponent.appendChild(recurringSummary);
}

After you've updated the code, the recurring subtotal renders as follows:

Recurring subtotal price and explanation

To add a subscription item to an order, the buyer’s payment method must be vaulted for future billing cycles of the subscription. Before you can vault the buyer's payment method, the buyer has to explicitly give consent to the subscription policies. Use the BuyerConsent component in App Bridge to collect consent:

src/index

src/index.jsx

// Track the buyer's approval to the subscriptions policies.
const [buyerConsent, setBuyerConsent] = useState(false);
const [buyerConsentError, setBuyerConsentError] = useState();

// ...

{purchaseOption.changes[0].type === "add_subscription" && (
<BuyerConsent
policy="subscriptions"
checked={buyerConsent}
onChange={setBuyerConsent}
error={buyerConsentError}
/>
)}
// Track the buyer's approval to the subscriptions policies.
let buyerConsent = false;

const buyerConsentComponent = root.createComponent(BuyerConsent, {
policy: 'subscriptions',
checked: buyerConsent,
onChange: () => {
buyerConsent = !buyerConsent;
},
});

if (
currentPurchaseOption?.changes[0].sellingPlanId &&
previousPurchaseOption?.changes[0].sellingPlanId
) {
// ...

wrapperComponent.insertChildBefore(
buyerConsentComponent,
buttonsComponent
);
}

This component creates a checkbox and a link to the subscription policies.

The checkbox where buyers can give their consent to adding a subscription

Anchor to Applying the subscription changeApplying the subscription change

For the add_subscription change to be accepted, the value of the buyer consent checkbox needs to be provided as a new parameter to the applyChangeset method. Without this parameter, the changeset won’t be applied and an error is returned.

src/index

src/index.jsx

await applyChangeset(token, {buyerConsentToSubscriptions: buyerConsent});
await applyChangeset(token, {buyerConsentToSubscriptions: buyerConsent});

Anchor to Step 4: Test your extensionStep 4: Test your extension

Complete a test order on your store and go through the checkout steps. When the post-purchase page appears, add a subscription product to your order. Navigate to the orders section of the Shopify Admin. You should see that on the latest order you have a one time as well as a subscription product.


  • Get familiar with the UX guidelines for creating subscriptions with post-purchase checkout extensions.

Was this page helpful?