# Charades Coin for Shopify This package includes a Shopify cart discount app and a separate native offsite payment app, both backed by Charades Coin payment APIs. Each merchant supplies their own Developers client ID and secret. Choose the discount app for customer-specific reward codes, or the [native payment app](payments/README.md) for a specifically approved Shopify payments registration. The implementation is ready for development-store integration testing. It has not been connected to a registered Shopify app, reviewed by Shopify, or tested against a live store. App registration, HTTPS hosting, merchant credentials and the store theme are external setup steps. ## Discounts and native payments | Capability | This implementation | | --- | --- | | Redeem Charades Coin for a fixed discount | Implemented through the GraphQL Admin discount API and a cart theme app block | | Pay the remaining balance | Shopify's existing checkout payment methods | | Cover the merchandise subtotal with Charades Coin | Possible when the discount equals the eligible subtotal; shipping and tax calculations still belong to Shopify | | Show Charades Coin as a payment method in checkout | Implemented in `payments/`; configure your approved payments app and payment method | | Native payment captures, voids and refunds | Implemented through the Payments Apps API and captured-payment refund contract; see `payments/README.md` | | Discount-code refunds | Merchant review; code cancellation and value use must be reconciled before returning Charades Coin | Shopify limits payment extensions to approved Payments Partners, with separate partner and app reviews. The native gateway should be a separate app registration: payments extensions cannot use general Shopify APIs, including the discount API used by this app. See [payments extensions](https://shopify.dev/docs/apps/build/payments), [approval](https://shopify.dev/docs/apps/build/payments/payments-extension-review), and [requirements](https://shopify.dev/docs/apps/build/payments/requirements). Before public distribution, Shopify must review the actual Charades Coin program, including any purchasable, transferable or withdrawable balances. This implementation does not establish that a particular stored-value program is eligible to operate as a loyalty discount app. ## Why capture happens before issuing a code The Charades Coin service places 30-minute holds. A Shopify discount code can remain usable independently of that hold. Issuing a code against a temporary hold and capturing later from an order webhook could grant a discount after the funds have been released. This app instead performs a durable exchange: 1. Save the customer, merchant, chosen reward, conversion rate result, request ID and a random code before contacting either provider. 2. Authorize using the existing `/api/relics/payment-authorizations` API. 3. Capture with a stable settlement reference, crediting the merchant treasury through the existing Charades Coin settlement flow. 4. Create a customer-specific Shopify discount with a usage limit of one, no expiry, and a minimum subtotal equal to its full value. 5. Reveal the code only after capture and code creation have both succeeded. Abandoned carts keep their code. No order webhook needs to capture or release customer funds. A code does not combine with other discounts and does not offer partial redemption or a remaining balance. The customer must explicitly choose to exchange Charades Coin; the widget explains when the debit occurs. ## Merchant credentials Create and manage merchant credentials in the [Developers portal](https://www.thecrimsonmarket.com/developers/apps/create). Use a separate client for each merchant business. For each merchant: 1. Create an application in the [Developers portal](https://www.thecrimsonmarket.com/developers/apps/create). 2. Allow the `profile` scope and authorization-code login with S256 PKCE. 3. Register `https://YOUR-APP-HOST/auth/tcm/callback` as an exact redirect URI. 4. Have a Charades Coin administrator enable the client, allowed currency keys, merchant treasury Transfer ID and withdrawal currency in the existing Charades Coin admin. Payment authorization requires an enabled `RelicDeveloperClient` mapping even if the client owns its currency branch. 5. Install the Shopify app, enter that merchant's client ID/secret and currency key, choose the number of Charades Coin per one shop currency unit, and set available reward amounts. For example, a rate of `100` with rewards `100, 500, 1000` in an AUD shop offers $1, $5 and $10 discounts. This is the merchant's retail discount rate. The branch's payout ratio and the merchant treasury's settlement currency are separate existing Charades Coin settings; merchants should align their economics deliberately. Optionally configure `TCM_LOGIN_CLIENT_ID` and `TCM_LOGIN_CLIENT_SECRET` for a shared customer login client registered with the same callback. Merchant payment captures still use each shop's own Developers credentials. New sign-ins use OAuthProvider; the Charades Coin API itself remains on its existing host. ## Run locally Requires Node.js 22+, MongoDB, and an HTTPS tunnel or public HTTPS host for Shopify callbacks and the app proxy. Keep the encryption key stable and back it up with the database recovery plan. ```powershell cd relics-shopify npm ci Copy-Item .env.example .env # Fill in .env, including a randomly generated SHOPIFY_ENCRYPTION_KEY. npm start ``` Run a second process with the same environment: ```powershell npm run worker ``` The worker is required: it issues discount codes, retries interrupted exchanges, and processes queued order and privacy webhooks. Multiple workers share database leases. Requests return a processing receipt quickly, so provider calls do not hold open a Shopify app proxy request. `SHOPIFY_MONGODB_URI` should point to a dedicated app database. This process never connects to the Charades Coin ledger database. Merchant credentials and Shopify access/refresh tokens are encrypted with AES-256-GCM and bound to their shop. Session tokens are stored as hashes and expire independently of MongoDB's TTL cleanup. The included Dockerfile can run either process. Build from this directory, supply environment variables at runtime, and override the worker command with `node worker.mjs`. `/health` checks the web process's database connection. Deploy the web and worker processes separately and monitor the worker's health and pending exchanges. ## Register and test in Shopify 1. Create an app in Shopify's Dev Dashboard and use a development store. Replace the client ID and example HTTPS host in `shopify.app.toml`; put the app credentials and same host in `.env`. 2. Use Shopify CLI to link this directory to the registration and release its app configuration and theme extension. The app must run with `embedded = false`; its merchant session uses top-level cookies. 3. Confirm the callback URI, `/apps/relics` proxy, declared scopes and `/webhooks` subscriptions were applied. Shopify CLI releases configuration/extensions; it does not host this Node application. 4. Install the app through Shopify, complete merchant setup, and add the **Charades Coin rewards** app block to the full cart page in an Online Store 2.0 theme that supports app blocks. This version does not insert into a theme's cart drawer automatically. 5. If the merchant customizes the app proxy path, enter that path in the app block settings. The backend accepts Shopify's signed `path_prefix`. 6. Test customer sign-in, account linking, insufficient balance, redemption, checkout, abandonment/reuse of a code, order creation, cancellation, refund review and uninstall. Confirm captured value and the merchant settlement lot in Charades Coin as well as the resulting Shopify discount. Scopes are `read_discounts`, `write_discounts`, `read_orders`, and `write_app_proxy`. Order scopes support usage and refund reconciliation; this app does not change orders or mark orders as paid. Obtain Shopify's required protected customer data access for customer-specific discounts and order/customer identifiers before production use. See [discount creation](https://shopify.dev/docs/api/admin-graphql/latest/mutations/discountCodeBasicCreate), [webhook scopes](https://shopify.dev/docs/api/admin-graphql/latest/enums/WebhookSubscriptionTopic), and [app proxy authentication](https://shopify.dev/docs/apps/build/online-store/app-proxies/authenticate-app-proxies). For independent businesses, plan for public distribution and Shopify App Store review. Custom distribution is restricted to one store or stores in the same Plus organization; it is not a general multi-business installation channel. See [distribution methods](https://shopify.dev/docs/apps/launch/distribution/select-distribution-method). ## Recovery and operational limits - The browser retains its request ID across reloads and retries. The database enforces one exchange per shop, customer and request ID; reuse with different terms is rejected. Charades Coin authorization/capture references and Shopify codes remain stable throughout recovery. - The worker looks up an existing code before attempting creation. A lost response after a Charades Coin capture or Shopify code creation is retried against the same operation. No automatic reversal or refund is attempted after an uncertain capture. - Disabling new rewards does not remove existing codes or stop recovery of already queued exchanges. Uninstall removes live shop credentials and sessions and prevents provider work until the shop is installed again. Financial exchange snapshots remain for recovery and accounting. - Supported shop currencies are AUD, USD, EUR, GBP, CAD, NZD, SGD, HKD, JPY and KRW. All discount arithmetic uses integer minor units. Rewards that cannot convert exactly are refused. The widget disables new exchanges in a different presentment currency. The worker checks the current shop currency before money movement; changing a shop's base currency requires reconciliation of existing codes. - Only the signed Shopify customer ID plus a short-lived Charades Coin account session can redeem or view codes. Account connection also requires a verifier kept in the initiating storefront tab, a browser-bound OAuth state cookie and PKCE. A forwarded connection URL cannot link the victim's wallet to another Shopify customer's account. Account sessions last one hour; customers can reconnect to recover their code history. - The app proxy body is not treated as signed identity. Customer account IDs, merchant credentials, discount values, exchange rates and currency are selected on the server. Merchant settings require a server session, CSRF token and matching Origin. - Each displayed offer carries a customer-bound signed quote. A new exchange is refused if the merchant changes its terms before submission; an existing exchange keeps its original terms on retry. Switching Shopify customer accounts clears the previous tab's spending session and pending request. - Repeated recovery failures appear in the merchant list as requiring review. A worker outage, merchant credential rotation, disabled Charades Coin mapping, changed currency or deleted Shopify code needs operator attention. Alert on old pending records, worker errors, refresh failures and review requests. Avoid proxy/request logging of bodies, OAuth codes and query tokens. ## Refunds and privacy operations before launch `orders/create` records code use. Cancellations and refunds create merchant review items and flag associated exchanges. They do not credit Charades Coin automatically. The service's reversal endpoint can only release an active authorization, while this app's codes are already captured. Establish an auditable merchant refund procedure before taking real customer value; do not use unrestricted top-ups as a substitute for settlement-aware refunds. All mandatory Shopify privacy webhook topics authenticate their raw bodies and enter a durable queue. Customer redaction revokes live sessions; shop redaction clears an uninstalled shop's live configuration. Accounting records and request identifiers remain pending review under the operator's retention policy. Data export, final deletion/anonymization, request completion tracking, and exceptions for retained financial records require an operator workflow before App Store submission. The queue is not a claim of completed privacy compliance. See [Shopify privacy requirements](https://shopify.dev/docs/apps/build/compliance/privacy-law-compliance). ## Native Charades Coin payments The included [native payment app](payments/README.md) provides hosted buyer confirmation, exact amount conversion, immediate sales, authorization-only payments, full captures, voids, partial/full refunds and asynchronous Shopify result callbacks. It runs separately with `npm run start:payments` and `npm run worker:payments` and requires the specific app's Shopify payment-provider approval and verified client-certificate TLS. The platform source includes a merchant-scoped, idempotent captured-payment refund API that adjusts available settlement lots. Deploy that platform change before enabling native refunds. Allocated/paid-out settlements and held or insufficient treasury funds require merchant review. The native gateway uses Shopify's payment lifecycle and does not create a discount or mark an order paid through the Admin API. ## Validation ```powershell npm test ``` Tests start an isolated local MongoDB on a free loopback port; they never read a deployment database URI or call real payment APIs. On Windows the default executable is `C:/Program Files/MongoDB/Server/8.0/bin/mongod.exe`; set `TEST_MONGOD_PATH` on other installations (otherwise `mongod` on non-Windows). Coverage includes signatures, OAuth state/PKCE handoff, cross-customer rejection, secret handling, exact currency arithmetic, concurrent request deduplication, capture-before-code ordering, interrupted capture and code creation recovery, session expiry, uninstall/reinstall ordering, signed webhook replay, manual review queues, currency changes, and customer voucher pagination. Provider contracts are tested with simulated HTTP responses. A Shopify development-store run is still required to validate the registered extension, approved scopes and real checkout behavior.