# OnCharge Payments for Magento 2 / Adobe Commerce

Module `OnCharge_Payments` (Composer package `oncharge/module-payments`).
Adds OnCharge as a payment method, keeps orders in step with OnCharge through
signed webhooks, reports shipment tracking (payouts are released once the
carrier confirms delivery), refunds online from credit memos, and serves the
compliance feed OnCharge reads for the research-use-only (RUO) review.

Requires Magento Open Source / Adobe Commerce 2.4.4 or later and PHP 8.1+.

## Install

The easiest way: in the OnCharge portal open **Integrations > Magento** and
download the module. The ZIP is a Composer artifact (`composer.json` at its
root), so Composer installs it from a folder:

```bash
mkdir -p artifacts && mv ~/Downloads/oncharge-magento-1.1.0.zip artifacts/
composer config repositories.oncharge artifact ./artifacts
composer require oncharge/module-payments:1.1.0
```

The portal also offers a ZIP laid out for `app/code/OnCharge/Payments` (unzip
it in the Magento root) for stores that do not use Composer.

Or from a path or VCS repository (this directory contains `composer.json`):

```bash
# path repository, e.g. a checkout of this repo next to the store
composer config repositories.oncharge path /path/to/oncharge/packages/magento-plugin
# or a VCS repository: composer config repositories.oncharge vcs <git url>
composer require oncharge/module-payments:^1.0

bin/magento module:enable OnCharge_Payments
bin/magento setup:upgrade
bin/magento setup:di:compile          # production mode only
bin/magento setup:static-content:deploy -f   # production mode only
bin/magento cache:flush
```

`setup:upgrade` creates three tables: `oncharge_payment_session`,
`oncharge_webhook_event` and `oncharge_shipment_report`. Magento's cron must
run (it resends tracking numbers OnCharge has not accepted yet, and sends the
daily heartbeat).

## Connection status in the OnCharge portal

The module sends a signed heartbeat to `POST /api/v1/integrations/heartbeat`
once a day (cron `oncharge_heartbeat`) and whenever the payment settings are
saved: its version, the Magento version and edition, the store's host and
whether payments and the compliance feed are on. The portal's Integrations
page then shows the store as connected, with the module version. Every signed
request also carries `User-Agent: OnCharge-Magento/<version>`. A failed
heartbeat is logged and never affects checkout.

## Configure

**Stores > Configuration > Sales > Payment Methods > OnCharge**

| Setting | |
|---|---|
| Enabled, Title, Description | What shoppers see at checkout. |
| API Key / API Secret | From the OnCharge dashboard. The secret is stored encrypted and never reaches the browser. |
| Environment | Production (`https://app.oncharge.io`), or a custom base URL only when OnCharge support asks. |
| Payment Action | **Sale**: the order is invoiced when OnCharge confirms the payment. **Authorize**: the payment is recorded and you create the invoice (Capture Online, which checks with OnCharge that the payment was captured). |
| Checkout Display | **Redirect** to the OnCharge checkout page, or **Embedded** on a payment page in your store using `https://app.oncharge.io/js/v1/oncharge.js`. |
| Callback Signing Secret | Register `https://<your store>/oncharge/webhook` as the callback URL in the OnCharge dashboard and paste the `oc_cbsec_…` secret it shows once. |
| Countries, min/max order total, sort order, debug logging | Standard payment method options. |

Add your store's domain to your OnCharge store settings; OnCharge only accepts
return URLs on registered domains.

### Compliance review (RUO stores)

Same page, **Compliance Review** group:

1. In the OnCharge dashboard add your store host. Paste the one-time
   **Connection Code** (`occs_…`) here and save. Only the connection id and a
   key derived from the code are kept (encrypted); enter `disconnect` to remove
   it. Then select **Verify connection** in the dashboard and set the base path
   to `/oncharge/compliance`.
2. **Connected Host**: leave empty unless the host you added in OnCharge
   differs from this store's base URL host.
