0% found this document useful (0 votes)
18 views7 pages

Shopify Discounted Order Webhook Guide

The document outlines the implementation of a webhook for processing Shopify checkouts with discounts and creating corresponding orders in PlayByPoint. It details the setup of a new webhook, the creation of a dedicated API endpoint, and the necessary logic for handling checkout data, including discount calculations. Additionally, it describes an automated script for synchronizing product and inventory data from Shopify to PlayByPoint, emphasizing the importance of SKU as a unique identifier for product matching.

Uploaded by

Asad Rahman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

Shopify Discounted Order Webhook Guide

The document outlines the implementation of a webhook for processing Shopify checkouts with discounts and creating corresponding orders in PlayByPoint. It details the setup of a new webhook, the creation of a dedicated API endpoint, and the necessary logic for handling checkout data, including discount calculations. Additionally, it describes an automated script for synchronizing product and inventory data from Shopify to PlayByPoint, emphasizing the importance of SKU as a unique identifier for product matching.

Uploaded by

Asad Rahman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Developer Guide: Discounted Order Creation via Shopify

Checkout Webhook
Project: The Picklr Shopify-PlayByPoint Integration
Feature: Implement a new webhook endpoint to process Shopify checkouts with discounts and
create corresponding orders in PlayByPoint.

1. Introduction & Goal

The objective of this feature is to create a new, dedicated process that listens for Shopify
checkout events. When a customer applies a discount during checkout, this new process will
capture the data, including all line items and their respective discounts, and create a
corresponding order in the PlayByPoint system.

This guide outlines the strategy and step-by-step instructions for a developer to implement this
functionality. This process is entirely separate from the existing orders/create webhook.

2. High-Level Strategy

The implementation will follow these strategic steps:

1. Configure a New Webhook in Shopify: A new webhook must be set up in the Shopify
admin panel to send checkout data to our application.
2. Create a New, Dedicated API Endpoint: A new route will be created in our [Link]
application ([Link]) specifically to handle incoming checkout webhooks.
3. Replicate Existing Patterns: The new endpoint will reuse the core Puppeteer workflow
from the existing order handler: log in to PlayByPoint, find or create a user, and fetch the
product list.
4. Adapt to the Checkout Data Structure: The script must be written to parse the JSON
structure of a checkout payload, which is different from an order payload.
5. Inject Discount Logic: The crucial new logic will involve identifying discount
information within the checkout data and correctly applying it to the order creation
request sent to PlayByPoint.

3. Prerequisite: Shopify Configuration

Before any development begins, the following configuration must be completed in the Shopify
admin panel:

1. Navigate to Settings > Notifications.


