Add Buy Now buttons
Your marketplace includes product description pages with sufficient details to drive purchases. You want an option on the page that directs buyers to checkout.
In this tutorial, you'll use the Storefront API's
cartCreate mutation to create a cart with a single variant. You'll embed a Buy Now button on product pages, which open a new tab with the URL to the online store for checkout.
What you'll learn
After you finish this tutorial, you'll know how to do the following:
cartCreatemutation to create a new cart for the product purchase
Add Buy Now buttons that redirect buyers to merchant checkout
You've completed the Add product description pages tutorial.
You're familiar with the Storefront API cart.
Step 1: Add a
You'll use the Storefront API's
cartCreate mutation to create a cart with a single variant, and redirect the buyer to the cart's checkout URL. Since you're immediately redirecting to checkout, you'll only retrieve the
checkoutURL field for the cart.
pages/products/[shopid]/[producthandle].js, add a
cartCreate mutation that accepts an
input parameter to hold cart information.
Step 2: Add a Buy Now button handler
In this step you'll create a callback function to run the
cartCreate mutation and open a tab in the browser window with the checkout URL.
Because you're embedding the Buy Now button into the marketplace's product description pages, you'll embed this function in your component directly, and use the variant and client from the component’s state.
pages/products/[shopID]/[productHandle].js, create a
buyNowfunction that accepts
variantIdand the Apollo Client (
Step 3: Add the Buy Now button
You'll surface Buy Now buttons in your product description pages, where buyers have ready access to product descriptions and variants. You'll also disable the Buy Now button if the selected variants aren't available.
pages/products/[shopid]/[producthandle].js, add a Buy Now button below the variant selectors that calls the
buyNowfunction that you created.
Your product description page should now look something like the following, and clicking the Buy Now button should open the checkout in a new tab.
- Learn how to surface a shop's policies in the context of a marketplace.