# @shoploop/sdk

Ambassador and Ripple attribution and server-side sales/refund receipts for Shoploop. Flat-fee briefs without milestone bonuses need no SDK. It also verifies access you gift to creators (optional). This package does not provide perks, invitation bonuses or Wandamark analytics.

Until an npm registry release is published, install the package served by your Shoploop deployment:

```sh
npm install https://shoploop.dev/sdk/shoploop-sdk-0.4.0.tgz
```

For a local checkout, use `npm install /path/to/dillio/packages/shoploop-sdk`. The public download becomes available when the matching application is deployed; do not assume `npm install @shoploop/sdk` is available on the registry.

## Browser: capture the creator code

```js
import { captureReferral, clearReferral } from '@shoploop/sdk/browser';
const referralCode = captureReferral();
// Include referralCode in your own authenticated signup request.
// After your backend confirms attribution, call clearReferral().
```

Call on the landing page, after any required storage consent. First valid `shoploop_ref=slr_…` wins for 30 days in that browser. The expiration is not extended by another visit. If storage is blocked, only the current URL can supply the code. On shared devices, clear after binding and on consent withdrawal. No browser network calls, cookies, page capture or automatic revenue events are made. Cross-device and blocked-storage attribution require your own signup flow. Plain ESM browsers can import `https://shoploop.dev/sdk/browser.js` without a package manager.

## Server: bind once at signup

Create a dedicated `sl_amb_…` key under your app → Ambassador SDK, server keys & tracked revenue. Keep it out of client bundles. Keys are scoped to one app; old `sl_live_…` perk keys and Wandamark keys are not accepted.

```js
import { Shoploop } from '@shoploop/sdk';
const shoploop = new Shoploop({ key: process.env.SHOPLOOP_SERVER_KEY });
await shoploop.attribute({ customerId: user.id, referralCode, email: user.email }); // email is optional
```

Derive `customerId` from the authenticated new account on your server. Do not let browsers choose another customer's ID, a sale amount or a paid status. Only attribute a genuinely new signup; store the binding in your own database/outbox. The first accepted binding is immutable: repeating it is safe, a different creator for that customer returns `attribution_conflict`. A code must belong to a hired creator for this app. Losing a plan, closing a brief or suspending a creator does not erase existing payment obligations. Ended hires with no approved work cannot receive new attributions; revenue-share attribution ends with the agreed term.

Use opaque stable IDs (letters, digits, `_`, `.`, `:`, `-`, maximum 200 characters, starting with a letter/digit), not names or email addresses. IDs are scoped to your app. The browser code is attribution evidence, not proof of a sale.

## Milestone bonuses

Some posts pay creators a bonus each time their sign-ups reach a milestone (for example $250 at 100 sign-ups, then $1,000 at 500). Each `attribute()` call is one sign-up. A sign-up counts toward a milestone once it has passed the post's hold (0, 7, 14 or 30 days) without being revoked, and only if it was made within the post's bonus window. Posts that count paying customers also need a settled `sale()` for that customer, net of refunds.

- Pass `email` to `attribute()` so a creator signing themselves up is flagged and doesn't count. Shoploop stores only a SHA-256 hash of the lowercased address.
- Revoke a fraudulent, duplicate or test sign-up during its hold:

```js
await shoploop.revokeSignup({ customerId: user.id, reason: 'Duplicate account' });
```

After the hold, `revokeSignup` returns `revoke_window_closed` (409); ask Shoploop support if a counted sign-up was fraudulent. You can also revoke held sign-ups on the post's page. When a milestone is reached, Shoploop invoices the bonus on the post's bonus terms.

## Server: verified receipts

After verifying your payment provider's webhook signature and settled payment, enqueue a durable delivery job:

```js
await shoploop.sale({
  eventId: 'sale:order_42', orderId: 'order_42', customerId: user.id,
  amountCents: 10000, currency: 'USD', occurredAt: '2026-11-10T14:00:00Z'
});
await shoploop.refund({
  eventId: 'refund:re_42', orderId: 'order_42',
  amountCents: 2500, currency: 'USD', occurredAt: '2026-11-12T14:00:00Z'
});
```

Amounts are positive integer **USD cents**. Report settled revenue before refunds, using one consistent policy for tax/fees agreed with the creator; report each actual refund separately. A sale before the hire is rejected. Events after the share term are retained but excluded from eligible monthly sharing. An unbound customer returns `unknown_customer`: deliver attribution first, then retry the receipt. Do not send ordinary unattributed customers to this API.

Use one stable sale event ID and order ID per settled charge, and one stable event ID per actual refund. Subscription renewals need distinct charge/order IDs. Reuse the **exact same payload** on retries. Conflicting payloads or another sale event for an existing order return 409. Multiple partial refunds are supported, capped at the sale amount. Refunds arriving before a sale are kept as unmatched receipts; the later sale must cover their total. Delivering a refund does not recover funds already invoiced or paid to a creator.

The SDK retries network errors, 429 and 5xx up to twice, with a 10-second per-attempt timeout. Long `Retry-After` throttling is handed back to your outbox. It rejects redirects to avoid forwarding credentials. Persist failed deliveries and retry with the original IDs, amounts and timestamps; the SDK is not a durable queue. A timeout can occur after acceptance, so replay rather than generating a new ID. Other 4xx require correction or reconciliation, not blind retries.