2. Scroll down to the Webhooks section and click Create webhook.
3. Configure the webhook with the following settings:
o Event: Checkout creation. (A Checkout update event can also be added if needed
to capture changes, but start with creation).
o Format: JSON.
o URL: This must point to the new endpoint you will create. During local
development, this will be an ngrok URL (e.g.,
[Link]
o Webhook API version: Select the latest stable version.

4. Step-by-Step Implementation Plan

This section describes the required logic to be built within the application.

Step 1: Create the New Endpoint

In the [Link] file, define a new route handler for POST /api/Shopify/checkout.
This handler will serve as the entry point for the entire workflow. Its first responsibility is to
receive the request from Shopify and immediately send back a 200 OK success response to
prevent Shopify from resending the webhook. All processing will happen after this response is
sent.

Step 2: Implement the Core Puppeteer Workflow

The new endpoint should replicate the established Puppeteer automation pattern:

1. Launch a headless Puppeteer browser instance.


2. Navigate to the PlayByPoint login page.
3. Programmatically fill in the username and password credentials and submit the form to
log in.
4. Handle any navigation waits to ensure the login is successful.

Step 3: Process the Checkout Data within the Browser Context

The majority of the logic should be executed within a [Link]() block, passing the
checkout payload from the webhook into the browser's context. Inside this block, the following
actions must be performed in sequence:

1. User Lookup: Extract the customer's email from the incoming checkout data. Use this
email to make an API call to the PlayByPoint user search endpoint to find the
corresponding user ID. The logic should gracefully handle cases where the user does not
yet exist.
2. Product Catalog Fetch: Make an API call to the PlayByPoint products endpoint to
retrieve a list of all available products and their details (like product_id, sku, price, etc.).
3. Line Item Processing & Discount Calculation: This is the core of the new feature. The
script must iterate through the line_items array from the Shopify checkout data. For each
line item:
o Find the matching product from the fetched PlayByPoint product catalog using
the sku.
o Crucially, inspect the line item for a field containing discount information. In
checkout webhooks, this is typically an array named applied_discounts.
o Calculate the total discount for that specific line item by summing the amount
value from each object within the applied_discounts array.
o Prepare a new object that contains all the necessary information for the
PlayByPoint order: product_id, quantity, price, and the newly calculated discount.

Step 4: Construct and Execute the PlayByPoint Order Request

After processing all line items, the script must create a single, consolidated order in PlayByPoint.

1. Build the Payload: Construct a form-data payload for the PlayByPoint "Create Order"
API endpoint (POST /api/facilities/969/orders).
2. Populate the Payload: Loop through the prepared list of processed line items. For each
item, append its details to the form data payload. The parameter names must match what
the PlayByPoint API expects.
3. Include the Discount: For each item, ensure you append the calculated discount value
using the correct parameter name, which is expected to be
order[product_orders_attributes][INDEX][discount].
4. Execute the Request: Make the POST request to the PlayByPoint API with the fully
constructed payload.
5. Log the Outcome: Log whether the order creation was successful or failed, and include
any response message from the API for debugging.

Step 5: Ensure Proper Cleanup

Regardless of success or failure, the Puppeteer browser instance must be closed within a finally
block to prevent memory leaks and orphaned browser processes.

5. Data Mapping & Key Fields

The developer must pay close attention to the following fields in the Shopify checkout payload:

 Customer Email: [Link] or [Link]. This is used for the user


lookup.
 Line Items Array: checkout.line_items. This is the array to loop through.
 SKU: checkout.line_items[i].sku. Used to match with PlayByPoint products.
 Applied Discounts: checkout.line_items[i].applied_discounts. This is an array. The
script needs to sum the amount property of each object inside this array to get the total
discount for the line item.

This data must be mapped to the PlayByPoint "Create Order" API parameters.

6. Critical Testing Strategy

1. Phase 1: Payload Inspection (Most Important First Step)


o Before implementing the full Puppeteer logic, the developer must first configure
the webhook and add temporary logging to the new endpoint to capture and print
the entire raw JSON payload from a test checkout.
o Action: Create a real checkout in Shopify with a discount applied and examine
the logged data. This is to verify the exact names and locations of the key fields
(applied_discounts, email, etc.) before writing logic that depends on them.
2. Phase 2: End-to-End Testing
o Create various discount types in Shopify (e.g., percentage, fixed amount).
o Perform test checkouts using these discounts.
o Monitor the application logs for "Discount Found" messages and successful order
creation confirmations.
o Log in to the PlayByPoint admin panel to manually verify that the order was
created and that the discount was applied correctly to the order's total.

Developer Guide: Automated Shopify to PlayByPoint


Inventory Sync
1. Introduction & Goal

The primary objective of this feature is to create a scheduled, automated script that synchronizes
product and inventory data from Shopify to PlayByPoint. The script will be responsible for:

1. Identifying newly created products in Shopify and adding them to PlayByPoint.


2. Identifying changes in stock levels for existing products in Shopify and updating them in
PlayByPoint.
3. Ensuring that the product catalog (identified by SKUs) in PlayByPoint is an accurate
reflection of the Shopify store.

This guide details the technical strategy for building this automation using API calls and web
automation, replacing the manual Excel-based process.

2. Core Technical Strategy: API-First Automation

The manual process relies on exporting and comparing Excel files. Our automated script will
replace this by interacting directly with both platforms' data layers:
 Shopify Data Source: We will use the Shopify Admin API. This is the official, reliable
way to get product and inventory data. It allows us to fetch products and filter them by
creation or update date, which is far more efficient than manual exports.
 PlayByPoint Data Source & Actions: PlayByPoint does not have a public, documented
API for product creation or stock management. Therefore, our strategy will be to
automate the user interface (UI) using Puppeteer. We will programmatically perform
the same steps a human would, but first, we must discover the internal API calls the PBP
frontend makes to its backend.

3. The Golden Key: The SKU

The entire synchronization process hinges on one critical piece of data: the SKU (Stock Keeping
Unit).

 How it Works: The SKU will be the unique identifier used to match a product in Shopify
to its corresponding product in PlayByPoint. Shopify Product IDs and PlayByPoint
Product IDs are internal to their own systems and cannot be used to link the two.
 Prerequisite: For this system to work, it is absolutely essential that every product and
variant in Shopify that needs to be synced has a unique and consistent SKU. This is a
non-negotiable data requirement.

4. High-Level Automation Workflow

The script will follow this logical sequence:

1. Fetch Data from Shopify: Connect to the Shopify Admin API and request a list of all
products that have been recently updated or created.
2. Fetch Data from PlayByPoint: Launch a Puppeteer browser, log in to PlayByPoint, and
call their internal API to get a complete list of all existing products.
3. Reconcile Data in Memory: Compare the two lists of products in the script's memory
using the SKU as the key. This comparison will result in three lists:
o Products to Create: SKUs that exist in Shopify but not in PlayByPoint.
o Products to Update: SKUs that exist in both systems but have different
inventory quantities.
o Products to Ignore: SKUs that exist in both systems and have matching
inventory.
4. Execute Actions in PlayByPoint: Using the same Puppeteer session, iterate through the
"create" and "update" lists and perform the necessary actions by replicating the UI
workflows.

5. Technical Implementation Plan

This section explains how to build each part of the workflow.

Part 1: Data Fetching


 Shopify:
1. Authentication: The developer must generate Shopify Admin API credentials
(API key and secret) for a private app within the Shopify store. These credentials
will be used for authentication.
2. API Endpoint: Use the [Link] endpoint of the Shopify Admin API.
3. Filtering: To get only recent changes, use the updated_at_min query parameter.
The script will need to store a timestamp of its last successful run and use that
timestamp to ask Shopify for "all products updated since...".
 PlayByPoint:
1. Authentication: The script will use Puppeteer to log in to the PBP admin panel,
creating an authenticated session.
2. API Endpoint: The existing script already shows that PBP has an internal API
for fetching products (e.g., GET /api/facilities/969/products). The script will make
this same API call to get all PBP products.

Part 2: Data Reconciliation (The "Compare" Logic)

1. Create Data Maps: For efficient lookup, convert the list of Shopify products and the list
of PBP products into two separate JavaScript Map objects. The key for both maps will be
the SKU, and the value will be the full product object.
2. Iterate and Compare:
o Loop through the Shopify product map.
o For each Shopify product's SKU, check if it exists in the PBP product map.
 If it does not exist: Add this Shopify product to a productsToCreate array.
 If it does exist: Compare the inventory quantity from Shopify with the
quantity from PBP. If they do not match, add the Shopify product (with its
new quantity) and the corresponding PBP Product ID to a
productsToUpdate array.

Part 3: Executing Actions in PlayByPoint (The "Action" Logic)

This is the most complex part and requires a technique we'll call "Network Request Spying."
Since we don't have API documentation for PBP, we must discover the API calls ourselves.

 The Technique:
1. Open the PBP admin panel in a normal Chrome browser.
2. Open Chrome DevTools and go to the Network tab.
3. Manually perform the actions described in the manual flow (add a new product,
update stock via adjustment).
4. Watch the Network tab to see the API requests the website makes. Find the
relevant requests (e.g., a POST request to /api/products when you save a new
product).
5. Inspect these requests. Look at the URL, the method (POST, PUT, etc.), and
especially the payload (the form data) being sent. This tells you exactly what
data your script needs to send.
 "Add New Product" Automation Flow:
o For each product in the productsToCreate list, the script will perform two distinct
API calls discovered through network spying:
1. Create the Product: Make a POST request to PBP's internal "create
product" endpoint. The payload will contain the product's name, SKU,
price, etc., taken from the Shopify data. The response from this API call
should contain the newly created PBP product_id.
2. Set Initial Stock: Make a second POST request to PBP's internal "stock
received" endpoint. The payload for this call will require the product_id
from the previous step and the inventory quantity from Shopify.
 "Update Stock" Automation Flow:
o For each product in the productsToUpdate list, the script will perform one API
call:
1. Create a Stock Adjustment: Make a POST request to PBP's internal
"stock adjustment" endpoint. The payload will require the product_id of
the existing PBP product and the new inventory quantity from Shopify.

6. Triggering Mechanism

This script is not a webhook; it needs to be run on a schedule. The best way to achieve this is
with a cron job. A cron job can be set up on the server to execute the script automatically at
regular intervals (e.g., once every hour).

7. Final Testing and Verification Flow

Once the script is built, testing should follow this plan:

1. Add a new product in Shopify. Run the script and verify it appears correctly in PBP
with the right initial stock.
2. Update the stock of an existing product in Shopify. Run the script and verify the
quantity is adjusted correctly in PBP.
3. Reconciliation Check: After a full run, the developer should manually perform the final
verification step:
o Fetch all products via the Shopify API.
o Fetch all products via the PBP internal API.
o Write a simple, one-off local script to compare the two resulting datasets to ensure
SKUs and quantities match perfectly.

You might also like