Connect any store
How to wire the Oyster skin scan into a store we don't ship an app for: a custom build, a headless storefront, or a platform you'd rather integrate by hand. You get the same result as our Shopify app and WooCommerce plugin: shoppers buy what the scan recommends through your own checkout, and each paid order is credited to the scan that drove it.
Works on any platform
Every step uses things all stores have: SKUs, a cart, data on order lines, and an event when an order is paid. The Shopify and WooCommerce code below shows one way to do it, not the only way.
Already on Shopify or WordPress?
The Shopify app and the WooCommerce plugin do all of this without code. Build it yourself only if you can't install them.
Your checkout stays in charge
Oyster never takes payment for these orders, fulfils them, refunds them or contacts the shopper. It records them for your reporting.
How it fits together
Steps 2 and 3 give shoppers a working "buy" button, and step 1 keeps what the scan recommends in stock and correctly priced. Steps 4 and 5 are what put sales in your Oyster dashboard, credited to the scan behind them. Skip them and the integration still sells, but you can't see what the scan earned.
Before you start
| You need | Where to get it | Where it goes |
|---|---|---|
| Widget public key | Your Oyster dashboard, Widget Manager | Your page code. Safe to publish. |
| Your store's domain on the allowed list | Widget Manager, allowed domains | The widget won't start on a domain that isn't listed. |
| An API key with Manage catalogue and Manage orders | Your Oyster dashboard, API Manager | Your server only. Never in page code. |
| Your vendor id | See below | Every order you report |
Give the API key Manage catalogue and Manage orders and nothing else. If you also want to look up your vendor id with it, add Read account settings and call:
curl https://api.oysterskin.com/api/v1/vendors/profile \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Accept: application/json"
# Your vendor id is vendor.id in the response.
Your vendor id never changes, so look it up once and store it with the key. You can remove Read account settings afterwards. Every Oyster webhook also carries it as vendor_id.
1. Sync your catalogue
Oyster recommends products from your Oyster catalogue, and your store sells products from its own. The two are joined on SKU. Every product you want the scan to sell needs the same SKU in both places, and Oyster needs your current price and stock so it recommends what you can actually sell.
For a handful of products you can add them by hand in your Oyster dashboard. Otherwise, have your server keep Oyster in step with three calls. They work the same on any platform:
| Call | Use it when |
|---|---|
POST /products/bulk-upsert | A product is created or edited, and for a full sync. Creates unknown SKUs and updates known ones. |
PATCH /products/stock | Stock changes, for example after a sale or a delivery. Stock only, so it's cheap to send often. |
POST /products/archive | A product is deleted, unpublished or discontinued. |
POST /products/resolve | You need to know what an Oyster product id is in your store. See store ids. |
All three are on api.oysterskin.com under /api/v1/integrations/storefront. Each takes up to 250 items per call and is safe to retry with the same body.
Create and update products
POST https://api.oysterskin.com/api/v1/integrations/storefront/products/bulk-upsert
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
{
"products": [
{
"sku": "CLN-150",
"name": "Gentle Cleanser 150ml",
"price": "8000.00",
"currency": "NGN",
"stock_level": 12,
"description": "A gentle daily cleanser for dry and sensitive skin.",
"brand": "Acme Skin",
"category": "Cleanser",
"image_url": "https://cdn.example.com/cln-150.jpg",
"ingredients": ["Aqua", "Glycerin", "Niacinamide"]
}
]
}
- sku, name and price are required. Everything else is optional, and a field you leave out keeps its current value, so you can send only what changed.
- Ingredients matter most. They are what Oyster matches against a shopper's skin. Send the full list, in order. Without it, Oyster reads them from the description where it can. Ingredients and skin types are taken when a product is created or has none yet; after that, correct them in your Oyster dashboard, and a sync won't overwrite your edits.
- A new product sent without stock_level starts at 0. Out-of-stock products rank below in-stock ones. If your store doesn't track quantities, send any positive number while a product is in stock and 0 when it isn't.
- Upserting a SKU you archived brings it back. A product you set to draft in your Oyster dashboard stays a draft.
- Other optional fields: usage_instructions, weight, weight_unit, size_volume, size_volume_unit, tags, and skin_types (names such as Oily or Dry).
Each product succeeds or fails on its own. The response is 200 when everything was saved, and 207 when something wasn't, with the reasons:
{
"data": {
"created": 1, "updated": 0, "claimed": 0, "listed": 0, "off_range": 0, "failed": 1,
"failed_items": [
{ "sku": "SRM-030", "external_product_id": null, "external_variant_id": null,
"reason": "invalid_image_url", "error": "The image_url field must be a valid URL." }
],
"results": [
{ "sku": "CLN-150", "external_product_id": null, "external_variant_id": null, "op": "created", "product_id": 9012 }
]
}
}
| Reason | Meaning |
|---|---|
invalid_image_url | The image URL isn't a valid URL. Fix it and resend that product. |
managed_by_connected_store | Your Oyster Shopify app or WooCommerce plugin already keeps this product in sync, so this call leaves it alone. |
sku_in_use | You sent store ids with a SKU that another item in the same store already uses. |
not_saved | Something else went wrong with this product. The error says what. |
off_range counts products in a category Oyster doesn't recommend from, such as fragrance or haircare. They're skipped, and removed from Oyster if they were there before.
Update stock
PATCH https://api.oysterskin.com/api/v1/integrations/storefront/products/stock
{ "stock_updates": [ { "sku": "CLN-150", "stock_level": 7 }, { "sku": "SRM-030", "stock_level": 0 } ] }
→ { "data": { "updated": 1, "not_found": [{ "sku": "SRM-030" }], "managed_by_connected_store": [] } }
Negative stock (an oversold item) is saved as 0. A SKU in not_found isn't in Oyster yet: upsert it first.
Archive products
POST https://api.oysterskin.com/api/v1/integrations/storefront/products/archive
{ "skus": ["CLN-150"] }
→ { "data": { "archived": 1, "not_found": [], "managed_by_connected_store": [] } }
Archived products are no longer recommended, but they're never deleted: past orders and scan results still show them.
Store ids, for Shopify and WooCommerce stores
If you're integrating a Shopify or WooCommerce store yourself, you can also send each product's own ids, the way the Oyster apps do. Add "platform": "shopify" or "woocommerce" to the request, and on each row external_product_id, plus external_variant_id for an item sold as a variant. A row can then be identified by its store ids, its SKU, or both.
{
"platform": "shopify",
"products": [
{ "external_product_id": "8741203411", "external_variant_id": "46120339201", "handle": "gentle-cleanser",
"sku": "CLN-150", "name": "Gentle Cleanser 150ml", "price": "8000.00", "stock_level": 12 },
{ "external_product_id": "8741203411", "external_variant_id": "46120339202",
"name": "Gentle Cleanser 300ml", "price": "14000.00", "stock_level": 4 }
]
}
- Each variant is its own product in Oyster, so archiving one variant leaves its siblings on sale.
- Stock and archive calls can name it by store id: external_variant_id or external_product_id in a stock update, and external_variant_ids or external_product_ids in an archive call, with the same platform. That's how most stock and delete webhooks report changes.
- A product with no SKU can still sync. Oyster gives it a SKU of its own. The widget's checkout event carries that SKU and Oyster's product_id, so turn the id back into your item with /products/resolve, from your server. When the order is paid, name that line by the same store ids (line fields).
- A product you already added to Oyster by SKU is linked rather than duplicated (claimed), and keeps the name, description and ingredients you set up in Oyster.
- If you also run the Oyster app or plugin for another store, your primary store keeps a shared product's details, and this store records only its own price and stock against it (listed).
POST https://api.oysterskin.com/api/v1/integrations/storefront/products/resolve
{ "platform": "shopify", "product_ids": [9012] }
→ { "data": { "9012": { "sku": "CLN-150", "external_product_id": "8741203411",
"external_variant_id": "46120339201", "handle": "gentle-cleanser" } } }
Resolve works with a key that has Read catalogue or Manage catalogue. It uses your API key, so call it from your server, never from page code. Products that aren't yours are left out.
When to sync
- Once, at the start: upsert your whole catalogue, 250 products per call.
- As things change: upsert on product create and edit, send stock when it moves, archive on delete or unpublish.
- Every night: upsert the whole catalogue again. It catches anything a missed event or a failed call left behind, and resending unchanged products is harmless.
SKU rules
- One SKU means one product, in your store and in Oyster. A SKU can appear only once per call.
- Oyster matches SKUs exactly, including case. Keep them identical everywhere you send them.
- Give every product a SKU if you can: it's the simplest way to match products everywhere. A Shopify or WooCommerce product without one can still be synced, sold and credited by its store ids.
2. Show the scan
Load the widget and create it with your public key and a callback. The callback is how the widget tells your page the shopper wants to buy. The full options are in Embedding the widget and the Options reference.
<script src="https://widget-lib.oysterskin.com/v1/oysterskin-vendor-widget-web.umd.js"></script>
<script>
window.addEventListener('load', function () {
OysterskinWidget.createScanWidget({
publicKey: 'YOUR_PUBLIC_KEY',
mode: 'float',
callback: onOysterMessage,
// If the shopper is logged in, pass them in so the widget doesn't ask again:
// user: { id: 'cust_8421', name: 'Ada Obi', email: '[email protected]' },
});
});
</script>
Load it on every page if you use the floating launcher. For a dedicated scan page, use mode: 'inline' with a container. While you build, use the sandbox script URL from Versioning.
3. Hand off to your cart
When the shopper taps the buy button, your callback receives a checkout event listing what they chose. Each item carries the SKU and quantity, and also the two ids that tie it to the scan:
{
"event": "checkout",
"data": {
"total_quantity": 3,
"currency": "NGN",
"checkout_items": [
{
"sku": "CLN-150",
"product_name": "Gentle Cleanser",
"quantity": 1,
"skin_analysis_batch_id": "a1B2c3D4e5",
"product_usage_routine_id": 88123
},
{
"sku": "SRM-030",
"product_name": "Niacinamide Serum",
"quantity": 2,
"skin_analysis_batch_id": "a1B2c3D4e5",
"product_usage_routine_id": 88124
}
],
"user": { "email": "[email protected]" }
}
}
Your handler does three things:
- Find each SKU in your store. Skip any you can't find or that are sold out, so one missing product doesn't block the rest.
- Add the rest to the shopper's cart, with the two ids on each line (step 4).
- Send the shopper to your checkout. If nothing could be added, send them to the cart instead of an empty checkout.
var checkoutInProgress = false;
function onOysterMessage(message) {
if (!message || message.event !== 'checkout' || checkoutInProgress) return;
var items = ((message.data && message.data.checkout_items) || []).filter(function (item) {
return item && item.sku;
});
if (!items.length) return;
checkoutInProgress = true;
// addToMyCart is yours: it adds each SKU with its scan ids and resolves to how many lines it added.
addToMyCart(items.map(function (item) {
return {
sku: item.sku,
quantity: item.quantity || 1,
oysterBatchId: item.skin_analysis_batch_id,
oysterRoutineId: item.product_usage_routine_id
};
}))
.then(function (added) { window.location.href = added > 0 ? '/checkout' : '/cart'; })
.catch(function () { window.location.href = '/cart'; });
}
The checkout event can also carry a welcome_offer or wheel_reward. See Spin the Wheel rewards and Payments, rewards, webhooks.
4. Carry the scan to the order
Oyster credits a purchase line by line. A line counts towards a scan only if it arrives with that scan's ids, so they have to survive from the cart to the paid order. Store them on the line, not on the order: one cart can hold products from two scans, or products the shopper added themselves.
| Store on the line | From the checkout item | What it is |
|---|---|---|
| Scan id | skin_analysis_batch_id |
The scan that recommended this product. Letters, digits, - and _, up to 128 characters. |
| Routine id | product_usage_routine_id |
The recommendation itself. A whole number. |
Every platform has somewhere to put data on a cart line that is copied onto the order line:
- Shopify: line item properties. Names starting with _ are hidden from the shopper.
- WooCommerce: cart item data, copied to order item meta when the order is created.
- Your own build: two nullable columns on your cart line and order line tables.
If the shopper changes the quantity of a tagged line, keep the ids. If they remove a recommended product and add it back later, it's still a sale the scan earned. Where your platform allows it, keep the ids for each SKU from the checkout event (in the session, or a first-party cookie) and apply them again whenever that SKU is added to the cart.
5. Report paid orders
When an order is paid, your server sends it to Oyster. Hook into whatever your platform fires at that moment: a paid-order webhook, an order status change, or your own payment callback.
- If no line carries a scan id or routine id, stop. There is nothing to credit.
- Build the request below from the order. Work the total out from the lines you send.
- Send it with your API key. A network error or a 5xx is worth retrying. Most other errors are not (see responses).
POST https://api.oysterskin.com/api/v1/integrations/storefront/orders
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
Accept: application/json
{
"vendor_id": 142,
"order_id": "7879",
"order_number": "#1042",
"currency": "NGN",
"placed_at": "2026-11-09T12:00:00+01:00",
"total": "27500.00",
"shipping_amount": "2500.00",
"tax_amount": "0.00",
"discount_amount": "1000.00",
"line_items": [
{
"line_item_id": "9871",
"sku": "CLN-150",
"quantity": 1,
"price": "8000.00",
"discount_amount": "1000.00",
"skin_analysis_batch_id": "a1B2c3D4e5",
"product_usage_routine_id": 88123
},
{
"line_item_id": "9872",
"sku": "SRM-030",
"quantity": 2,
"price": "9000.00",
"discount_amount": "0.00",
"skin_analysis_batch_id": "a1B2c3D4e5",
"product_usage_routine_id": 88124
}
]
}
The order then appears in your Oyster dashboard with only its tagged lines credited to the scan. Untagged lines are recorded as part of the order but credited to nothing.
6. Honour Spin the Wheel rewards
If you run Spin the Wheel, a shopper who wins gets a code. By default that code is for Oyster's own checkout. Register your checkout and rewards are issued for yours instead: you create each code when it's won, the shopper uses it with you, and you tell Oyster it was used so it shows in your Spin the Wheel report.
- Register the reward types your checkout can honour. Refresh it every day.
- Create the code when your server receives the signed wheel.reward_won webhook.
- Report the use when an order that used the code is paid.
You need an API key with Honour Spin the Wheel rewards at your checkout (wheel:rewards), and a webhook endpoint subscribed to wheel.reward_won. One key can carry this and Manage orders together.
Register your checkout
POST https://api.oysterskin.com/api/v1/integrations/storefront/wheel/capabilities
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
Accept: application/json
{
"protocol_version": 1,
"store_host": "shop.example.com",
"currency": "NGN",
"reward_types": ["percentage_discount", "fixed_discount", "free_delivery"]
}
List only the types your checkout can apply: percentage_discount, fixed_discount, free_delivery and free_item. Only those can be put on your wheel. currency must be your checkout's, and match your Oyster account's. If your store runs on Shopify or WooCommerce and you sync products with store ids, add "platform" and reward terms name products by those ids.
If your checkout has limits, say so in an optional constraints object and the dashboard won't let a reward ask for more:
| Constraint | Send it when |
|---|---|
| fixed_discount_product_restrictions: false | A fixed discount can only apply to the whole cart. |
| excluded_products_require_allowed_products: true | Your checkout can exclude products only from an explicit list of eligible ones. |
| free_item_product_restrictions: false | A free-item code can't carry extra product restrictions. |
| free_item_combines_with_discounts: false | A free item can't be used with other discounts. |
| free_item_requires_expiry: true | A free item must expire. |
| free_item_max_expiry_days | A free item must expire within this many days. |
| free_item_usage_limit | A free item can be used at most this many times. |
| free_item_min_order_amount: 0 | A free item can't require a minimum spend. |
Your checkout honours rewards while all of these hold:
- you registered in the last 48 hours,
- the key you registered with still exists,
- a webhook endpoint is switched on and subscribed to wheel.reward_won.
When one stops holding, new rewards go back to Oyster's checkout within a minute, and come back to yours when you register again. To stop on purpose, send DELETE to the same URL. Codes you already issued keep working with you either way, so keep reporting their use.
Create the code
Every win arrives at your server as a signed wheel.reward_won webhook. When its redemption_authority is store, the reward is yours to honour: create a discount in your checkout with that exact code and these terms. Check the signature first (see Verifying the signature), and key on reward_id, because a retry must not create a second code.
"data": {
"reward_id": "9b1f0c2e-5d4a-4c1e-9a77-2f3c8d6e1a40",
"code": "WHEEL-7QK2M9XWD4H8RZ3PLT6NVB5CJ1GYEA0S",
"email": "[email protected]",
"type": "percentage_discount",
"value": 10,
"currency": "NGN",
"min_order_amount": 5000,
"usage_limit": 1,
"expires_at": "2026-11-26T09:14:22+00:00",
"restrictions": {
"allowed_product_ids": ["7310"],
"excluded_product_ids": [],
"allowed_skus": ["SRM-030"],
"excluded_skus": [],
"combines_with_discounts": false
},
"product_id": null,
"variant_id": null,
"sku": null,
"terms_hash": "5e8f...",
"redemption_authority": "store"
}
| Field | What to do with it |
|---|---|
| type, value | percentage_discount: value percent off. fixed_discount: value off in currency. free_delivery: waive the delivery charge. free_item: the product in product_id / sku, free. |
| Restrict the code to this shopper if your checkout can. | |
| usage_limit, expires_at | How many orders can use it, and until when. expires_at is null for no expiry. |
| min_order_amount | The cart subtotal the code needs, or null for none. |
| restrictions | The products it applies to (empty means all), the ones it doesn't, and whether it can be used with other discounts. Products are named by Oyster product id and by SKU, or by your store ids if you registered a platform. |
The shopper sees their code in the widget and enters it at your checkout. If your checkout can take a code from a link, you can also apply it for them from the wheelRewardWon event. Never create a discount from that event, though: it comes from the page, so anyone can fake it.
Report the use
When an order that used the code is paid, report it from the same place you report paid orders. Report it whether or not the order came from a scan.
POST https://api.oysterskin.com/api/v1/integrations/storefront/wheel/redemptions
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
Accept: application/json
{
"reward_id": "9b1f0c2e-5d4a-4c1e-9a77-2f3c8d6e1a40",
"order_id": "7879",
"discount_amount": 1500,
"currency": "NGN",
"completed_at": "2026-11-10T14:22:05Z"
}
discount_amount is what the code took off, in the same units as your order totals. Sending the same reward_id and order_id again is safe and returns the first receipt, so retry with the same order_id, never a new one. A 422 means the reward has no uses left or the currency differs: your checkout should already have refused the code. A 404 means the reward wasn't issued for your checkout.
Order API reference
Order fields
| Field | Required | Notes |
|---|---|---|
vendor_id | Yes | Your vendor id. Must match the account the API key belongs to. |
order_id | Yes | Your store's own id for the order, as a string, up to 128 characters. It identifies the order, so a resend with the same id is treated as the same order. |
order_number | No | The number shoppers and your staff see, if it differs from the id. |
currency | Yes | ISO code: NGN, GHS, ZAR, KES, RWF, UGX, TZS, XOF, XAF, EGP, USD, EUR, GBP, CAD or AUD. |
placed_at | Yes | When the order was placed or paid, ISO 8601 with a time zone. |
total | Yes | What the lines you send add up to. See Money. |
shipping_amount | No | Defaults to 0. |
tax_amount | No | Tax charged on top of prices. Defaults to 0. Leave it at 0 if your prices already include tax. |
discount_amount | No | The sum of the line discounts. Defaults to 0. |
customer_email | No | Optional. Not used to credit the order, so you can leave it out. |
line_items | Yes | 1 to 250 lines. |
platform | With store ids | shopify or woocommerce, when any line names its product by store ids. |
Line fields
| Field | Required | Notes |
|---|---|---|
line_item_id | Yes | Your id for the line, unique within the order. |
sku | Unless store ids | Must match exactly one product in your Oyster catalogue. |
external_product_id | No | The store's own product id, as you synced it with the same platform. Use it instead of sku for a product without one. |
external_variant_id | No | The store's own variant id, for an item sold as a variant. |
quantity | Yes | A whole number, 1 or more. |
price | Yes | Unit price before discounts. |
discount_amount | No | The discount on the whole line, not per unit. Defaults to 0. |
skin_analysis_batch_id | No | From step 4. Tags the line to a scan. |
product_usage_routine_id | No | From step 4. Send it along with the scan id when you have it. If you send both, they must agree. |
Money
Send amounts as strings or numbers with at most two decimal places, in major units ("8000.00", not kobo or cents). Oyster checks the order adds up, to the cent:
discount_amount = sum of line discount_amount
total = sum of (price × quantity) − discount_amount + shipping_amount + tax_amount
Calculate total from the values you send. Don't copy your platform's grand total. A store's grand total often includes things Oyster doesn't model, like fees, tips, gift cards and duties, and won't match. Order-level discounts (a coupon on the whole cart) must be spread across the lines they apply to. Most platforms already record that split per line.
If you report only the lines from the scan, send shipping_amount and tax_amount as 0 so the order isn't credited with shipping and tax that belong to products outside it.
Responses
| Status | Body | Meaning and what to do |
|---|---|---|
| 201 | "recorded": true | Recorded and credited. Done. |
| 200 | "duplicate": true | You already sent this order with the same content. Done. |
| 200 | "recorded": false, "reason": "no_recommendation_items" | No line was tagged to a scan. Nothing to record. Done. |
| 401, 403 | The key is wrong, revoked, or doesn't have Manage orders. Fix the key, then retry. | |
| 409 | external_order_payload_conflict | This order_id was already recorded with different content. Don't retry. |
| 422 | reason, line_ids | The order was refused. line_ids names the line at fault. See below. Fix the cause, but retrying the same order won't help. |
| 429, 5xx | Temporary. Retry later with the same body. |
| 422 reason | Cause |
|---|---|
vendor_mismatch | vendor_id isn't the account the key belongs to. |
catalog_product_unresolved | A line's SKU isn't in your Oyster catalogue, or more than one product has it. |
recommendation_mismatch | A tagged line's product wasn't recommended by that scan, or its scan id and routine id don't agree. |
recommendation_unresolved | The scan id isn't a scan taken with your account. |
conflicting_recommendation_customers | The tagged lines come from scans by different shoppers. One order can be credited to one shopper only. |
purchase_amount_mismatch | The amounts don't add up. See Money. |
invalid_line_amount | A line's discount is more than its value, or an amount is out of range. |
Example: Shopify
On Shopify the Oyster app does all of this for you. Use this only if you can't install the app, or want full control. It works on every Shopify plan.
The storefront snippet
Shopify's storefront has no "find variant by SKU" endpoint, so the snippet searches for the SKU with /search/suggest.json, reads each candidate with /products/{handle}.js, and keeps the variant whose SKU matches. It adds the variants with /cart/add.js, with the scan ids as hidden line item properties (_oyster_batch_id, _oyster_routine_id), then goes to checkout.
In Shopify admin open Online Store → Themes → … → Edit code, open layout/theme.liquid, and paste this just before </body>:
<!-- Oyster widget -->
<script src="https://widget-lib.oysterskin.com/v1/oysterskin-vendor-widget-web.umd.js"></script>
<script>
(function () {
var PUBLIC_KEY = 'YOUR_PUBLIC_KEY';
// Keeps cart and checkout URLs inside the shopper's market and language (e.g. /fr/).
var ROOT = (window.Shopify && Shopify.routes && Shopify.routes.root) || '/';
var BATCH_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
var checkoutInProgress = false;
var productCache = {};
function getJson(url) {
return fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
.then(function (res) {
if (!res.ok) throw new Error(url + ' returned ' + res.status);
return res.json();
});
}
function postJson(url, body) {
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(body)
}).then(function (res) {
return res.json().catch(function () { return {}; }).then(function (json) {
if (!res.ok) throw new Error(json.description || json.message || url + ' returned ' + res.status);
return json;
});
});
}
function normaliseSku(sku) {
return String(sku || '').trim().toLowerCase();
}
function productByHandle(handle) {
if (!productCache[handle]) {
productCache[handle] = getJson(ROOT + 'products/' + encodeURIComponent(handle) + '.js')
.catch(function () { return null; });
}
return productCache[handle];
}
function findVariantBySku(sku) {
var wanted = normaliseSku(sku);
var params = new URLSearchParams({
q: String(sku).trim(),
'resources[type]': 'product',
'resources[limit]': '10',
'resources[options][fields]': 'variants.sku',
'resources[options][unavailable_products]': 'last'
});
return getJson(ROOT + 'search/suggest.json?' + params.toString())
.then(function (json) {
var results = (json.resources && json.resources.results && json.resources.results.products) || [];
return Promise.all(results.map(function (result) { return productByHandle(result.handle); }));
})
.then(function (products) {
var matches = [];
products.forEach(function (product) {
((product && product.variants) || []).forEach(function (variant) {
if (normaliseSku(variant.sku) === wanted) matches.push(variant);
});
});
return matches.filter(function (v) { return v.available; })[0] || matches[0] || null;
});
}
function scanProperties(item) {
var properties = {};
if (BATCH_ID_PATTERN.test(String(item.skin_analysis_batch_id || ''))) {
properties._oyster_batch_id = item.skin_analysis_batch_id;
}
if (item.product_usage_routine_id) {
properties._oyster_routine_id = String(item.product_usage_routine_id);
}
return properties;
}
function lineForItem(item) {
return findVariantBySku(item.sku)
.then(function (variant) {
if (!variant) {
console.warn('[oyster] no published Shopify variant has SKU', item.sku);
return null;
}
if (!variant.available) {
console.warn('[oyster] skipping sold-out SKU', item.sku);
return null;
}
return { id: variant.id, quantity: item.quantity || 1, properties: scanProperties(item) };
})
.catch(function (err) {
console.warn('[oyster] lookup failed for SKU', item.sku, err);
return null;
});
}
// /cart/add.js rejects the whole batch if any one line fails (e.g. not enough stock),
// so fall back to adding lines one by one and keep whatever succeeds.
function addLinesToCart(lines) {
return postJson(ROOT + 'cart/add.js', { items: lines })
.then(function () { return lines.length; })
.catch(function () {
return lines.reduce(function (chain, line) {
return chain.then(function (added) {
return postJson(ROOT + 'cart/add.js', { items: [line] })
.then(function () { return added + 1; })
.catch(function (err) {
console.warn('[oyster] could not add variant', line.id, err.message);
return added;
});
});
}, Promise.resolve(0));
});
}
function handleCheckout(data) {
if (checkoutInProgress) return;
var items = ((data && data.checkout_items) || []).filter(function (item) { return item && item.sku; });
if (!items.length) {
console.warn('[oyster] checkout event had no items with a SKU');
return;
}
checkoutInProgress = true;
Promise.all(items.map(lineForItem))
.then(function (lines) {
lines = lines.filter(Boolean);
return lines.length ? addLinesToCart(lines) : 0;
})
.then(function (added) {
window.location.href = ROOT + (added > 0 ? 'checkout' : 'cart');
})
.catch(function (err) {
console.error('[oyster] checkout handoff failed', err);
window.location.href = ROOT + 'cart';
});
}
window.addEventListener('load', function () {
OysterskinWidget.createScanWidget({
mode: 'float',
publicKey: PUBLIC_KEY,
callback: function (message) {
if (message && message.event === 'checkout') handleCheckout(message.data);
}{% if customer %},
user: {
id: '{{ customer.id }}',
name: {{ customer.name | json }},
email: {{ customer.email | json }}
}{% endif %}
});
});
})();
</script>
<!-- End Oyster widget -->
Products must be published to the Online Store sales channel, or the storefront can't see them. Shopify keeps the same variant with different properties as separate cart lines, so a product the shopper already had in their cart stays untagged and the scan's copy is tagged.
Keeping the catalogue in sync
The same relay can sync your catalogue. Add webhooks for Product creation and Product update, and send "platform": "shopify" with one row per variant for /products/bulk-upsert: the product id, the variant id, its SKU, the title, the variant's price and its stock (see store ids). Archive the variant ids of a product whose status is no longer active. Product deletion sends the product id, which you can pass straight to /products/archive as external_product_ids. Stock that changes through sales is caught by a nightly full sync through the Shopify Admin API.
The order relay
Shopify's webhooks can't carry your Oyster API key, so a small relay sits between them. It checks the webhook really came from your store, turns the order into Oyster's format, and sends it on. This one runs on Cloudflare Workers' free plan. Any serverless platform works the same way.
- In Cloudflare go to Workers & Pages → Create → Create Worker, name it (e.g. oyster-order-relay) and deploy the starter.
- Edit code, replace everything with the code below, and Deploy.
- Under Settings → Variables and Secrets add the secrets OYSTER_API_KEY and SHOPIFY_WEBHOOK_SECRET (a placeholder for now), and the variable OYSTER_VENDOR_ID.
- In Shopify admin go to Settings → Notifications → Webhooks, Create webhook: event Order payment, format JSON, your worker's URL, the latest API version.
- Copy the value Shopify shows under "Your webhooks will be signed with…" into SHOPIFY_WEBHOOK_SECRET.
const OYSTER_ORDERS_URL = 'https://api.oysterskin.com/api/v1/integrations/storefront/orders';
// true if some of your products are not in your Oyster catalogue: report only the lines from the scan.
const ONLY_SCAN_LINES = false;
// Shopify retries a webhook that doesn't get a 2xx, so only ask for a retry
// when trying again could succeed (a key you then fix, rate limiting, an outage).
const RETRYABLE_STATUSES = [401, 403, 429];
export default {
async fetch(request, env) {
if (request.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
const rawBody = await request.arrayBuffer();
const signature = request.headers.get('X-Shopify-Hmac-Sha256');
if (!(await isFromShopify(rawBody, signature, env.SHOPIFY_WEBHOOK_SECRET))) {
return new Response('Invalid signature', { status: 401 });
}
const order = JSON.parse(new TextDecoder().decode(rawBody));
const payload = toOysterOrder(order, Number(env.OYSTER_VENDOR_ID));
if (!payload) {
return new Response('No line on this order came from a scan', { status: 200 });
}
let response;
try {
response = await fetch(OYSTER_ORDERS_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${env.OYSTER_API_KEY}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(payload),
});
} catch (err) {
console.error('Oyster unreachable', err);
return new Response('Oyster unreachable', { status: 502 });
}
const detail = await response.text();
if (response.ok) {
return new Response(detail, { status: 200 });
}
console.error(`Oyster answered ${response.status} for order ${order.id}`, detail);
const retry = response.status >= 500 || RETRYABLE_STATUSES.includes(response.status);
return new Response(detail, { status: retry ? 502 : 200 });
},
};
const cents = (amount) => Math.round(Number(amount || 0) * 100);
const money = (amountInCents) => (amountInCents / 100).toFixed(2);
const sum = (values) => values.reduce((total, value) => total + value, 0);
function lineProperty(line, name) {
const property = (line.properties || []).find((p) => p.name === name);
return property ? String(property.value).trim() || null : null;
}
function toOysterOrder(order, vendorId) {
const lines = (order.line_items || [])
.filter((line) => line.sku && line.quantity > 0)
.map((line) => {
const routineId = lineProperty(line, '_oyster_routine_id');
return {
line_item_id: String(line.id),
sku: line.sku.trim(),
quantity: line.quantity,
priceCents: cents(line.price),
discountCents: sum((line.discount_allocations || []).map((a) => cents(a.amount))),
skin_analysis_batch_id: lineProperty(line, '_oyster_batch_id'),
product_usage_routine_id: routineId ? Number(routineId) : null,
};
});
const fromScan = (line) => line.skin_analysis_batch_id || line.product_usage_routine_id;
if (!lines.some(fromScan)) return null;
const sent = ONLY_SCAN_LINES ? lines.filter(fromScan) : lines;
const shippingCents = ONLY_SCAN_LINES
? 0
: sum((order.shipping_lines || []).map((s) => cents(s.discounted_price ?? s.price)));
// With tax-inclusive prices the tax is already inside each line's price.
const taxCents = ONLY_SCAN_LINES || order.taxes_included ? 0 : cents(order.total_tax);
const subtotalCents = sum(sent.map((l) => l.priceCents * l.quantity));
const discountCents = sum(sent.map((l) => l.discountCents));
return {
vendor_id: vendorId,
order_id: String(order.id),
order_number: order.name ?? null,
currency: order.currency,
placed_at: order.processed_at || order.created_at,
total: money(subtotalCents - discountCents + shippingCents + taxCents),
shipping_amount: money(shippingCents),
tax_amount: money(taxCents),
discount_amount: money(discountCents),
line_items: sent.map(({ priceCents, discountCents, ...line }) => ({
...line,
price: money(priceCents),
discount_amount: money(discountCents),
})),
};
}
async function isFromShopify(rawBody, signature, secret) {
if (!signature || !secret) return false;
let signatureBytes;
try {
signatureBytes = Uint8Array.from(atob(signature), (c) => c.charCodeAt(0));
} catch {
return false;
}
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify'],
);
return crypto.subtle.verify('HMAC', key, signatureBytes, rawBody);
}
Click Send test notification next to the webhook: the worker's logs should show a 200 with "No line on this order came from a scan". A 401 there means the signing secret is wrong.
Spin the Wheel rewards
For step 6, a second worker creates each won code as a Shopify discount and reports it when an order that used it is paid. The discount is limited to the shopper who won it. It handles percentage, fixed and free-delivery rewards. A free item needs its stock held until the shopper uses it, so leave it out here unless you build that.
- Create a custom app for your store with the Admin API scopes read_discounts, write_discounts, read_customers and write_customers, and copy its Admin API access token.
- Create a second Cloudflare worker (e.g. oyster-wheel) with the code below.
- Add the secrets OYSTER_API_KEY (a key with Honour Spin the Wheel rewards at your checkout), OYSTER_WEBHOOK_SECRET, SHOPIFY_ADMIN_TOKEN and SHOPIFY_WEBHOOK_SECRET, and the variables SHOP_DOMAIN (your .myshopify.com address) and SHOP_CURRENCY.
- Under Settings → Triggers add a cron trigger for once a day, e.g. 0 3 * * *. That keeps the registration fresh.
- In your Oyster dashboard, Developers → Webhooks, add https://<your worker>/oyster for wheel.reward_won, and copy its signing secret into OYSTER_WEBHOOK_SECRET.
- In Shopify, add a second Order payment webhook pointing at https://<your worker>/shopify/order-paid.
- Register once now, without waiting for the cron: run the curl in Register your checkout with the same body the worker sends.
const OYSTER_WHEEL_URL = 'https://api.oysterskin.com/api/v1/integrations/storefront/wheel';
const SHOPIFY_API_VERSION = '2025-10';
const REWARD_TYPES = ['percentage_discount', 'fixed_discount', 'free_delivery'];
export default {
async scheduled(event, env) {
const response = await oyster(env, '/capabilities', {
protocol_version: 1,
store_host: env.SHOP_DOMAIN,
currency: env.SHOP_CURRENCY,
platform: 'shopify',
reward_types: REWARD_TYPES,
// A Shopify discount can exclude products only by listing the ones it applies to.
constraints: { excluded_products_require_allowed_products: true },
});
if (!response.ok) console.error('Registration refused', response.status, await response.text());
},
async fetch(request, env) {
const path = new URL(request.url).pathname;
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const rawBody = await request.arrayBuffer();
if (path === '/oyster') return onRewardWon(rawBody, request, env);
if (path === '/shopify/order-paid') return onOrderPaid(rawBody, request, env);
return new Response('Not found', { status: 404 });
},
};
async function onRewardWon(rawBody, request, env) {
if (!(await isFromOyster(rawBody, request.headers.get('Oyster-Signature'), env.OYSTER_WEBHOOK_SECRET))) {
return new Response('Invalid signature', { status: 400 });
}
const { event, data: reward } = JSON.parse(new TextDecoder().decode(rawBody));
if (event !== 'wheel.reward_won' || reward.redemption_authority !== 'store' || !REWARD_TYPES.includes(reward.type)) {
return new Response('Not ours to create', { status: 200 });
}
try {
await createDiscount(env, reward);
return new Response('Created', { status: 200 });
} catch (err) {
// Oyster retries with the same reward_id, and the code check below makes that safe.
console.error(`Reward ${reward.reward_id} not created`, err);
return new Response('Try again', { status: 502 });
}
}
async function onOrderPaid(rawBody, request, env) {
if (!(await isFromShopify(rawBody, request.headers.get('X-Shopify-Hmac-Sha256'), env.SHOPIFY_WEBHOOK_SECRET))) {
return new Response('Invalid signature', { status: 401 });
}
const order = JSON.parse(new TextDecoder().decode(rawBody));
for (const used of order.discount_codes || []) {
const rewardId = await rewardIdForCode(env, used.code);
if (!rewardId) continue;
const response = await oyster(env, '/redemptions', {
reward_id: rewardId,
order_id: String(order.id),
discount_amount: Number(used.amount),
currency: order.currency,
completed_at: order.processed_at || new Date().toISOString(),
});
// Shopify retries the webhook, and the same reward and order return the first receipt.
if (response.status >= 500 || response.status === 429) return new Response('Try again', { status: 502 });
if (!response.ok) console.error(`Oyster refused reward ${rewardId}`, response.status, await response.text());
}
return new Response('OK', { status: 200 });
}
const rewardTitle = (reward) => `Oyster reward ${reward.reward_id}`;
const productGid = (id) => `gid://shopify/Product/${id}`;
async function createDiscount(env, reward) {
if (await rewardIdForCode(env, reward.code)) return;
const combines = reward.restrictions.combines_with_discounts === true;
const excluded = reward.restrictions.excluded_product_ids;
const products = reward.restrictions.allowed_product_ids.filter((id) => !excluded.includes(id));
const input = {
title: rewardTitle(reward),
code: reward.code,
startsAt: new Date().toISOString(),
endsAt: reward.expires_at,
usageLimit: reward.usage_limit,
appliesOncePerCustomer: reward.usage_limit === 1,
context: { customers: { add: [await customerFor(env, reward.email)] } },
combinesWith: {
orderDiscounts: combines,
productDiscounts: combines,
shippingDiscounts: reward.type === 'free_delivery' ? false : combines,
},
...(reward.min_order_amount > 0
? { minimumRequirement: { subtotal: { greaterThanOrEqualToSubtotal: String(reward.min_order_amount) } } }
: {}),
};
const created = reward.type === 'free_delivery'
? (await shopify(env, `mutation ($input: DiscountCodeFreeShippingInput!) {
discountCodeFreeShippingCreate(freeShippingCodeDiscount: $input) { codeDiscountNode { id } userErrors { message } }
}`, { input: { ...input, destination: { all: true } } })).discountCodeFreeShippingCreate
: (await shopify(env, `mutation ($input: DiscountCodeBasicInput!) {
discountCodeBasicCreate(basicCodeDiscount: $input) { codeDiscountNode { id } userErrors { message } }
}`, { input: { ...input, customerGets: {
items: products.length ? { products: { productsToAdd: products.map(productGid) } } : { all: true },
value: reward.type === 'percentage_discount'
? { percentage: reward.value / 100 }
: { discountAmount: { amount: String(reward.value), appliesOnEachItem: false } },
} } })).discountCodeBasicCreate;
// Two deliveries of one win can race; the code is unique, so the loser finds the winner's.
if (!created.codeDiscountNode && !(await rewardIdForCode(env, reward.code))) {
throw new Error(created.userErrors.map((e) => e.message).join('; '));
}
}
async function rewardIdForCode(env, code) {
const data = await shopify(env, `query ($code: String!) {
codeDiscountNodeByCode(code: $code) {
codeDiscount { ... on DiscountCodeBasic { title } ... on DiscountCodeFreeShipping { title } }
}
}`, { code });
const title = data.codeDiscountNodeByCode?.codeDiscount?.title || '';
return title.startsWith('Oyster reward ') ? title.slice('Oyster reward '.length) : null;
}
async function customerFor(env, email) {
const query = `email:${JSON.stringify(email)}`;
const found = await shopify(env, 'query ($query: String!) { customers(first: 2, query: $query) { nodes { id email } } }', { query });
const match = found.customers.nodes.find((c) => c.email?.toLowerCase() === email.toLowerCase());
if (match) return match.id;
const created = await shopify(env, 'mutation ($input: CustomerInput!) { customerCreate(input: $input) { customer { id } userErrors { message } } }', { input: { email } });
if (!created.customerCreate.customer) throw new Error(created.customerCreate.userErrors.map((e) => e.message).join('; '));
return created.customerCreate.customer.id;
}
async function shopify(env, query, variables) {
const response = await fetch(`https://${env.SHOP_DOMAIN}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`, {
method: 'POST',
headers: { 'X-Shopify-Access-Token': env.SHOPIFY_ADMIN_TOKEN, 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
});
const body = await response.json();
if (!response.ok || body.errors) throw new Error(JSON.stringify(body.errors || response.status));
return body.data;
}
function oyster(env, path, body) {
return fetch(OYSTER_WHEEL_URL + path, {
method: 'POST',
headers: {
Authorization: `Bearer ${env.OYSTER_API_KEY}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(body),
});
}
async function isFromOyster(rawBody, header, secret) {
const parts = Object.fromEntries((header || '').split(',').map((part) => part.split('=')));
if (!secret || !/^[0-9a-f]{64}$/.test(parts.v1 || '') || Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) {
return false;
}
const key = await crypto.subtle.importKey(
'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'],
);
const signature = new Uint8Array(parts.v1.match(/../g).map((byte) => parseInt(byte, 16)));
const signed = new Uint8Array([...new TextEncoder().encode(`${parts.t}.`), ...new Uint8Array(rawBody)]);
return crypto.subtle.verify('HMAC', key, signature, signed);
}
// The same check as in the order relay.
async function isFromShopify(rawBody, signature, secret) {
if (!signature || !secret) return false;
let signatureBytes;
try {
signatureBytes = Uint8Array.from(atob(signature), (c) => c.charCodeAt(0));
} catch {
return false;
}
const key = await crypto.subtle.importKey(
'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'],
);
return crypto.subtle.verify('HMAC', key, signatureBytes, rawBody);
}
Spin the wheel and win: the worker's logs should show "Created", and the code appears under Discounts in Shopify, titled with the reward id. Pay an order with it and the use appears in your Spin the Wheel report.
Example: WooCommerce
On WordPress the Oyster for WooCommerce plugin does all of this for you, and more. Use this only if you can't install it. Everything lives in one file that loads the widget, adds scan products to the cart with their ids, copies the ids onto the order, and reports the order once it's paid.
First add your key and vendor id to wp-config.php, so they stay out of the code:
define( 'OYSTER_PUBLIC_KEY', 'YOUR_PUBLIC_KEY' );
define( 'OYSTER_API_KEY', 'YOUR_API_KEY' );
define( 'OYSTER_VENDOR_ID', 142 );
Then save this as wp-content/mu-plugins/oyster.php. Must-use plugins load automatically, with nothing to activate.
<?php
/**
* Plugin Name: Oyster custom integration
*/
defined( 'ABSPATH' ) || exit;
const OYSTER_ORDERS_URL = 'https://api.oysterskin.com/api/v1/integrations/storefront/orders';
// true if some of your products are not in your Oyster catalogue: report only the lines from the scan.
const OYSTER_ONLY_SCAN_LINES = false;
const OYSTER_MAX_ATTEMPTS = 6;
add_action( 'wp_footer', 'oyster_widget_script' );
function oyster_widget_script() {
$user = wp_get_current_user();
$config = array(
'mode' => 'float',
'publicKey' => OYSTER_PUBLIC_KEY,
);
if ( $user->exists() ) {
$config['user'] = array(
'id' => (string) $user->ID,
'name' => $user->display_name,
'email' => $user->user_email,
);
}
?>
<script src="https://widget-lib.oysterskin.com/v1/oysterskin-vendor-widget-web.umd.js"></script>
<script>
(function () {
var config = <?php echo wp_json_encode( $config ); ?>;
var ajaxUrl = <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;
var cartUrl = <?php echo wp_json_encode( wc_get_cart_url() ); ?>;
var checkoutInProgress = false;
function handleCheckout(data) {
var items = ((data && data.checkout_items) || []).filter(function (item) { return item && item.sku; });
if (checkoutInProgress || !items.length) return;
checkoutInProgress = true;
var body = new URLSearchParams({ action: 'oyster_add_to_cart', items: JSON.stringify(items) });
fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
.then(function (res) { return res.json(); })
.then(function (result) { window.location.href = result.redirect || cartUrl; })
.catch(function () { window.location.href = cartUrl; });
}
config.callback = function (message) {
if (message && message.event === 'checkout') handleCheckout(message.data);
};
window.addEventListener('load', function () { OysterskinWidget.createScanWidget(config); });
})();
</script>
<?php
}
add_action( 'wp_ajax_oyster_add_to_cart', 'oyster_add_to_cart' );
add_action( 'wp_ajax_nopriv_oyster_add_to_cart', 'oyster_add_to_cart' );
function oyster_add_to_cart() {
$items = json_decode( wp_unslash( $_POST['items'] ?? '[]' ), true );
$added = 0;
foreach ( is_array( $items ) ? $items : array() as $item ) {
$product_id = wc_get_product_id_by_sku( sanitize_text_field( $item['sku'] ?? '' ) );
$product = $product_id ? wc_get_product( $product_id ) : null;
if ( ! $product || ! $product->is_purchasable() || ! $product->is_in_stock() ) {
continue;
}
$scan = array();
$batch_id = (string) ( $item['skin_analysis_batch_id'] ?? '' );
if ( preg_match( '/^[A-Za-z0-9_-]{1,128}$/', $batch_id ) ) {
$scan['oyster_batch_id'] = $batch_id;
}
$routine_id = absint( $item['product_usage_routine_id'] ?? 0 );
if ( $routine_id ) {
$scan['oyster_routine_id'] = $routine_id;
}
$is_variation = $product->is_type( 'variation' );
$cart_key = WC()->cart->add_to_cart(
$is_variation ? $product->get_parent_id() : $product->get_id(),
max( 1, absint( $item['quantity'] ?? 1 ) ),
$is_variation ? $product->get_id() : 0,
$is_variation ? $product->get_variation_attributes() : array(),
$scan
);
if ( $cart_key ) {
$added++;
}
}
wp_send_json( array( 'redirect' => $added ? wc_get_checkout_url() : wc_get_cart_url() ) );
}
add_action( 'woocommerce_checkout_create_order_line_item', 'oyster_copy_scan_to_order_line', 10, 3 );
function oyster_copy_scan_to_order_line( $item, $cart_item_key, $values ) {
if ( ! empty( $values['oyster_batch_id'] ) ) {
$item->add_meta_data( '_oyster_batch_id', $values['oyster_batch_id'], true );
}
if ( ! empty( $values['oyster_routine_id'] ) ) {
$item->add_meta_data( '_oyster_routine_id', $values['oyster_routine_id'], true );
}
}
// Reported in the background so a slow response never holds up the shopper's order.
add_action( 'woocommerce_order_status_processing', 'oyster_queue_order_report' );
add_action( 'woocommerce_order_status_completed', 'oyster_queue_order_report' );
add_action( 'oyster_report_order', 'oyster_report_order', 10, 2 );
function oyster_queue_order_report( $order_id ) {
$order = wc_get_order( $order_id );
if ( $order && ! $order->get_meta( '_oyster_reported' ) ) {
as_enqueue_async_action( 'oyster_report_order', array( $order_id, 1 ), 'oyster' );
}
}
function oyster_money( $cents ) {
return number_format( $cents / 100, 2, '.', '' );
}
function oyster_order_payload( WC_Order $order ) {
$lines = array();
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
$sku = $product ? trim( $product->get_sku() ) : '';
$quantity = (int) $item->get_quantity();
if ( '' === $sku || $quantity < 1 ) {
continue;
}
$price_cents = (int) round( (float) $item->get_subtotal() * 100 / $quantity );
$lines[] = array(
'line_item_id' => (string) $item_id,
'sku' => $sku,
'quantity' => $quantity,
'price_cents' => $price_cents,
'discount_cents' => max( 0, $price_cents * $quantity - (int) round( (float) $item->get_total() * 100 ) ),
'skin_analysis_batch_id' => $item->get_meta( '_oyster_batch_id' ) ?: null,
'product_usage_routine_id' => (int) $item->get_meta( '_oyster_routine_id' ) ?: null,
);
}
$from_scan = function ( $line ) {
return $line['skin_analysis_batch_id'] || $line['product_usage_routine_id'];
};
if ( ! array_filter( $lines, $from_scan ) ) {
return null;
}
$sent = OYSTER_ONLY_SCAN_LINES ? array_values( array_filter( $lines, $from_scan ) ) : $lines;
$shipping_cents = OYSTER_ONLY_SCAN_LINES ? 0 : (int) round( (float) $order->get_shipping_total() * 100 );
$tax_cents = OYSTER_ONLY_SCAN_LINES ? 0 : (int) round( (float) $order->get_total_tax() * 100 );
$subtotal_cents = 0;
$discount_cents = 0;
foreach ( $sent as $line ) {
$subtotal_cents += $line['price_cents'] * $line['quantity'];
$discount_cents += $line['discount_cents'];
}
$placed_at = $order->get_date_paid() ?: $order->get_date_created();
return array(
'vendor_id' => (int) OYSTER_VENDOR_ID,
'order_id' => (string) $order->get_id(),
'order_number' => (string) $order->get_order_number(),
'currency' => $order->get_currency(),
'placed_at' => $placed_at->format( DATE_ATOM ),
'total' => oyster_money( $subtotal_cents - $discount_cents + $shipping_cents + $tax_cents ),
'shipping_amount' => oyster_money( $shipping_cents ),
'tax_amount' => oyster_money( $tax_cents ),
'discount_amount' => oyster_money( $discount_cents ),
'line_items' => array_map(
function ( $line ) {
return array(
'line_item_id' => $line['line_item_id'],
'sku' => $line['sku'],
'quantity' => $line['quantity'],
'price' => oyster_money( $line['price_cents'] ),
'discount_amount' => oyster_money( $line['discount_cents'] ),
'skin_analysis_batch_id' => $line['skin_analysis_batch_id'],
'product_usage_routine_id' => $line['product_usage_routine_id'],
);
},
$sent
),
);
}
function oyster_report_order( $order_id, $attempt ) {
$order = wc_get_order( $order_id );
if ( ! $order || $order->get_meta( '_oyster_reported' ) ) {
return;
}
$payload = oyster_order_payload( $order );
if ( ! $payload ) {
$order->update_meta_data( '_oyster_reported', 'not_from_scan' );
$order->save();
return;
}
$response = wp_remote_post(
OYSTER_ORDERS_URL,
array(
'timeout' => 15,
'headers' => array(
'Authorization' => 'Bearer ' . OYSTER_API_KEY,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
),
'body' => wp_json_encode( $payload ),
)
);
$status = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
// 409 and 422 won't change on a retry: record the answer and stop.
if ( ( $status >= 200 && $status < 300 ) || 409 === $status || 422 === $status ) {
if ( $status >= 300 ) {
wc_get_logger()->warning( "Oyster refused order {$order_id}: " . wp_remote_retrieve_body( $response ), array( 'source' => 'oyster' ) );
}
$order->update_meta_data( '_oyster_reported', (string) $status );
$order->save();
return;
}
wc_get_logger()->warning( "Oyster answered {$status} for order {$order_id}, attempt {$attempt}", array( 'source' => 'oyster' ) );
if ( $attempt < OYSTER_MAX_ATTEMPTS ) {
as_schedule_single_action( time() + 600 * $attempt, 'oyster_report_order', array( $order_id, $attempt + 1 ), 'oyster' );
}
}
This works with both the classic and the block checkout. Processing is the usual "paid" status. If your store marks paid orders differently, change the two status hooks. Failed reports are logged under WooCommerce → Status → Logs, source oyster. If you run a full-page cache, it can cache the widget script like the rest of the page. That's fine, since nothing in it is per-visitor apart from the logged-in shopper, and cache plugins already skip logged-in visitors.
Keeping the catalogue in sync
Add this to the same file. It upserts a product when you create or edit it, sends stock when it changes, archives a product when you trash or unpublish it, and runs a full sync every night. Each request names the store as woocommerce and sends WooCommerce's own product and variation ids (store ids), so variable products sync one row per variation. Products without a SKU or a price are skipped, to match the order code above, which reports lines by SKU.
const OYSTER_PRODUCTS_URL = 'https://api.oysterskin.com/api/v1/integrations/storefront/products';
add_action( 'woocommerce_new_product', 'oyster_queue_product_sync' );
add_action( 'woocommerce_update_product', 'oyster_queue_product_sync' );
add_action( 'woocommerce_new_product_variation', 'oyster_queue_product_sync' );
add_action( 'woocommerce_update_product_variation', 'oyster_queue_product_sync' );
add_action( 'woocommerce_product_set_stock', 'oyster_queue_stock_sync' );
add_action( 'woocommerce_variation_set_stock', 'oyster_queue_stock_sync' );
add_action( 'wp_trash_post', 'oyster_archive_trashed_product' );
add_action( 'oyster_sync_product', 'oyster_sync_product' );
add_action( 'oyster_sync_stock', 'oyster_sync_stock' );
add_action( 'oyster_full_catalogue_sync', 'oyster_full_catalogue_sync' );
add_action( 'init', function () {
if ( function_exists( 'as_has_scheduled_action' ) && ! as_has_scheduled_action( 'oyster_full_catalogue_sync' ) ) {
as_schedule_recurring_action( strtotime( 'tomorrow 03:00' ), DAY_IN_SECONDS, 'oyster_full_catalogue_sync', array(), 'oyster' );
}
} );
// Queued so a slow response never holds up saving a product or placing an order.
function oyster_queue_product_sync( $product_id ) {
as_enqueue_async_action( 'oyster_sync_product', array( (int) $product_id ), 'oyster', true );
}
function oyster_queue_stock_sync( $product ) {
as_enqueue_async_action( 'oyster_sync_stock', array( $product->get_id() ), 'oyster', true );
}
function oyster_catalogue_request( $method, $path, array $body ) {
$response = wp_remote_request(
OYSTER_PRODUCTS_URL . $path,
array(
'method' => $method,
'timeout' => 30,
'headers' => array(
'Authorization' => 'Bearer ' . OYSTER_API_KEY,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
),
'body' => wp_json_encode( array( 'platform' => 'woocommerce' ) + $body ),
)
);
$status = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
// Anything short of a clean 200 is logged; the nightly sync resends it.
if ( 200 !== $status ) {
$detail = is_wp_error( $response ) ? $response->get_error_message() : wp_remote_retrieve_body( $response );
wc_get_logger()->warning( "Oyster {$path} answered {$status}: {$detail}", array( 'source' => 'oyster' ) );
}
}
function oyster_stock_level( WC_Product $product ) {
if ( $product->managing_stock() ) {
return max( 0, (int) $product->get_stock_quantity() );
}
return $product->is_in_stock() ? 100 : 0;
}
function oyster_product_rows( $product ) {
if ( ! $product ) {
return array();
}
if ( $product->is_type( 'variable' ) ) {
return array_merge( array(), ...array_map( fn ( $id ) => oyster_product_rows( wc_get_product( $id ) ), $product->get_children() ) );
}
$sku = trim( (string) $product->get_sku() );
if ( '' === $sku || '' === $product->get_price() ) {
return array();
}
$parent = $product->get_parent_id() ? wc_get_product( $product->get_parent_id() ) : $product;
$terms = get_the_terms( $parent->get_id(), 'product_cat' );
$image = wp_get_attachment_image_url( $product->get_image_id() ?: $parent->get_image_id(), 'full' );
return array(
array_filter(
array(
'sku' => $sku,
'external_product_id' => (string) $parent->get_id(),
'external_variant_id' => $product->get_parent_id() ? (string) $product->get_id() : null,
'name' => $product->get_name(),
'price' => (float) $product->get_price(),
'currency' => get_woocommerce_currency(),
'stock_level' => oyster_stock_level( $product ),
'description' => wp_strip_all_tags( $parent->get_description() ),
'category' => $terms && ! is_wp_error( $terms ) ? $terms[0]->name : null,
'image_url' => $image ?: null,
),
fn ( $value ) => null !== $value && '' !== $value
),
);
}
function oyster_sync_product( $product_id ) {
$product = wc_get_product( $product_id );
$rows = oyster_product_rows( $product );
if ( ! $rows ) {
return;
}
$listing = $product->get_parent_id() ? wc_get_product( $product->get_parent_id() ) : $product;
if ( 'publish' === $listing->get_status() ) {
oyster_catalogue_request( 'POST', '/bulk-upsert', array( 'products' => $rows ) );
} else {
oyster_catalogue_request( 'POST', '/archive', array( 'skus' => array_column( $rows, 'sku' ) ) );
}
}
function oyster_sync_stock( $product_id ) {
$product = wc_get_product( $product_id );
$sku = $product ? trim( (string) $product->get_sku() ) : '';
if ( '' !== $sku ) {
oyster_catalogue_request( 'PATCH', '/stock', array( 'stock_updates' => array( array( 'sku' => $sku, 'stock_level' => oyster_stock_level( $product ) ) ) ) );
}
}
// Runs before the product goes to the trash, while its SKUs can still be read.
function oyster_archive_trashed_product( $post_id ) {
$rows = oyster_product_rows( wc_get_product( $post_id ) );
if ( $rows ) {
oyster_catalogue_request( 'POST', '/archive', array( 'skus' => array_column( $rows, 'sku' ) ) );
}
}
function oyster_full_catalogue_sync() {
$rows = array();
foreach ( wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'return' => 'ids' ) ) as $product_id ) {
array_push( $rows, ...oyster_product_rows( wc_get_product( $product_id ) ) );
}
foreach ( array_chunk( $rows, 250 ) as $chunk ) {
oyster_catalogue_request( 'POST', '/bulk-upsert', array( 'products' => $chunk ) );
}
}
Run the first full sync straight away with Tools → Scheduled Actions: search for oyster_full_catalogue_sync and click Run.
Spin the Wheel rewards
For step 6, add this to the same file. It registers your checkout every day, turns each won code into a WooCommerce coupon for the shopper's email address, and reports the coupon's use when the order is paid. It handles percentage, fixed and free-delivery rewards. For free delivery, set your Free shipping method to require a valid coupon.
- Give the API key in OYSTER_API_KEY Honour Spin the Wheel rewards at your checkout as well.
- In your Oyster dashboard, Developers → Webhooks, add https://your-store.example/wp-json/oyster/v1/wheel for wheel.reward_won.
- Add its signing secret to wp-config.php as define( 'OYSTER_WEBHOOK_SECRET', '...' );
const OYSTER_WHEEL_URL = 'https://api.oysterskin.com/api/v1/integrations/storefront/wheel';
const OYSTER_REWARD_TYPES = array( 'percentage_discount', 'fixed_discount', 'free_delivery' );
add_action( 'oyster_register_wheel', 'oyster_register_wheel' );
add_action( 'oyster_report_reward_use', 'oyster_report_reward_use', 10, 3 );
add_action( 'woocommerce_order_status_processing', 'oyster_queue_reward_uses' );
add_action( 'woocommerce_order_status_completed', 'oyster_queue_reward_uses' );
add_action( 'init', function () {
if ( function_exists( 'as_has_scheduled_action' ) && ! as_has_scheduled_action( 'oyster_register_wheel' ) ) {
as_schedule_recurring_action( time(), DAY_IN_SECONDS, 'oyster_register_wheel', array(), 'oyster' );
}
} );
add_action( 'rest_api_init', function () {
register_rest_route( 'oyster/v1', '/wheel', array(
'methods' => 'POST',
'callback' => 'oyster_on_reward_won',
'permission_callback' => '__return_true', // The signature below is the check.
) );
} );
function oyster_wheel_request( $path, array $body ) {
$response = wp_remote_post(
OYSTER_WHEEL_URL . $path,
array(
'timeout' => 15,
'headers' => array(
'Authorization' => 'Bearer ' . OYSTER_API_KEY,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
),
'body' => wp_json_encode( $body ),
)
);
return is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
}
function oyster_register_wheel() {
$status = oyster_wheel_request( '/capabilities', array(
'protocol_version' => 1,
'store_host' => wp_parse_url( home_url(), PHP_URL_HOST ),
'currency' => get_woocommerce_currency(),
'platform' => 'woocommerce',
'reward_types' => OYSTER_REWARD_TYPES,
// A WooCommerce fixed-cart coupon takes its amount off the whole cart.
'constraints' => array( 'fixed_discount_product_restrictions' => false ),
) );
if ( 200 !== $status ) {
wc_get_logger()->warning( "Oyster refused the wheel registration: {$status}", array( 'source' => 'oyster' ) );
}
}
function oyster_is_from_oyster( WP_REST_Request $request ) {
parse_str( str_replace( ',', '&', (string) $request->get_header( 'oyster_signature' ) ), $parts );
if ( empty( $parts['t'] ) || empty( $parts['v1'] ) || abs( time() - (int) $parts['t'] ) > 300 ) {
return false;
}
$expected = hash_hmac( 'sha256', $parts['t'] . '.' . $request->get_body(), OYSTER_WEBHOOK_SECRET );
return hash_equals( $expected, (string) $parts['v1'] );
}
function oyster_on_reward_won( WP_REST_Request $request ) {
if ( ! oyster_is_from_oyster( $request ) ) {
return new WP_REST_Response( 'Invalid signature', 400 );
}
$event = json_decode( $request->get_body(), true );
$reward = $event['data'] ?? array();
if ( 'wheel.reward_won' !== ( $event['event'] ?? '' ) || 'store' !== ( $reward['redemption_authority'] ?? '' )
|| ! in_array( $reward['type'], OYSTER_REWARD_TYPES, true ) ) {
return new WP_REST_Response( 'Not ours to create', 200 );
}
// A retry carries the same code.
if ( wc_get_coupon_id_by_code( $reward['code'] ) ) {
return new WP_REST_Response( 'Already created', 200 );
}
$coupon = new WC_Coupon();
$coupon->set_code( $reward['code'] );
$coupon->set_discount_type( 'percentage_discount' === $reward['type'] ? 'percent' : 'fixed_cart' );
$coupon->set_amount( 'free_delivery' === $reward['type'] ? 0 : $reward['value'] );
$coupon->set_free_shipping( 'free_delivery' === $reward['type'] );
$coupon->set_usage_limit( $reward['usage_limit'] );
$coupon->set_usage_limit_per_user( $reward['usage_limit'] );
$coupon->set_email_restrictions( array( strtolower( $reward['email'] ) ) );
$coupon->set_individual_use( ! $reward['restrictions']['combines_with_discounts'] );
$coupon->set_product_ids( array_map( 'intval', $reward['restrictions']['allowed_product_ids'] ) );
$coupon->set_excluded_product_ids( array_map( 'intval', $reward['restrictions']['excluded_product_ids'] ) );
$coupon->set_minimum_amount( $reward['min_order_amount'] ?? 0 );
$coupon->set_date_expires( $reward['expires_at'] ? strtotime( $reward['expires_at'] ) : null );
$coupon->set_description( 'Oyster wheel reward' );
$coupon->update_meta_data( '_oyster_reward_id', $reward['reward_id'] );
$coupon->save();
return new WP_REST_Response( 'Created', 200 );
}
function oyster_queue_reward_uses( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
foreach ( $order->get_coupons() as $item ) {
$reward_id = ( new WC_Coupon( $item->get_code() ) )->get_meta( '_oyster_reward_id' );
if ( $reward_id && ! $order->get_meta( "_oyster_reward_reported_{$reward_id}" ) ) {
as_enqueue_async_action( 'oyster_report_reward_use', array( $order_id, $reward_id, 1 ), 'oyster' );
}
}
}
function oyster_report_reward_use( $order_id, $reward_id, $attempt ) {
$order = wc_get_order( $order_id );
$item = current( array_filter(
$order->get_coupons(),
fn ( $coupon ) => ( new WC_Coupon( $coupon->get_code() ) )->get_meta( '_oyster_reward_id' ) === $reward_id
) );
$paid = $order->get_date_paid() ?: $order->get_date_created();
$status = oyster_wheel_request( '/redemptions', array(
'reward_id' => $reward_id,
'order_id' => (string) $order_id,
'discount_amount' => $item ? (float) $item->get_discount() : 0,
'currency' => $order->get_currency(),
'completed_at' => $paid->date( DATE_ATOM ),
) );
// The same reward and order return the first receipt, so a retry is safe.
if ( $status >= 500 || 0 === $status || 429 === $status ) {
if ( $attempt < OYSTER_MAX_ATTEMPTS ) {
as_schedule_single_action( time() + 600 * $attempt, 'oyster_report_reward_use', array( $order_id, $reward_id, $attempt + 1 ), 'oyster' );
}
return;
}
if ( 200 !== $status ) {
wc_get_logger()->warning( "Oyster refused reward {$reward_id} on order {$order_id}: {$status}", array( 'source' => 'oyster' ) );
}
$order->update_meta_data( "_oyster_reward_reported_{$reward_id}", (string) $status );
$order->save();
}
Win a reward on your site: a coupon with the shopper's code appears under Marketing → Coupons, described as "Oyster wheel reward". Pay an order with it and the use appears in your Spin the Wheel report.
Payments, rewards, webhooks
- Charging for the scan or a booking through your own checkout. See Your own gateway. It is a separate API key scope, confirmed from the same server-side hook that sees your order become paid.
- Welcome offers. The checkout event can carry a welcome_offer code. It's a code you created in your own store, so apply it at your checkout (most platforms accept it on the checkout URL or through a coupon field). Spin the Wheel rewards are step 6.
- Scan results in your own systems. Webhooks send your server each finished scan, signed, so you can attach it to a customer record or start a follow-up.
Test it
- Run a scan on your site. In the browser console you should see no errors from the widget.
- Tap the buy button. You should land on your checkout with the recommended products in the cart.
- Check the cart lines carry the scan ids: line properties on Shopify, item data on WooCommerce, your columns on your own build.
- Pay with a test payment method. Your server's log should show a 201 from Oyster.
- Open Orders in your Oyster dashboard. The order is there, credited to the scan.
- Place one order without using the scan. Your server should skip it, or Oyster should answer no_recommendation_items.
Troubleshooting
| What you see | Likely cause | Fix |
|---|---|---|
| The widget never appears | Your domain isn't on the allowed list, or the script didn't load | Add the domain in Widget Manager. Check the console and your Content Security Policy (see CSP). |
| Buy button does nothing | No callback, or it throws | Log every message in the callback and check the console. |
| Shopper lands on the cart, not checkout | None of the SKUs were found or in stock | Compare SKUs character for character. Check the products are published and in stock. |
| Order paid, but no scan ids on its lines | The ids were added to the cart but not copied to the order | Check step 4 for your platform. |
| 401 or 403 from Oyster | Wrong key, or it doesn't have Manage orders | Create a key in API Manager with Manage orders. |
| 422 catalog_product_unresolved | A line's SKU isn't in Oyster | Sync the product (step 1), or report only the lines from the scan. |
| A product is recommended while sold out, or at an old price | Stock or price changes aren't reaching Oyster | Send stock as it changes, and run the nightly full sync. |
| managed_by_connected_store on sync | Your Oyster Shopify app or WooCommerce plugin already syncs that product | Nothing to do. Let the app keep it in sync, or disconnect the app if this integration replaces it. |
| 422 purchase_amount_mismatch | The totals don't add up | Calculate total from what you send. See Money. |
| 422 recommendation_mismatch | A line was tagged with a scan that didn't recommend it | Tag a line only with the ids the checkout event gave for that SKU. |
| Won codes don't work at your checkout | Rewards are still issued for Oyster's checkout: the registration lapsed, its key was deleted, or no webhook endpoint listens for wheel.reward_won | Check all three in Register your checkout, then register again. |
| 404 reporting a reward's use | The reward was issued for another checkout | Report only rewards whose redemption_authority was store. |
| 409 | The order was already reported with different content | Report each order once, when paid. Don't re-report after edits or refunds. |
Launch checklist
- Your catalogue synced to Oyster with the same SKUs, and stock and price updates flowing, plus the nightly full sync.
- Your live domain on the allowed list, and the production script URL (/v1/, not /latest/ or sandbox).
- The API key on your server only, with Manage catalogue and Manage orders, plus Honour Spin the Wheel rewards at your checkout if you run the wheel, and nothing more.
- Scan ids reach the paid order's lines.
- Orders are reported once, when paid. Retries happen only for network errors, 429 and 5xx.
- A test order shows in your Oyster dashboard, credited to its scan.
- If you run Spin the Wheel: your checkout registered, a daily refresh scheduled, a won code created in your checkout, and its use showing in your Spin the Wheel report.