Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,30 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.0.3] - 2026-09-21

### Added

- `checkoutEvents()->update()` documents the optional `payment` field on
`order_placed`/`order_declined` events (settled payment method, with a
nested `card` sub-object) — it was already forwarded as pass-through data,
this only documents the shape.
- `carts()->create()` and `carts()->update()` accept an optional `variant_id`
on each item.
- `sessions()->create()` and `sessions()->update()` document the optional
`verification` field (identity/contact verification already performed by
the caller) — pass-through data, this only documents the shape.

### Changed

- **BREAKING:** `treatments()->sync()` gains `$payment` and `$verification`
optional array parameters, and `$userAgent` moves earlier in the signature
and becomes a required, non-empty argument (the API now requires the
`User-Agent` header on this endpoint). Old signature:
`sync(string $session, array $orderIds, ?string $utmSource = null, ?string $userAgent = null)`.
New signature:
`sync(string $session, array $orderIds, string $userAgent, ?string $utmSource = null, ?array $payment = null, ?array $verification = null)`.

## [0.0.2] - 2026-09-08

### Added
Expand Down
9 changes: 6 additions & 3 deletions docs/INTEGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ $treatment = $client->treatments()->create([
])->data();
```

> **Alternative when the order originates in an external CRM:** if your CRM is the source of truth for the order record and you only need AsterMD to be aware of it, call `$client->treatments()->sync($session, ['28618'])` instead of `treatments()->create(...)`.
> **Alternative when the order originates in an external CRM:** if your CRM is the source of truth for the order record and you only need AsterMD to be aware of it, call `$client->treatments()->sync($session, ['28618'], $_SERVER['HTTP_USER_AGENT'])` instead of `treatments()->create(...)`.

### Step 12 — Resume from any step

Expand Down Expand Up @@ -532,9 +532,12 @@ Uploaded bytes are **PHI**. The SDK never writes them to a debug log, even with
| `create(array $data): Response` | POST | `/v1/sales/treatments/create` |
| `view(string $id): Response` | GET | `/v1/sales/treatments/view/{id}` |
| `list(array $query = []): Response` | GET | `/v1/sales/treatments/list` |
| `sync(string $session, array $orderIds, ?string $utmSource = null, ?string $userAgent = null): Response` | POST | `/v1/sales/treatments/sync` |
| `sync(string $session, array $orderIds, string $userAgent, ?string $utmSource = null, ?array $payment = null, ?array $verification = null): Response` | POST | `/v1/sales/treatments/sync` |

Use `sync()` to push an order settled in an external CRM into AsterMD after settlement happens outside the SDK.
`$userAgent` is required by the API. `$payment` and `$verification` are optional and
carry the settled payment method and any identity/contact verification already
performed by the caller.

### `doctorsNetworks()`

Expand Down Expand Up @@ -1148,4 +1151,4 @@ block ends with `# Transport error: <message>` in place of the response section.
- **`AuthenticationException` after one auto-retry is final.** The SDK does not loop; treat it as a configuration error.
- **PHP empty arrays encode as JSON `[]`, not `{}`.** If an endpoint requires a JSON object and you have no fields, pass `(object) []` (a stdClass instance) so PHP encodes it as `{}`. The SDK already handles the known case: `sessions()->create()` coerces empty `data` to `{}` internally. (`intakeSubmissions()->create()` / `->update()` take a list of field objects, so their empty `data` is correctly sent as `[]`.) If you hit a `validation.isObject` 400 on any other endpoint, that's the cause — wrap the empty field with `(object) []`.
- **`sessions()->view()` takes an array of IDs.** `view(['uuid'])` for a single lookup, `view(['a','b'])` to batch-fetch; pass an IANA tz as the 2nd arg (`view(['uuid'], 'Asia/Kolkata')`) to format response timestamps. The real route is `/sessions/view?session_ids=…` (comma-joined).
- **Forward the visitor's `User-Agent` and IP yourself.** The SDK runs server-to-server, so it cannot see the visitor's browser or IP. For device/geo attribution, pass `$_SERVER['HTTP_USER_AGENT']` and `$_SERVER['REMOTE_ADDR']` to `sessions()->create(userAgent: …, clientIp: …)` — the SDK sends them as the `User-Agent` and `X-Original-Client-Ip` headers. (`treatments()->sync()` likewise accepts `userAgent`.) Otherwise the server attributes the call to the PHP client's UA/IP. Each header is omitted when its arg is null/empty.
- **Forward the visitor's `User-Agent` and IP yourself.** The SDK runs server-to-server, so it cannot see the visitor's browser or IP. For device/geo attribution, pass `$_SERVER['HTTP_USER_AGENT']` and `$_SERVER['REMOTE_ADDR']` to `sessions()->create(userAgent: …, clientIp: …)` — the SDK sends them as the `User-Agent` and `X-Original-Client-Ip` headers. Each header is omitted when its arg is null/empty. `treatments()->sync()` also takes a `$userAgent`, but there it's a required argument — the API rejects the call without it.
21 changes: 12 additions & 9 deletions src/Resource/Carts.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
* The journey event (`cart_initiated` / `cart_update`) is derived server-side and
* the `channel_id` comes from the API credential, so callers pass neither.
*
* Cart items use the keys `product_id`, `name`, and `qty` (all required). The SDK
* forwards the item list unmodified, so any additional caller-supplied keys reach
* the wire unchanged.
* Cart items use the keys `product_id`, `name`, and `qty` (all required), plus an
* optional `variant_id`. The SDK forwards the item list unmodified, so any
* additional caller-supplied keys reach the wire unchanged.
*
* @phpstan-type CartItem array{product_id: string, name: string, qty: int}
* @phpstan-type CartItem array{product_id: string, variant_id?: string, name: string, qty: int}
*/
final class Carts extends AbstractResource
{
Expand All @@ -28,12 +28,14 @@ final class Carts extends AbstractResource
*
* Call this when the prospect first adds items to their cart. Each item in
* `$items` must contain `product_id` (ID string), `name`, and
* `qty` (integer). The server derives the `cart_initiated` journey event and
* resolves the channel from the API credential, so neither is sent. Inspect
* `$response->data()` for the created cart record.
* `qty` (integer), and may optionally include `variant_id` (ID string) when
* the product has variants. The server derives the `cart_initiated` journey
* event and resolves the channel from the API credential, so neither is sent.
* Inspect `$response->data()` for the created cart record.
*
* @param string $session the session UUID to associate the cart with
* @param list<CartItem> $items list of items to add; each item requires `product_id`, `name`, and `qty`
* @param list<CartItem> $items list of items to add; each item requires `product_id`, `name`, and `qty`,
* plus an optional `variant_id`
*
* @return Response the created cart envelope; `data()` contains the new cart record (with `status` and `items`)
*
Expand Down Expand Up @@ -63,7 +65,8 @@ public function create(string $session, array $items): Response
* changed items. The `cart_update` journey event is derived server-side.
*
* @param string $session the UUID of the session whose cart to update
* @param list<CartItem> $items the replacement item list; each item requires `product_id`, `name`, and `qty`
* @param list<CartItem> $items the replacement item list; each item requires `product_id`, `name`, and `qty`,
* plus an optional `variant_id`
*
* @return Response the updated cart envelope
*
Expand Down
8 changes: 7 additions & 1 deletion src/Resource/CheckoutEvents.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,13 @@ public function create(string $session, array $data = []): Response
* `payment_method` (string — `apple_pay`|`google_pay`|`card`|`paypal`),
* `currency` (string ISO 4217 — order events),
* `provider_order_id` (list<string> — payment provider order ids),
* `opportunity_id` (string — optional CRM opportunity id). Full schema in the
* `opportunity_id` (string — optional CRM opportunity id),
* `payment` (array, optional — order events; the settled payment method.
* Shape: `type` (`paypal`|`apple_pay`|`gpay`|`credit_card`|`pre_paid`),
* `pre_auth` (bool), `pre_auth_qa` (bool, optional),
* `pre_auth_amount` (number, optional), `card` (array, optional — `type`
* one of `amex`|`visa`|`mastercard`|`discover`|`diners_club`|`jcb`, `bin`
* optional, `exp` required)). Full schema in the
* API reference under `/checkout-events/update/{session_id}`.
*
* @return Response the updated checkout-event envelope
Expand Down
17 changes: 12 additions & 5 deletions src/Resource/Sessions.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,12 @@ final class Sessions extends AbstractResource
* All `$data` fields are optional. Known keys (per the sales API
* `SessionCreateRequest`): `channel_id` (string — normally derived from the API
* credential, so rarely needed), `referrer` (string), `utm`
* (`{source, medium, campaign}`), and `custom_params` (arbitrary object). The
* server also enriches the stored record with `ip`, `geo`, and browser/device
* (`{source, medium, campaign}`), `custom_params` (arbitrary object), and
* `verification` (array, optional — identity/contact verification already
* performed by the caller; every field inside it is optional too. Shape:
* `email` (bool), `address` (bool), `id` (array, optional — `verified` (bool),
* `method` (`ssn`|`dob`|`cross_check`|`document_upload`), `value` (string)).
* The server also enriches the stored record with `ip`, `geo`, and browser/device
* fields derived from the request; the response `data()` returns that enriched
* read-model. Any additional keys you pass are forwarded unmodified.
*
Expand Down Expand Up @@ -114,11 +118,14 @@ public function view(array $sessions, ?string $tz = null): Response
*
* Sends a `PUT` request with `$data` as the JSON body. Use this to attach
* additional context to a session after creation (e.g. UTM parameters resolved
* client-side). Pass only the fields you want to change; the server performs a
* merge rather than a full replacement.
* client-side, or verification results captured later in the flow). Pass only
* the fields you want to change; the server performs a merge rather than a full
* replacement. `$data` accepts the same optional `verification` key documented
* on {@see self::create()}.
*
* @param string $session the UUID of the session to update
* @param array<string, mixed> $data fields to update on the session record; empty array sends `{}`
* @param array<string, mixed> $data fields to update on the session record; empty array sends `{}`.
* Includes the optional `verification` key documented on {@see self::create()}
*
* @return Response the updated session envelope
*
Expand Down
71 changes: 54 additions & 17 deletions src/Resource/Treatments.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace AsterMD\Sdk\Resource;

use AsterMD\Sdk\Response;
use InvalidArgumentException;

/**
* Treatment (order) operations on the `sales` service.
Expand Down Expand Up @@ -107,27 +108,59 @@ public function list(array $query = []): Response
* issued by the payment aggregator. Inspect `$response->data()` for the created
* treatment records.
*
* Pass `$userAgent` to attribute the import to the visitor's browser: it is
* forwarded verbatim as the `User-Agent` request header. Because the SDK runs
* `$userAgent` attributes the import to the visitor's browser: it is forwarded
* verbatim as the required `User-Agent` request header. Because the SDK runs
* server-to-server, only the consuming application knows the real value — read
* it from `$_SERVER['HTTP_USER_AGENT']` and pass it here. When `null` or empty,
* no `User-Agent` header is added and the HTTP client's default applies.
*
* @param string $session the session UUID to associate with the imported orders
* @param list<string> $orderIds list of external CRM order identifiers to import
* @param string|null $utmSource optional marketing attribution source (e.g. `google`, `facebook`);
* sent as `utm_source` only when provided
* @param string|null $userAgent the visitor's browser User-Agent to forward as the `User-Agent`
* header (e.g. `$_SERVER['HTTP_USER_AGENT']`); `null` or empty omits it
* it from `$_SERVER['HTTP_USER_AGENT']` and pass it here.
*
* `$payment`, when supplied, carries the settled payment method for the order.
* `card`, when present, additionally requires `type` (one of `amex`, `visa`,
* `mastercard`, `discover`, `diners_club`, `jcb`) and `exp`, with `bin` optional.
*
* `$verification`, when supplied, records identity/contact verification already
* performed by the caller. `id`, when present, additionally requires `verified`
* and `method` (one of `ssn`, `dob`, `cross_check`, `document_upload`), plus the
* verified `value`.
*
* @param string $session the session UUID to associate with the imported orders
* @param list<string> $orderIds list of external CRM order identifiers to import
* @param string $userAgent the visitor's browser User-Agent to forward as the required
* `User-Agent` header (e.g. `$_SERVER['HTTP_USER_AGENT']`)
* @param string|null $utmSource optional marketing attribution source (e.g. `google`, `facebook`);
* sent as `utm_source` only when provided
* @param array{
* type: string,
* pre_auth: bool,
* pre_auth_qa?: bool,
* pre_auth_amount?: int|float,
* card?: array<string, mixed>
* }|null $payment the settled payment method; `type` is one of `paypal`, `apple_pay`,
* `gpay`, `credit_card`, `pre_paid`
* @param array{
* email: bool,
* address: bool,
* id?: array<string, mixed>
* }|null $verification identity/contact verification already performed by the caller
*
* @return Response the sync result envelope; `data()` contains the created treatment records
*
* @throws \InvalidArgumentException if `$userAgent` is empty
* @throws \AsterMD\Sdk\Exception\ValidationException if `$orderIds` is empty or malformed
* @throws \AsterMD\Sdk\Exception\ApiException on a non-2xx response from the server
* @throws \AsterMD\Sdk\Exception\TransportException on a network-level failure
*/
public function sync(string $session, array $orderIds, ?string $utmSource = null, ?string $userAgent = null): Response
{
public function sync(
string $session,
array $orderIds,
string $userAgent,
?string $utmSource = null,
?array $payment = null,
?array $verification = null,
): Response {
if ($userAgent === '') {
throw new InvalidArgumentException('treatments/sync requires a non-empty User-Agent.');
}

$body = [
'session_id' => $session,
'order_ids' => $orderIds,
Expand All @@ -137,10 +170,14 @@ public function sync(string $session, array $orderIds, ?string $utmSource = null
$body['utm_source'] = $utmSource;
}

$headers = ($userAgent !== null && $userAgent !== '')
? ['User-Agent' => $userAgent]
: [];
if ($payment !== null) {
$body['payment'] = $payment;
}

if ($verification !== null) {
$body['verification'] = $verification;
}

return $this->transport->send('sales', 'POST', '/treatments/sync', body: $body, headers: $headers);
return $this->transport->send('sales', 'POST', '/treatments/sync', body: $body, headers: ['User-Agent' => $userAgent]);
}
}
14 changes: 14 additions & 0 deletions tests/Unit/Resource/CartsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ public function testCreateSendsSessionAndItems(): void
self::assertArrayNotHasKey('channel_id', $body);
}

public function testCreateForwardsOptionalVariantId(): void
{
$this->http->enqueue(200, '{"success":true,"message":"ok","data":{},"meta":{}}');

$this->resource->create('sess-uuid', [
['product_id' => 'p1', 'variant_id' => 'v1', 'name' => 'Semaglutide', 'qty' => 2],
]);

self::assertJsonStringEqualsJsonString(
'{"session":"sess-uuid","items":[{"product_id":"p1","variant_id":"v1","name":"Semaglutide","qty":2}]}',
(string) $this->http->lastRequest()->getBody(),
);
}

public function testUpdatePutsBySessionWithItemsOnly(): void
{
$this->http->enqueue(200, '{"success":true,"message":"ok","data":{},"meta":{}}');
Expand Down
23 changes: 23 additions & 0 deletions tests/Unit/Resource/CheckoutEventsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,27 @@ public function testUpdateOrderPlacedSendsEventAndOrderFields(): void
(string) $this->http->lastRequest()->getBody(),
);
}

public function testUpdateOrderPlacedForwardsPaymentWhenProvided(): void
{
$this->http->enqueue(200, '{"success":true,"message":"ok","data":{},"meta":{}}');

$this->resource->update('sess-uuid', CheckoutEvent::OrderPlaced, [
'order_total' => 99.0,
'payment' => [
'type' => 'credit_card',
'pre_auth' => false,
'card' => [
'type' => 'visa',
'exp' => '12/29',
],
],
]);

self::assertJsonStringEqualsJsonString(
'{"event":"order_placed","order_total":99.0,"payment":'
. '{"type":"credit_card","pre_auth":false,"card":{"type":"visa","exp":"12/29"}}}',
(string) $this->http->lastRequest()->getBody(),
);
}
}
Loading
Loading