3. Policy pages are detected from CMS page identifiers (`terms`,
   `privacy-policy-cookie-restriction-mode`, `refund-policy`, `returns`,
   `shipping`, `contact-us`, …) and Magento's contact form. Set a CMS
   identifier, path or URL to override any of them.
4. **Document Attributes**: product attribute codes holding links to
   documents such as certificates of analysis. PDF links in descriptions are
   picked up automatically.
5. **Reviewer access**: create a separate customer account for payment and
   card-network reviewers with the same access a verified buyer has, enter its
   email, sign in as it once to check it shows every product with its price, then
   set **I Signed In as This Account** to Yes. Changing the email clears the
   confirmation. If a catalogue-access extension decides what the account can
   see, it can answer through the `oncharge_compliance_reviewer_can_view_catalog`
   event (`transport` DataObject, key `can_view`).

Endpoints, served from the store's own host:

```
GET /oncharge/compliance/proof?challenge=<hex64>&ts=<unix>
GET /oncharge/compliance/content?cursor=<n>&limit=<n>      (signed)
GET /oncharge/compliance/reviewer-access                    (signed)
```

The feed serves active CMS pages first, then every enabled product with its
own page in the store view, including products set to "Catalog" visibility
(hidden from search), up to 5,000 items. Signatures follow
`docs/integrations/compliance-feed-protocol.md`; request nonces are kept in the
Magento cache for 10 minutes to refuse replays.

## How it maps to the OnCharge API

| Magento | OnCharge |
|---|---|
| Customer places the order | Order is created **Pending Payment**, no email yet (`initialize` command). |
| Browser goes to `/oncharge/checkout/start` | `POST /api/v1/checkout/sessions` with amount (minor units), currency, `reference` and `order_id` (increment id), `return_url`, customer email/phone, typed `shipping` object, `line_items` and string metadata; `Idempotency-Key: magento-<increment>-<protect code>`. Then redirect to `https://app.oncharge.io` + `iframe_url`, or the embedded page. The order already carries its id and shipping address, so `POST …/sessions/{id}/order` is not needed. |
| Return URL `/oncharge/checkout/return` | `GET /api/v1/checkout/sessions/{id}` only to choose the page (success, or cart restored). It never changes the order. |
| Webhook `/oncharge/webhook` | v2 `OnCharge-Signature: t=…,v1=HMAC(secret, "t.body")` (±300 s); legacy `X-Oncharge-Signature` body HMAC when no v2 header is present. Deduplicated on the event id. `payment.captured` invoices (Sale) or records the authorisation (Authorize) after checking amount and currency; `payment.refused` / `payment.cancelled` cancel the pending order; `refund.succeeded` confirms refunds and records a refund made in the OnCharge dashboard as an offline credit memo; `chargeback.opened` holds the order; `delivery.confirmed` adds an order comment. |
| Shipment tracking saved (admin, API or extension) | `POST /api/v1/shipments` with `session_id`, `order_id` and `{carrier, tracking_number}`; carrier codes/titles map to USPS, UPS, FedEx or DHL Express, otherwise the number is sent without a carrier. The verdict is added as an order comment; pending tracks are resent by cron every 15 minutes. |
| Online credit memo | `POST /api/v1/refunds` with `session_id`, amount in order-currency minor units, currency and an Idempotency-Key. |

## Tests

No Magento installation is needed for the library tests:

```bash
php tests/run.php        # request signing, webhook verification, compliance
                         # protocol test vectors, paging, carriers, amounts, session body
find src tests -name '*.php' -o -name '*.phtml' | xargs -n1 php -l
```

The vectors are the ones computed by the OnCharge server code and the
WooCommerce compliance scanner plugin (which the test also loads directly).

Not verified without a running Magento store: dependency injection wiring,
the checkout renderer, the admin configuration screens, order state
transitions, credit memo creation, CSP headers and the embedded checkout
script.
