# OnCharge for Wix

Take card payments on a Wix site through the OnCharge hosted checkout, keep
Wix orders in step with OnCharge, report shipment tracking (OnCharge releases
the payout once the carrier confirms delivery), refund from the Wix
dashboard, and serve the compliance feed OnCharge reads for the
research-use-only (RUO) review.

## How it plugs into Wix

Wix lets a site owner add their own payment provider with the **Velo Payment
Provider service plugin** (formerly "SPI" / "custom extension"). Wix calls three
functions in the site's backend:

| Wix calls | When | This integration |
|---|---|---|
| `connectAccount()` | The owner clicks **Connect** under Accept Payments | Checks the OnCharge API key and secret with a signed request and returns the account. |
| `createTransaction()` | A buyer places an order | `POST /api/v1/checkout/sessions`, then returns `{pluginTransactionId: <session id>, redirectUrl: <OnCharge hosted checkout>}` so Wix sends the buyer to OnCharge. |
| `refundTransaction()` | The owner refunds from the Orders page | `POST /api/v1/refunds` and returns `{pluginRefundId}`. |

Payment results reach Wix through an HTTP function that verifies the OnCharge
webhook and calls `submitEvent()` from `wix-payment-provider-backend`.

The service plugin works only on the owner's own site (Wix does not allow it
in the App Market) and needs a Wix premium plan that accepts payments. Use a
connected custom domain: OnCharge accepts return URLs and webhooks only on
the domains registered for the store.

## Connection status in the OnCharge portal

The integration sends a signed heartbeat to `POST /api/v1/integrations/heartbeat`
once a day (the `sendOnChargeHeartbeat` job in `jobs.config`) and when the
owner connects OnCharge under Accept Payments: its version, the site's domain
and what is switched on. The portal's Integrations page then shows the site as
connected. The portal's **Integrations > Wix** page walks through this setup
and downloads these files as one ZIP.

## Files

Copy `src/backend/` into the site's **Backend** (Wix Studio / editor with Dev
Mode on, or the Wix IDE / CLI):

```
backend/
  http-functions.js                       webhook, return URL and compliance feed
  events.js                               wixEcom_onFulfillmentsUpdated → shipments
  jobs.config                             hourly retry of pending tracking numbers, daily heartbeat
  oncharge/
    config.js                             your site's settings (edit this)
    handlers.js                           all request handling (tested with Node)
    signing.js webhooks.js compliance.js  pure modules (tested with Node)
    version.js                            this integration's version
    catalog.js checkout.js carriers.js api.js
    wix/deps.js                           Wix APIs: Secrets Manager, CMS, eCom, Members, Stores
    wix/catalog-v3.js                     Wix Stores Catalog V3 product reads
    wix/jobs.js                           the scheduled job
  service-plugins/payment-provider/oncharge/
    oncharge.js                           connectAccount, createTransaction, refundTransaction
    oncharge-config.js                    getConfig: title, hosted page, credentials fields
```

If the site already has `backend/http-functions.js` or `backend/events.js`,
add the exports from these files to the existing ones.

## Set up in the Wix editor

1. **Turn on Dev Mode** (Wix Editor: Dev Mode > Turn on Dev Mode; Wix Studio:
   Code panel is on by default).
2. **Add the payment plugin.** Code sidebar > **Public & Backend** > hover
   **Service Plugins** > **+** > **Payment**. Name it `oncharge` and select
   **Add & Edit Code**. Wix creates
   `backend/service-plugins/payment-provider/oncharge/oncharge.js` and
   `oncharge-config.js`; replace their contents with the files from this
   package.
3. **Add the backend files.** Under **Backend**, create the `oncharge` folder
   (and `oncharge/wix`) with the files above, plus `http-functions.js`,
   `events.js` and `jobs.config` at the Backend root.
4. **Install packages** (Packages & Apps > npm, or the Wix IDE): `@wix/stores`
   and `@wix/essentials`. They are needed on Wix Stores Catalog V3 sites; install
   them anyway so the backend builds the same on every site.
5. **Create the CMS collection** `OnChargeLog` (CMS > Create Collection), with
   permissions **Admin only** for read, create, update and delete. Fields:
   `kind` (Text) and `data` (Object); Wix adds others as needed. It holds
   OnCharge session ids per Wix transaction, handled webhook ids, compliance
   request nonces and tracking numbers waiting to be resent. No card data or
   secrets are stored.
