Skip to content

About

Printify for Payload: print-on-demand for Payload’s ecommerce plugin, with product sync, order fulfillment and tracking, and optional price write-back.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Printify plugin for Payload ecommerce

Connects a Printify shop to a store built with Payload's official ecommerce plugin:

  • Products → store. Products published (or created/updated) in Printify are synced into the store's products, variants, variantTypes and variantOptions, with prices (cents), enabled variants and mockup image links. Products removed in Printify become drafts. Works with any sales channel (Pop-Up Store, Etsy, Shopify, ...). For shops on Printify's API channel, publishHandshake: true also answers Printify's publishing events (publishing_succeeded with your product URL).
  • Prices → Printify (optional). With pushPrices: true, a price edited on a synced variant in Payload is written to the Printify product first; if Printify refuses (product locked while publishing, API error, your guard), the edit is refused, so the two never disagree.
  • Visibility, both ways. Hidden Printify products are imported as drafts; visible ones are published. With pushVisibility: true, Publish/Unpublish on a synced product in Payload also publishes/unpublishes it in Printify first (refused if Printify refuses). "Save draft" does not.
  • Orders → Printify. When an order becomes paid (status: processing), its Printify items are sent as a Printify order (external_id = your order id). Orders wait in Printify for approval unless sendToProduction: true. The order is sent once and never retried. Before the create goes out, the order is marked sending in one conditional write, so of two saves that pay the same order at once only one sends it. Each send is also written to a hidden send ledger outside the save's transaction (see The send ledger), so an order that reached Printify is never created there again, even when the save that paid it is rolled back. Sending needs MongoDB transactions (see Database transactions); without them nothing is sent. If Printify answers with a server error, times out or the connection drops, it may have created the order anyway, so fulfillment.status becomes unknown and the plugin won't send that order again on its own. If Printify answers 409 for an order it already holds with this external_id, that order is recorded and nothing new is created. If Printify did create it, its next order webhook settles the order by external_id. Otherwise staff settle it (see Orders with an unknown outcome). A duplicated order is marked copied and is never sent. An order with an item whose Printify link doesn't match its product is not sent; it is marked failed (see Fields only the plugin writes).
  • Printify → orders. Order and shipment webhooks update fulfillment on the order (status, carrier, tracking number and URL). In a multi-tenant setup, only the owning store's orders.

Self-contained: it depends only on payload and Node's crypto.

On its own, and with others

On its own. Printify needs Payload's official ecommerce plugin, listed before it, plus a Printify shop, a personal access token and a webhook secret. It doesn't use any other plugin.

Works with:

  • Payload ecommerce (@payloadcms/plugin-ecommerce): required. Printify adds fields and hooks to its products, variants and orders.
  • Multi-tenant stores (for example @payloadcms/plugin-multi-tenant): the tenant option says which site owns the synced products.

Family. Printify is in the Patronage family, with Membership, Sponsors, Backing, Credits and Roadmap, though nothing in the code links it to them yet. The families are a working draft that may change.

Install

npm install @extantape/payload-plugin-printify
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
import { printifyPlugin } from '@extantape/payload-plugin-printify'

export default buildConfig({
  plugins: [
    ecommercePlugin({ /* ... */ inventory: false }), // print on demand: no stock to count
    printifyPlugin({
      apiToken: process.env.PRINTIFY_API_TOKEN,
      shopId: process.env.PRINTIFY_SHOP_ID,
      webhookSecret: process.env.PRINTIFY_WEBHOOK_SECRET,
      productURL: ({ slug }) => `https://example.com/shop/${slug}`,
      // Optional:
      // sendToProduction: true,
      // pushPrices: true,
      // pushVisibility: true,
      // publishHandshake: true,                                          // shop on the API sales channel
      // beforePrintifyWrite: ({ action, doc, req }) => { if (!isProduction) throw new Error('staging only reads Printify') },
      // access: { manage: ({ req }) => req.user?.roles?.includes('admin') === true }, // who may settle orders
      // settle: { resend: true, resendAfterMinutes: 30 },                // allow resending unknown orders
      // allowUnguardedSends: true,                                       // send without transactions: read Database transactions first
      // currency: 'USD',                                                 // priceIn<currency> fields
      // tenant: { field: 'tenant', resolve: async (payload) => tenantId }, // multi-tenant stores
      // collections: { products: 'products', orders: 'orders', sends: 'printify-sends' }, // custom slugs
    }),
  ],
})

Add it after ecommercePlugin. It adds:

