> Beta: > Post-purchase checkout extensions are in beta and can be used without restrictions in a [development store](/docs/api/development-stores). To use post-purchase extensions on a live store, you need to [request access](/docs/apps/build/checkout/product-offers/build-a-post-purchase-offer#step-5-request-access). In this tutorial, you'll learn how 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](/assets/api/post-purchase/post-purchase-subscription-overview.png) ## What you'll learn 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 ## Requirements - You've completed [Build a post-purchase product offer checkout extension](/docs/apps/build/checkout/product-offers/build-a-post-purchase-offer). ## Limitations You can't create a post-purchase subscription that does the following: * 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 ## Step 1: Add required data To offer a customer a subscription, a product needs to have an associated selling plan group. [Selling plans](/docs/apps/build/purchase-options/subscriptions/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](#step-2-return-subscription-information-from-the-app-server). To complete this tutorial, the product on the store you will have in the upsell offer needs to be associated with a selling plan. ### Update app scopes 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. ```toml scopes = "write_products,write_purchase_options" ``` ### Create 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. ```shell curl -X POST \ -H 'X-Shopify-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/\"], productVariantIds: [\"gid://shopify/ProductVariant/\"] } ) { sellingPlanGroup { id sellingPlans(first: 1) { edges { node { id } } } } userErrors { field message } } }' \ 'https://.myshopify.com/admin/api/2023-07/graphql.json' ``` ## Step 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](/docs/apps/build/checkout/product-offers/build-a-post-purchase-offer) to return an offer with the selling plan information that you created in the previous step. ```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", }, }, ], }, ]; ``` ## Step 3: Update your extension code to offer subscriptions Replace the content of your extension script with the following code. ```jsx?filename: 'src/index.jsx', title: 'React' 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, }), }).then((response) => response.json()); await storage.update(postPurchaseOffer); // For local development, always show the post-purchase page return { render: true }; } ); render("Checkout::PostPurchase::Render", () => ); export function App() { const { storage, inputData, calculateChangeset, applyChangeset, done } = useExtensionInput(); const [loading, setLoading] = useState(true); const [calculatedPurchase, setCalculatedPurchase] = useState(); // Track the buyer's approval to the subscriptions policies. const [buyerConsent, setBuyerConsent] = useState(false); const [buyerConsentError, setBuyerConsentError] = useState(); const [selectedPurchaseOption, setSelectedPurchaseOption] = useState(0); const { offers } = storage.initialData; const purchaseOptions = offers; const purchaseOption = purchaseOptions[selectedPurchaseOption]; // 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]); // Extract values from the calculated purchase. const shipping = calculatedPurchase?.addedShippingLines[0]?.priceSet?.presentmentMoney ?.amount; const taxes = calculatedPurchase?.addedTaxLines[0]?.priceSet?.presentmentMoney?.amount; const total = calculatedPurchase?.totalOutstandingSet.presentmentMoney.amount; const discountedPrice = calculatedPurchase?.updatedLineItems[0].totalPriceSet.presentmentMoney .amount; const originalPrice = calculatedPurchase?.updatedLineItems[0].priceSet.presentmentMoney.amount; async function acceptOffer() { setLoading(true); // Make a request to your app server to sign the changeset with your app's API secret key. const token = await fetch(`${APP_URL}/api/sign-changeset`, { method: "POST", headers: { Authorization: `Bearer ${inputData.token}`, "Content-Type": "application/json", }, body: JSON.stringify({ referenceId: inputData.initialPurchase.referenceId, changes: purchaseOptions[selectedPurchaseOption].id, }), }) .then((response) => response.json()) .then((response) => response.token) .catch((e) => console.log(e)); // Send the value of the buyer consent with the changeset to Shopify to add the subscription const result = await applyChangeset(token, { buyerConsentToSubscriptions: buyerConsent, }); // Ensure that there is no buyer consent error if ( result.errors.find((error) => error.code === "buyer_consent_required") ) { // Show an error if the buyer didn't accept the subscriptions policy setBuyerConsentError("You need to accept the subscriptions policy."); setLoading(false); } else { // Redirect to the Thank you page. done(); } // Redirect to the thank-you page. done(); } function declineOffer() { setLoading(true); // Redirect to the thank-you page. done(); } return ( It's not too late to add this to your order Add the {purchaseOption.productTitle} to your order and{" "} save {purchaseOption.changes[0].discount.title} {purchaseOption.productTitle} {purchaseOptions.length > 1 && ( setSelectedPurchaseOption(parseInt(value, 10)) } value={selectedPurchaseOption.toString()} options={purchaseOptions.map((option, index) => ({ label: option.title, value: index.toString(), }))} /> ``` ```js?filename: 'src/index.js', title: 'Vanilla' 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](/assets/api/post-purchase/selling_plan_options.png) #### Updating 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: ```jsx?filename: 'src/index.jsx', title: 'React' // 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]); ``` ```js?filename: 'src/index.js', title: 'Vanilla' // 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](/assets/api/post-purchase/price_breakdown.png) #### Showing 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. ```jsx?filename: 'src/index.jsx', title: 'React' function RecurringSummary({label, amount, interval}) { return ( {label} {formatCurrency(amount)} {getBillingInterval(interval)} Doesn't include shipping, tax, duties, or any applicable discounts. ); } const originalPrice = calculatedPurchase?.updatedLineItems[0].priceSet.presentmentMoney.amount; // ... {purchaseOption.sellingPlanInterval && ( )} ``` ```js?filename: 'src/index.js', title: 'Vanilla' 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](/assets/api/post-purchase/recurring_subtotal.png) #### Collecting buyer's consent 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: ```jsx?filename: 'src/index.jsx', title: 'React' // Track the buyer's approval to the subscriptions policies. const [buyerConsent, setBuyerConsent] = useState(false); const [buyerConsentError, setBuyerConsentError] = useState(); // ... {purchaseOption.changes[0].type === "add_subscription" && ( )} ``` ```js?filename: 'src/index.js', title: 'Vanilla' // 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](/assets/api/post-purchase/buyer-consent-checkbox.png) ### Applying 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. ```jsx?filename: 'src/index.jsx', title: 'React' await applyChangeset(token, {buyerConsentToSubscriptions: buyerConsent}); ``` ```js?filename: 'src/index.js', title: 'Vanilla' await applyChangeset(token, {buyerConsentToSubscriptions: buyerConsent}); ``` ## Step 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. ## Next steps - Get familiar with the [UX guidelines](/docs/apps/build/checkout/product-offers/ux-for-post-purchase-subscriptions) for creating subscriptions with post-purchase checkout extensions.