Shoploop accepts your server's assertions; it does not independently verify your payment provider. A public collection endpoint forwarding arbitrary browser payloads under your key is unsafe.

## Monthly review and invoicing

```js
const month = await shoploop.revenue('2026-11');
```

The dashboard and API show gross, refunds, net, the previously reported amount, eligibility and `needsReview`. Months use UTC and the brief's existing revenue-share calendar term. Refunds adjust the **original sale month**, including refunds received later. Unmatched refunds need missing sale receipts before reporting.

Review the totals against your complete billing records, then report the closed month on the brief management page. Tracking never automatically creates, changes, cancels or refunds an invoice. Manual reporting still works for uncaptured revenue. A difference after reporting is flagged for review; contact Shoploop support to reconcile existing invoices/payments rather than submitting another month's figure to compensate silently.

## Ripple invite chains

Ripple links (`/r/srp_…`) send people to your website with `?shoploop_ref=srp_…`. The same `captureReferral()` and `attribute()` calls handle them, so an app that already tracks creators needs only one extra call:

```js
// At signup, exactly as for creators. An srp_ code binds the customer to their place in your invite chain.
await shoploop.attribute({ customerId: user.id, referralCode });
// When they actually use the app (finished onboarding, first session, first action you count). Safe to repeat.
await shoploop.activate({ customerId: user.id });
// A settled sale. Add offerCode when they used your Ripple offer code, so the dashboard counts it as redeemed.
await shoploop.sale({ eventId: 'sale:order_42', orderId: 'order_42', customerId: user.id, amountCents: 4900,
  currency: 'USD', occurredAt: '2026-11-10T14:00:00Z', offerCode: 'FRIENDS50' });
```

Ripple attribution is separate from creator attribution: a customer can have both, and neither conflicts with the other. The first Ripple binding for a customer is permanent; binding them to another member returns `attribution_conflict`. `activate()` returns `unknown_customer` (404) for customers who didn't arrive through Ripple. Sales and refunds use the same receipts as creators; a Ripple-only customer's sales are never part of a creator's revenue share. Shoploop doesn't check offer codes or expiry; your app does. A sale counts as redeemed only when it happened before the offer's expiry date.

Ripple is included with the Growth and Unlimited plans.

## Gifted creator access (optional)

On the Growth and Unlimited plans you can give the creators you hire free access to your app. The simplest set-up needs no code: save an invite link, a promo code or written steps on your app's Shoploop page, switch gifting on for a brief, and each hired creator sees those details.

If you want your app to grant the access itself and to notice when it is withdrawn, verify with Shoploop. A creator with active access can create a one-time `sl_acc_…` token on their creator page and paste it into your app:

```js
const result = await shoploop.redeemAccess(token);
if (result.valid) {
  // Bind result.grantId to the creator's authenticated account on your server, then unlock the comped plan.
}
// Before protected operations, or on a schedule:
const { active } = await shoploop.accessStatus({ grantId });
if (!active) { /* downgrade the account */ }
```

A token works once and expires after 7 days. A refused token resolves with `valid: false` and a `reason` (`unknown_token`, `revoked`, `already_used`, `expired`); it is not thrown. `accessStatus` is false once access is suspended or the hire ends, and stays false after a restore until the creator redeems a new token. `referralCode` and `applicationId` identify the hire; both are null when Shoploop gifted the creator directly. Shoploop does not call your server: poll `accessStatus`. A gifted account pays nothing, so it never produces a sale receipt.

## HTTP API

All requests require `Authorization: Bearer sl_amb_…`. POST bodies are JSON with the same fields as the SDK methods.

| Method | Endpoint | Purpose |
| --- | --- | --- |
| POST | `/api/v1/ambassadors/attributions` | Bind customer to creator (`email` optional) |
| POST | `/api/v1/ambassadors/attributions/revoke` | `{customerId, reason?}` removes a sign-up during its hold |
| POST | `/api/v1/ambassadors/sales` | Record a settled sale (`offerCode` optional, for Ripple offers) |
| POST | `/api/v1/ambassadors/refunds` | Record a refund, even before its sale |
| GET | `/api/v1/ambassadors/revenue?month=YYYY-MM` | Review monthly totals |
| POST | `/api/v1/ripple/attributions` | `{customerId, referralCode: "srp_…"}` binds a customer to their Ripple invite |
| POST | `/api/v1/ripple/activations` | `{customerId}` reports that a Ripple customer used the app |
| POST | `/api/v1/access/verify` | `{token}` redeems a creator's access token; `{grantId}` or `{referralCode}` checks it is still active |

401: missing/revoked/wrong key; 404: unknown customer/referral; 409: attribution/event/order conflict, or a revoke after the hold; 422: invalid data or refund exceeds sale; 429: throttled; 5xx: retry. Responses are not cached. Browser CORS access is intentionally unsupported.

`new Shoploop({ key, endpoint, retries, timeoutMs, fetch })` supports an alternate deployment or test adapter. `endpoint` must be an HTTPS origin; local HTTP is permitted only for localhost. `ShoploopError` exposes `code` and `status`.