Collection Fields
products title, slug, description, images[] (only if missing), printify (productId, shopId, blueprintId, printProviderId, syncedAt), its lock hook and the visibility push hook
variants printify (variantId, productId, sku), the link lock hook, the price push and "from" price hooks
orders fulfillment (provider, externalId, status, error, submittedAt, sendingAt, unknownAt, shipments[]), its lock hook and the submit hook

and two endpoints: POST /api/printify/webhook, which rejects requests without a valid X-Pfy-Signature (HMAC-SHA256 of the body with webhookSecret), and POST /api/printify/orders/:id/settle (below).

Set up

  1. Printify → My Profile → Connections → generate a personal access token (scopes: shops, products, orders, webhooks). Store it as an environment variable.
  2. Find the shop id: listPrintifyShops(token) → [{ id, title, sales_channel }].
  3. Generate a webhook secret: openssl rand -hex 20.
  4. Deploy, then register webhooks once per deployment URL: await registerPrintifyWebhooks(payload, 'https://example.com').
  5. Import existing products: await syncPrintifyShop(payload) (safe to re-run; read-only on Printify).

Fields only the plugin writes

An order's fulfillment, a product's printify group and a variant's printify.variantId and printify.productId are written only by the plugin: fulfillment by the paid-order hook, webhooks and settling, the product and variant links by the sync. Every other write keeps what is stored. That covers the REST, GraphQL and admin API, the Local API with or without overrideAccess, a host's own hooks, version restores and duplicates. Values sent there are dropped and the rest of the save goes through.

  • Seed and import code can't set them. To link a product to Printify, sync it (syncPrintifyShop, syncPrintifyProduct or a Printify product webhook). To change an order's Printify state, settle it (below).
  • A duplicated order gets fulfillment.status: copied and is never sent to Printify, even when it is paid or moved back to paid later. Copies of copies are copied too. Settling refuses a copied order (409) and sends nothing. To ship the same items again, create a new order.
  • A duplicated product or variant starts with no Printify link, so the sync, webhooks, price and visibility pushes and orders only ever use the original.
  • A version restore brings back the rest of the document and keeps these fields as they are.
  • A variant's sku is copied from Printify for display. The plugin never reads it, so it stays editable.

What an order line is sent as. Each item is sent with the variant's printify.variantId and printify.productId, both written by the sync. The variant's printify.productId must equal its product's printify.productId. If any item fails that check (a variant synced before productId existed, or a variant whose product was changed in Payload), nothing is sent for the whole order, fulfillment.status becomes failed with an error naming the fix, and the server log gets an error. To send it: run syncPrintifyShop, then set the order back to pending and then to processing. A resend settle that meets such an item answers 409, sends nothing and leaves the order as it was; run the sync, then settle again.

The plugin's own writes. The plugin marks each of its writes with a grant that only it can make, for one document and the exact values it writes, valid only while that write runs. Request context sent by a client can't carry it. Another write on the same request, for example a host hook that updates the same order from inside the plugin's write, doesn't match those values, so it is locked like any other write, and the plugin's result is still recorded. If a host beforeChange hook changes the plugin's values inside its write, the plugin writes its result straight to the database (skipping hooks and versions) as long as the order's Printify status hasn't moved on meanwhile, and logs an error either way. The order is still sent only once.

Database transactions

The plugin sends paid orders to Printify, and settles orders, only inside a MongoDB transaction. That needs a MongoDB replica set (a single-node replica set is enough) with Payload's transactionOptions left on, which is the MongoDB adapter's default. Inside a transaction, an order saved by someone else while it is being sent fails with an error and the plugin's Printify record stands.

Without transactions (a standalone MongoDB, transactionOptions: false, or another database adapter):

  • The plugin logs an error at startup saying paid orders will not be sent.
  • A paid order is not sent. Its fulfillment.status is set to failed, with an error saying transactions are needed, unless a save made at the same moment writes over that mark; either way nothing is sent. Once transactions are on, send it by setting the order to pending, then to processing. It is sent once.
  • Settling answers 500 and changes nothing.

The same holds for a single request that turns transactions off: an order created as paid with disableTransaction: true is marked failed and not sent.

While the plugin can send, updates to orders made outside a transaction are refused with a 409 error, including Local API calls with disableTransaction: true. Creating orders that way still works. Direct database writes (payload.db.updateOne and the like) skip Payload's hooks, so the plugin can't check them: don't write orders that way while they may be paid.