6. **Save the secrets** in **Developer Tools > Secrets Manager**:
   | Name | Value |
   |---|---|
   | `oncharge_api_key` | OnCharge API key |
   | `oncharge_api_secret` | OnCharge API secret |
   | `oncharge_webhook_secret` | the callback signing secret (`oc_cbsec_…`), see step 9 |
   | `oncharge_compliance_code` | the compliance connection code (`occs_…`), RUO stores only |
7. **Edit `backend/oncharge/config.js`**: set `storeHost` to the site's domain
   (e.g. `www.example.com`), the policy page paths, and the reviewer settings
   (step 11).
8. **Publish the site.** Service plugins, HTTP functions and backend events
   run only on the published site, not in preview.
9. **In the OnCharge dashboard**: add the site's domain to the store, and
   register the callback URL `https://<domain>/_functions/onchargeWebhook`.
   Save the signing secret it shows once as `oncharge_webhook_secret`, then
   publish again.
10. **Connect OnCharge in Wix**: Dashboard > Settings > **Accept Payments** >
    **See More Payment Options** > OnCharge > **Connect**, enter the same API
    key as `oncharge_api_key`, and select **Connect**. OnCharge then appears at
    checkout as "Credit / Debit Card".
11. **Compliance review (RUO stores)**: in the OnCharge dashboard add the host
    and copy the connection code into `oncharge_compliance_code`. Set the feed
    base path to **`/_functions/onchargeCompliance`**, then select **Verify
    connection**. For reviewer access, create a separate site member for
    payment and card-network reviewers with the same access a verified buyer
    has; put its login email in `reviewer.email`, sign in as it once to check
    it shows every product with its price, then put the same email in
    `reviewer.confirmedEmail` and publish.

## Endpoints

Wix names an HTTP function after its exported function (`get_<name>`,
`post_<name>`), and a JavaScript name cannot contain a hyphen, so the paths
are camel case. Sub-paths arrive in `request.path`.

| URL | Purpose |
|---|---|
| `POST https://<domain>/_functions/onchargeWebhook` | OnCharge webhooks (callback URL) |
| `GET https://<domain>/_functions/onchargeReturn?state=…&sig=…` | Return URL of each checkout session |
| `GET https://<domain>/_functions/onchargeCompliance/proof?challenge=…&ts=…` | Compliance: host ownership proof |
| `GET https://<domain>/_functions/onchargeCompliance/content?cursor=…&limit=…` | Compliance: catalogue (signed) |
| `GET https://<domain>/_functions/onchargeCompliance/reviewer-access` | Compliance: reviewer login status (signed) |

## How each flow maps to the OnCharge API

- **Checkout.** `createTransaction()` sends `POST /api/v1/checkout/sessions`
  with `amount` (Wix `totalAmount`, already in minor units), `currency`,
  `reference` = the Wix transaction id, `return_url`, `customer_email` /
  `customer_phone`, the typed `shipping` object from the Wix shipping address
  (omitted when every item is digital), `line_items` and string metadata
  (Wix transaction and payment order ids), with
  `Idempotency-Key: wix-<transaction id>`. The buyer is redirected to
  `https://app.oncharge.io` + `iframe_url`. The Wix order stays pending until
  OnCharge's webhook confirms the payment.
- **Return URL.** OnCharge only accepts return URLs on the store's own
  domain, so the session's `return_url` is this site's `onchargeReturn`
  function. It carries Wix's success / pending / error / cancel URLs, signed
  with a key derived from the API secret (it cannot redirect elsewhere), reads
  the session status with `GET /api/v1/checkout/sessions/{id}` and redirects
  to the matching Wix page.
- **Webhooks.** `OnCharge-Signature: t=…,v1=HMAC(secret, "t.body")` within
  300 s, or the legacy `X-Oncharge-Signature` body HMAC when no v2 header is
  present; deduplicated on the event id (`OnChargeLog`). `payment.captured`
  approves the Wix transaction (after checking amount and currency against
  what was sent), `payment.pending` → reason 5009, `payment.refused` → 3000,
  `payment.cancelled` → 3030 (3035 when expired). `refund.succeeded`,
  `chargeback.*` and `delivery.confirmed` are logged: Wix records refunds from
  `refundTransaction()`'s answer, and the refund event carries no refund id to
  match, so refunds issued in the OnCharge dashboard are not mirrored into Wix.
- **Shipments.** `wixEcom_onFulfillmentsUpdated` finds the OnCharge session
  that paid the order (its `providerTransactionId` in Order Transactions),
  names the order once with `POST /api/v1/checkout/sessions/{id}/order`
  (`order_id` = Wix order number), then sends every tracking number to
  `POST /api/v1/shipments`. Wix shipping providers map to USPS, UPS, FedEx or
  DHL Express; others are sent without a carrier. Numbers OnCharge cannot
  judge yet (payment not recorded, OnCharge unreachable) are kept and resent
  hourly by the `jobs.config` job, up to 12 times.