Only the MongoDB adapter is accepted for now. The Postgres and SQLite adapters haven't been tested, so the plugin sends nothing on them.

allowUnguardedSends: true turns the requirement off: the plugin sends and settles without a transaction, on any adapter. If anyone saves an order (in the admin, over the API or from your own code) while it is being sent, that save can write over the order's Printify record. The order then shows either no Printify state or sending. The send ledger still holds the Printify order, and setting the order to pending, then processing creates no second one:

  • An order with no Printify state gets its Printify id back.
  • An order left sending keeps that status. After 10 minutes staff can settle it, and a resend records the Printify order the ledger holds.

Tested on MongoDB only. With it on, don't edit orders while they are being paid.

The send ledger

The plugin adds a hidden collection, printify-sends (rename it with collections.sends). It holds one record per order the plugin has started sending: whether the send is under way, sent, failed or unclear, and the Printify order id once Printify answers. The plugin writes it straight to the database, outside the transaction of the save that paid the order, so a rolled-back save or a later save of the order can't erase it.

  • Each order is created in Printify once. A send that definitely failed can be sent again.
  • When an order's record says Printify has it, paying the order again records that Printify order on it, and nothing is created.
  • When a send is still under way or its outcome is unclear, the order is marked unknown and staff settle it (see Orders with an unknown outcome). Settling as sent, or a resend, updates the record.
  • If the ledger can't be written, the order is marked failed and nothing is sent.

Clients can't read it: its access answers false, so REST, GraphQL and the admin get nothing. Only server code can read it, for example the Local API with its default overrideAccess: true. Its hooks refuse every create, update and delete through Payload, the Local API included. Records are kept. Don't delete them or write them with payload.db: the plugin relies on them to send each order once.

On a multi-tenant host, leave this collection out of the multi-tenant plugin's collections; it has no tenant field and no client reads it.

Upgrading to 0.3.0

Writes from your own code to an order's fulfillment, a product's printify group or a variant's printify.variantId and printify.productId are now ignored, Local API included. Duplicated orders are never sent, and duplicated products and variants start unlinked. An order with an item whose variant isn't linked to its product's Printify product isn't sent; it is marked failed. Paid orders are sent, and orders settled, only with MongoDB transactions on. The plugin adds a hidden printify-sends collection (see The send ledger); on MongoDB it needs no migration. After upgrading:

  1. Make sure your database runs MongoDB transactions: a replica set, with Payload's transactionOptions not set to false (see Database transactions). If the plugin logs "paid orders will NOT be sent" at startup, they aren't on. Orders paid meanwhile are marked failed; send them afterwards by setting them to pending, then processing. Also remove disableTransaction: true from your own code that updates orders.
  2. Remove any host code that writes these fields. Link products by syncing; change an order's Printify state by settling it.
  3. If you settle orders, give the orders collection update access that allows the staff who settle (see Orders with an unknown outcome).
  4. Run await syncPrintifyShop(payload) once, so every variant stores its Printify product. Until it has run, orders with variants synced by an earlier release are not sent; they are marked failed, and you can send them afterwards by setting them to pending and then processing.
  5. In Printify, look for more than one order for the same shop order (the same external id), and cancel the extra ones that haven't shipped.
  6. Check that each product with a printify.productId links one of your shop's Printify products, and that no two products link the same one. Then run syncPrintifyShop again. Two products can offer the same Printify variantId, so variants sharing one is normal and needs no change.
  7. If you list collections by slug (for access rules, the multi-tenant plugin, backups or exports), leave printify-sends out of tenant scoping, and keep it in backups. Orders sent before this release have no ledger record; they keep their Printify id on the order as before.

Staging copies

Staging and production usually read the same Printify shop. Pass beforePrintifyWrite and throw outside production: orders are then marked held and price and visibility edits are refused, while product sync (read-only on Printify) keeps working everywhere.

Orders with an unknown outcome

When creating a Printify order fails with a server error, a timeout or a dropped connection, Printify may have created it anyway. The order gets fulfillment.status: unknown and is never sent again on its own. While a create is out, the order reads sending. An order still sending 10 minutes later (the process stopped mid-send) is treated like an unknown one.

Printify tells us. Any signed Printify order event whose order carries our order id (external_id, or metadata.shop_order_id) settles it: the Printify id and status are recorded. This only happens while some order is unknown or sending, so other order events cost no extra Printify call.

Staff settle it. Look for the order id in Printify (it's the order's external_id and label), then:

import { settleUnknownOrder } from '@extantape/payload-plugin-printify'