- **Refunds.** `refundTransaction()` reads the session currency, then sends
  `POST /api/v1/refunds` with the Wix `refundAmount` (minor units) and
  `Idempotency-Key: wix-refund-<Wix refund id>`.
- **Compliance feed.** Implements `docs/integrations/compliance-feed-protocol.md`:
  the home page and the pages in `config.pages` (read from the published
  site), then Wix Stores products (Catalog V1 `Stores/Products`, or Catalog V3
  Products API; visible products, plus hidden ones if `includeHiddenProducts`),
  up to 5,000 items. Product descriptions, info sections, prices, SKUs, image
  alt texts and PDF links (certificates of analysis) are included. Reviewer
  access reports whether the configured site member exists, is approved, and
  was confirmed by the owner.

## Tests

```bash
cd packages/wix-integration
node --test test/*.test.js     # or: pnpm --filter @oncharge/wix-integration test
```

The tests run the real handlers against a fake OnCharge and an in-memory
store: request signing against the server's signing string, v2 and legacy
webhook verification, the compliance protocol test vectors from the protocol
doc and the server's test suite, feed paging, the session body built from
Wix's documented `createTransaction()` example, the signed return state, the
Wix `submitEvent()` payloads, refunds and the fulfilment-to-shipments flow.

## Not verified without a live Wix site

Nothing here has run on Wix yet. In particular, untested:

- the service plugin being picked up, the Connect page, and the redirect to
  the OnCharge checkout and back through Wix's return URLs;
- `submitEvent()` moving the Wix order to paid / declined, and Wix accepting
  the reason codes used;
- `wix-secrets-backend.v2` `getSecretValue()` (the result is read as a
  string or `{value}`), `wix-auth` `elevate()`, `wix-data` with the
  `OnChargeLog` collection (including the duplicate-insert error used to
  detect repeats), and Node's `crypto` in Velo;
- Wix Stores product reads on both catalog versions, the Catalog V3
  `queryProducts` request shape and the dynamic import of
  `wix/catalog-v3.js`;
- fetching the site's own published pages from the backend (`wix-fetch`) and
  how much page text Wix's server-rendered HTML contains;
- `wixEcom_onFulfillmentsUpdated`, Order Transactions'
  `providerTransactionId` holding the OnCharge session id, `orders.getOrder()`
  for the order number, and the `jobs.config` schedule;
- `wix-members.v2` `queryMembers()` by login email and the member `status`
  values;
- HTTP function details: header names arriving in lower case, `request.path`
  for sub-paths, 302 redirects through `response()`, and the URL shape on
  free `wixsite.com` sites (use a connected domain).

## Wix documentation used

- Payment provider tutorial: https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-pay/tutorial-payment-provider-service-plugin
- `createTransaction()`: https://dev.wix.com/docs/velo/events-service-plugins/payments/service-plugins/wix-payments/payment-provider/create-transaction
- Amounts in minor units, field schema: https://dev.wix.com/docs/api-reference/business-management/payments/payment-service-provider-service-plugin/transactions/create-transaction
- `submitEvent()`: https://dev.wix.com/docs/velo/apis/wix-payment-provider-backend/submit-event
- Reason codes: https://dev.wix.com/docs/api-reference/business-management/payments/payment-service-provider-service-plugin/reason-codes
- Refunds (synchronous): https://dev.wix.com/docs/api-reference/business-management/payments/payment-service-provider-service-plugin/processing-refunds
- HTTP functions: https://dev.wix.com/docs/velo/velo-only-apis/wix-http-functions/get and https://dev.wix.com/docs/velo/velo-only-apis/wix-http-functions/wix-http-function-request/headers
- Secrets Manager (`getSecret()` deprecated 7 Sept 2025): https://dev.wix.com/docs/velo/apis/wix-secrets-backend-v2/secrets/get-secret-value
- Fulfilment event: https://dev.wix.com/docs/velo/events-service-plugins/e-commerce/events/on-fulfillments-updated
- Order Transactions: https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/orders/order-transactions/order-transactions-object
- Stores Catalog V1 collection: https://dev.wix.com/docs/velo/apis/wix-stores-v2/products-collection-fields
- Stores Catalog V3: https://dev.wix.com/docs/api-reference/business-solutions/stores/catalog-v3/products-v3/query-products and https://dev.wix.com/docs/api-reference/business-solutions/stores/catalog-versioning/get-catalog-version
- Members: https://dev.wix.com/docs/velo/apis/wix-members-v2/members/query-members