// It's in Printify: record it. The plugin reads that order from Printify first and records it
// only if it carries this order id, with Printify's status and shipments.
await settleUnknownOrder(payload, { order: orderId, outcome: 'sent', printifyId: 'Printify order id', req })

// It isn't: send it now, once. Off unless the host sets `settle: { resend: true }`.
await settleUnknownOrder(payload, { order: orderId, outcome: 'resend', req })

From the admin (signed in), the same as a request:

curl -X POST https://example.com/api/printify/orders/ORDER_ID/settle \
  -H 'Content-Type: application/json' -b 'payload-token=...' \
  -d '{"outcome":"sent","printifyId":"PRINTIFY_ORDER_ID"}'

It answers 200 with the new fulfillment, 400 for a missing or malformed printifyId or a wrong outcome, 403 when you may not settle that order, 404 when there is no such order, 409 when the order can't be settled as asked (already recorded, still being sent, no longer paid, Printify turned off here, resending off, the wait not over, or the Printify order belongs to another order), and 502 when Printify couldn't be read or didn't confirm.

What a host must set up:

  • access.manage: only people it answers exactly true for may settle. It is called with { req, id, data }. A query, any other truthy value or an error is a no. With no access.manage, nobody can.
  • The orders collection's update access must also allow that person that order. Settling calls it with the order id. true passes. A query passes when the order matches it, so a multi-tenant host's per-store admins can settle only their own store's orders. Anything else, including an empty query or one with an empty and or or list at any depth, is a 403. Payload's ecommerce plugin gives orders update: isAdmin by default.
  • settle.resend (default off) allows the resend outcome. A resend waits until the order has been unknown for settle.resendAfterMinutes (default 30, at least 10), so a late Printify create has time to show up. It then pages through the shop's Printify orders (50 a page, up to 100 pages) for one carrying this order id. If it finds one, it records that one and sends nothing. If the list can't be read, it sends nothing and the order stays unknown. Printify's docs don't say whether the list can be filtered by external_id, so it reads them all.
  • A Printify order with no external_id blocks resends. If the shop's order list holds an order carrying no order id (one made by hand in Printify, or by another tool), the plugin can't rule it out, so every resend answers 502 and sends nothing while that order is in the list. Find the order in Printify: if it is this one, settle it as sent with its Printify id.

How it behaves:

  • Only the plugin writes the fulfillment fields (see Fields only the plugin writes), so settling is the only way to change them.
  • The order must still be waiting to be settled when the change is written: the status is part of the write's condition (payload.db.updateOne with it in where). Of two staff settling at once, one wins and the other gets a 409. This relies on the database adapter doing that conditional update in one step, as MongoDB's does. Settling runs inside a transaction (see Database transactions). It is tested on a real MongoDB (in memory); the SQL adapters haven't been tested.
  • A Printify order id another order in the store already holds is refused.
  • resend goes through the same path as a paid order: the tenant check and beforePrintifyWrite still apply, and its outcome can be unknown again.
  • There's no button in the admin yet; the field's description points to the endpoint.

Testing

npm test runs every test without reaching Printify: Printify is always a fake fetch. Most tests use a small fake Payload. test/real-db.test.ts runs a real Payload with the official ecommerce and multi-tenant plugins on an in-memory MongoDB replica set (mongodb-memory-server, which downloads a MongoDB binary on first run), with and without transactions. It covers the paid-order hook, saves made while an order is being sent, database transactions and the send ledger, the refusals without transactions, settling, webhooks, two stores on one Payload, the plugin-only fields kept through REST and Local API writes, version restores and duplicates, and orders refused when a variant's link doesn't match its product. Nothing has been tested against Printify itself or on Postgres or SQLite.

Notes

  • Prices are Printify's retail prices in cents, as Payload ecommerce stores them (priceInUSD). The product's own price is the lowest published variant price ("from" price).
  • Printify updates a product's variants as a whole list; a price push sends every variant with one price changed. A shop's channel (e.g. the Pop-Up Store) may need the product republished in Printify to show the new price there.
  • Mockups are linked from Printify's CDN, not copied into uploads.
  • Shipping cost for a cart: new PrintifyClient(token).shippingCost(shopId, { line_items, address_to }).
  • API limits: 600 requests/minute. The client retries 429 with backoff, and server errors only for reads. Creating an order is never retried.

About

Printify for Payload: print-on-demand for Payload’s ecommerce plugin, with product sync, order fulfillment and tracking, and optional price write-back.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages