> These are general integration docs. Sign in to download EARNESTY.md from your app’s Integration area, customized with your App ID, reward names, disclosure settings and reward endpoint. [Sign in](https://go.earnesty.app/dashboard). # Earnesty — integration documentation Everything needed to integrate Earnesty, as one file. Your users post about your product on X; Earnesty verifies the post and POSTs a reward to your backend, which credits the user. You keep your own ledger. Your own App ID, X handle, disclosure and reward endpoint are in your console under App settings and Integration. Nothing in this file is specific to one app. Rendered: https://earnesty.app/docs/integration --- # Integrating Earnesty — three steps Your users post about your product on X, YouTube or TikTok. Earnesty verifies the post and tells your backend to reward the user. You keep your own end-user reward ledger. Your organization separately funds an Earnesty wallet for processing fees. The whole integration is **one column, one route, one call**, in that order. Both examples below are TypeScript; the shapes are plain HTTP and JSON, so they transcribe to anything. For processing funding, unlimited registration and queued validation, see [processing credits](https://earnesty.app/docs/integration/processing-credits/). --- ## 1. One column — somewhere for a reward to land Most products meter a plan, not a balance: a monthly quota, a question allowance, seats on a tier. A reward from Earnesty is extra on top of that, so it needs a place to accumulate that your entitlement check already reads. ```sql -- On whatever row your entitlement check reads: the account, the org, the user. ALTER TABLE accounts ADD COLUMN earned_bonus integer NOT NULL DEFAULT 0; -- One row per reward we ever sent you. The UNIQUE constraint is the idempotency. CREATE TABLE earnesty_rewards ( reward_reference text PRIMARY KEY, account_id text NOT NULL, reward_type text NOT NULL, amount integer NOT NULL, -- What is left of THIS grant. Spend against it (oldest first), so a -- revocation can give back one grant's unspent credits without touching -- another's. A flat balance alone cannot tell them apart. remaining integer NOT NULL, received_at timestamptz NOT NULL DEFAULT now() ); ``` Then one line where you compute what a user may do: ```ts const allowed = plan.monthlyQuota + account.earned_bonus; ``` If your product already has a credits balance, skip the column and credit into that. The `earnesty_rewards` table stays: it is what makes the route below safe to call twice. --- ## 2. One route — receive a reward, apply it once We `POST` to a URL you choose, with a bearer token you choose. The body is four fields: ```json { "productUserId": "acct_123", "amount": 10, "rewardType": "credits", "rewardReference": "claim:1841…" } ``` Insert the reference; if it was already there, do nothing. Return 2xx either way. ```ts // Express / Hono / a Supabase edge function — the shape is the same. export async function receiveReward(req: Request): Promise { if (req.headers.get('authorization') !== `Bearer ${process.env.EARNESTY_REWARD_KEY}`) { return new Response('unauthorized', { status: 401 }); } const { productUserId, amount, rewardType, rewardReference, kind } = await req.json(); if (rewardType !== 'credits') { // A reward you have not shipped support for. Refuse it; do not guess. return Response.json({ error: 'unknown_reward_type' }, { status: 400 }); } if (kind !== 'post' && kind !== 'carry' && kind !== 'test') { // Not everything that arrives here is credit: `revocation` takes some // back, and a kind you do not know is a // future occasion, not a failure. Crediting without looking is how a // revocation gets applied with the sign inverted. The full branch — // including giving back one grant's remainder — is in reward-endpoint.md. return Response.json({ success: true, ignored: true }); } // Test rewards use this same balance update. const inserted = await db.transaction(async (tx) => { const { rowCount } = await tx.query( `INSERT INTO earnesty_rewards (reward_reference, account_id, reward_type, amount, remaining) VALUES ($1, $2, $3, $4, $4) ON CONFLICT (reward_reference) DO NOTHING`, [rewardReference, productUserId, rewardType, amount], ); if (rowCount === 1) { await tx.query(`UPDATE accounts SET earned_bonus = earned_bonus + $1 WHERE id = $2`, [ amount, productUserId, ]); } return rowCount === 1; }); return Response.json({ success: true, credited: inserted }); } ``` That is the whole handler. Full contract, including why a duplicate must be a 2xx and what we do when it is not: [the reward endpoint contract](https://earnesty.app/docs/integration/reward-endpoint/). **Check it before a single post exists.** **Integration → Send test reward** sends a real reward — one unit of your selected reward type, to a user id you type (use an account of your own) — and then sends it again with the same reference. You see both answers, and the account should be up by one, not two. The dashboard lists every real delivery afterwards with what your endpoint said about it. **Test rewards change the selected account’s actual spendable balance.** Use an account of your own. Apply `kind: "test"` with the same balance and deduplication logic as ordinary rewards: sending one unit twice must increase its spendable balance by exactly one unit. Logging-only or separate-ledger behavior is an explicit customization, not this example’s default. --- ## 3. One call — enroll a user, show them their code Call this from your backend for every user at signup, not as an optional step — it registers them in your earned tier. What comes back is what they need to post — their claim code — and a link to their own status page. ```ts const res = await fetch('https://api.earnesty.app/v1/users', { method: 'POST', headers: { Authorization: `Bearer ${EARNESTY_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ appId: EARNESTY_APP_ID, productUserId: account.id }), }); const { code, statusPageUrl } = await res.json(); // Show `code` and embed or link to `statusPageUrl`. Registration is unlimited. ``` Idempotent: calling again for the same user returns the same code. The link lasts 30 days: store `statusPageUrl` and `statusPageUrlExpiresAt` on the account's server-side record and never email it. Embed the hosted page with the [embed helper](https://earnesty.app/docs/integration/embed/), or open it from a link. Custom-rendered white-label UI is not currently offered. Full registration contract: [enrolling users](https://earnesty.app/docs/integration/enroll-user/). **Where the link belongs: your own limit screen.** The moment a user reaches a limit is one only you can see — we do not hold your end-user reward balance — and it is the right place for the offer: one line, in your words, linking to `statusPageUrl` from a fresh call. The recurring offer is available regardless of balance, subject to its cooldown, limits and funding. Your app decides when to surface it; Earnesty does not monitor your users’ balances. A low-credit screen is a useful placement, not an eligibility trigger. See [enrolling users](https://earnesty.app/docs/integration/enroll-user/). --- ## Going live ### Three credentials | Variable | Where it comes from | What your backend does with it | |---|---|---| | `EARNESTY_API_KEY` | Earnesty: **Integration → Connect your app**. Starts with `esk_` | Sends it on every call to Earnesty | | `EARNESTY_SIGNING_SECRET` | Earnesty: **Generate signing secret** on the same page. Shown once | Verifies that a delivery came from Earnesty | | `EARNESTY_REWARD_KEY` | You: any long random string, such as `openssl rand -hex 32` | Checks the bearer token on deliveries. Paste it into Earnesty beside your endpoint URL | Keep all three in your platform's secret manager, never in the browser, the repository or logs. ### An install script for your platform Every platform stores secrets differently, so we don't ship a script. Ask your coding assistant to write one for yours from this description: - Ask for the API key and the signing secret with hidden input. Refuse an API key that doesn't start with `esk_`. An empty answer keeps the stored value, so the script can be re-run after rotating one of them. - Generate the reward key on the first run and keep it on later runs. - Store the three values in the platform's secret manager and expose them to the backend under the names above, then redeploy. - Print the reward endpoint URL and the reward key to paste into Earnesty. Never print the API key or the signing secret. - Optionally, keep the integration off behind a switch such as `EARNESTY_ENABLED`, so the credentials can be installed before the code that uses them is released. ### The order 1. Install the credentials and deploy. 2. Save your endpoint URL and reward key in **Integration**, then **Send test reward** to an account of your own. 3. Switch enrollment on. New accounts enroll at signup. Existing accounts enroll on their first visit to your rewards screen, or with a one-off backfill. Enrollment is idempotent and free, so a backfill can run in batches and be re-run safely. 4. Enter your own account's ID in **Integration → Check an account**, then make one real post from it. See [testing your integration](https://earnesty.app/docs/integration/testing/). 5. Activate an offer. Until then, enrolled users can't earn, so enrolling everyone early is harmless. Nothing in this list breaks if steps 2 to 4 happen in a different order. --- ## How this API changes Fields are only ever added, never removed or retyped. Parse what you use and ignore what you don't recognise — an unknown field in a payload or reply is a new feature, not an error. There is no version header; if a breaking change ever becomes necessary, it will arrive behind an explicit opt-in, never by the existing contract shifting under you. ## What you never do - **Mirror a balance.** Your end-user reward balance stays in your system; the Earnesty processing wallet is separate. - **Parse `rewardReference`.** Its format is ours. Switch on `rewardType`. - **Poll us.** Every reward is pushed, and retried for you if your endpoint is down. Why the boundary sits here: you own the user and the ledger that serves them; we own finding the post and proving it qualifies. Neither side needs the other's database. ### Recognizable account names Enrollment accepts an optional `displayName` (for example, “Acme Design Team”) for owner reporting. Keep `productUserId` as the stable reward-recipient ID. Names can be updated through repeat enrollment without changing reward routing. The dashboard distinguishes the account name from the actual X author of a post. See [the enrollment contract](https://earnesty.app/docs/integration/enroll-user/#optional-account-display-name) for limits, update and clear behavior. ## Contextual earning opportunities Use the [posting-offer API and optional button](https://earnesty.app/docs/integration/posting-offer/) to show what an account can earn right now, the recurring reward, a Drop or a Milestone, after a useful result or when access runs low. Your app chooses placement and presentation; the hosted page supplies instructions and history. --- # Reward Endpoint — Integration Contract New here? Start with the [three-step overview](https://earnesty.app/docs/integration/); this page is the full contract. ## Overview Earnesty POSTs a **reward** to your reward endpoint to credit a USER in your product. This endpoint **MUST be idempotent** — Earnesty may call it more than once for the same reward due to retries, network issues, or delivery worker restarts. Your endpoint must handle duplicates safely. ## Idempotency Requirement > **Your reward endpoint MUST be idempotent on the `rewardReference` key.** > > If Earnesty sends a request with a `rewardReference` you have already processed, your endpoint MUST skip the duplicate and return a success response (2xx). Do not credit twice for the same reference. Earnesty makes seven delivery attempts with backoff (1m, 10m, 1h, 6h, then a day apart). A later successful delivery triggers recovery for failed deliveries whose last attempt was more than one hour ago, up to three recovery cycles. Persistently refused deliveries need investigation. This is not exactly-once transport: your ledger must apply each reference at most once. `X-Earnesty-Pending` reports the backlog on successful delivery. `rewardReference` is unique across every reward type, so a handler can dedupe on it alone. --- ## Request Format ``` POST {your reward endpoint} Authorization: Bearer {your API key} Content-Type: application/json ``` ### Body ```json { "productUserId": "user-123", "amount": 500, "rewardType": "tokens", "rewardReference": "claim:1234567890" } ``` | Field | Type | Description | | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `productUserId` | string | The USER's ID in your system — the same ID you passed to `POST /v1/users` | | `amount` | integer | How much to credit, in `rewardType` | | `rewardType` | string | **Which reward.** The immutable key of one of your reward types, matching `^[a-z][a-z0-9_]{0,31}$` | | `rewardReference` | string | Unique idempotency key for this reward (see format below) | | `kind` | string | The occasion: `post` (the verified post), `carry` (Post performance bonus, assessed once ~5 days later), `revocation`, or `test` (the console's test button) | | `earnedAt` | string | When the reward was earned, ISO 8601 | | `postUrl` | string \| null | The post this pays for; `null` on a test reward | | `metadata` | object | Your own tags from the enroll call, verbatim; `{}` when none were set | --- ## Switch on `rewardType`. Never on `rewardReference` `rewardType` is the field that tells you which reward to credit. Apps manage these keys in **App settings → Reward types**. Ongoing rewards use the default type; Drops and Milestones can use other types. Display names may change, but keys stay fixed. Test each type in **Integration** before activating offers that use it. ```js switch (body.rewardType) { case 'tokens': return addTokens(user, body.amount); case 'seats': return addSeats(user, body.amount); default: return 400; // a type you have not shipped support for } ``` **Do not infer the reward from `rewardReference`.** Its format is ours and is documented below so you can read a reward in your own logs — not so you can parse it. We reserve the right to change it, and an integration that switches on it would break silently when we did. The same goes for `amount`: two rewards can legitimately share a number. A `rewardType` you do not recognise should be refused rather than guessed at. It means a reward your handler does not know about — for example, a special Drop reward — and crediting it as your default currency is worse than a failed delivery you can see. --- ## Reward Reference Format The `rewardReference` uniquely identifies each reward. Use it as your deduplication key. | Occasion | Format | Example | | --------------- | ----------------- | ------------------ | | The post itself | `claim:{post_id}` | `claim:1234567890` | | Carry | `carry:{post_id}` | `carry:1234567890` | - The **post reward** is issued once per verified post. - **Carry** settles **once**, five days after the post was made. We read the post's public counts (impressions, likes, replies, reposts, quotes, bookmarks), rank them against the other posts in your program over the last 30 days, and pay zero, a quarter, half or all of the configured Post performance maximum. The maximum is independent of the posting reward, which can be zero. A bonus requires at least 10 reported views and one engagement, and is capped by the remaining allowance for its reward type. Both occasions pay in the same reward type — the one the post was priced in. `grantType` is not on the wire, because the occasion of a reward is our business and the kind of thing given is yours. --- ## Expected Response Return a **2xx status** on success. Earnesty treats any 2xx response as a successful delivery. ### Success (new reward) ``` HTTP/1.1 200 OK Content-Type: application/json { "success": true, "credited": true } ``` ### Success (duplicate — already processed) ``` HTTP/1.1 200 OK Content-Type: application/json { "success": true, "credited": false, "reason": "duplicate_reward_reference" } ``` Both responses are treated as successful delivery by Earnesty. The body format is flexible — only the 2xx status matters to Earnesty's delivery worker. --- ## Ordering, concurrency and deleted accounts Delivery order is not guaranteed. A revocation may arrive before or concurrently with its grant. Record it even if the grant is missing, and suppress that grant if it later arrives. Both branches must lock the same retained account row inside a transaction before checking or updating the ledger. Spending and account deletion must take that lock too. Use READ COMMITTED, or SERIALIZABLE with retry. Locking a nonexistent grant row is insufficient. Keep UNIQUE delivery references, separate grant/revocation records and an index on revokes. Remove only the named grant's remaining amount under the default consumable policy; absorb already-spent units. Never debit unrelated earnings. For deleted accounts, retain a minimal non-personal ledger identity and record late deliveries as discarded before returning 2xx. An unknown account without a deletion record must fail rather than silently lose a reward. The downloaded EARNESTY.md on the Integration page contains the complete transactional reference handler. Test grant-first, revocation-first, duplicate and concurrent deliveries, concurrent spending, and late deliveries after deletion against your actual database. ## The Test Reward **Integration → Send test reward** sends your endpoint a **real reward** — not a ping. It carries your selected reward type and an amount of one, addressed to a `productUserId` you type in (use an account of your own), with a reference of the form `test:`: ```json { "productUserId": "acct_yours", "amount": 1, "rewardType": "credits", "rewardReference": "test:3f1c…", "kind": "test", "postUrl": null } ``` Then it sends **the same request again**. Authenticate, apply and deduplicate `kind: "test"` through your normal balance transaction, just like `post` and `carry`. **Test rewards affect the selected account's actual spendable balance. Use an account of your own.** The expected result is explicit: send one unit twice with the same reward reference and see the account's spendable balance increase by **exactly one**, not zero or two. Two 2xx responses show acceptance, not proof of a balance change; check the balance too. Once the test reward is accepted, **Send test revocation** sends its revocation: `kind: "revocation"`, `revokes` set to the test reward's reference, `rewardReference` of the form `revoke:test:`, sent twice. The balance should return to where it started. Logging-only behavior or a separate test ledger is an explicit customization, not the reference handler's default. Document it if chosen: it will not satisfy the console's standard spendable-balance check. The dashboard's Programme operations section lists every accepted post with what it awarded and how delivery went. A reward your endpoint refused is opened already, with the status and body it returned on the last attempt, so a wrong key reads as "401" in your console rather than as a question to us. The CSV download carries the same answers for every post. --- ## Error Responses If your endpoint returns a non-2xx status, Earnesty will retry with exponential backoff: The retry delays are 1 minute, 10 minutes, 1 hour, 6 hours, then a day apart, with seven failed delivery attempts before the record is marked failed. Later successful deliveries can trigger bounded recovery requeues; do not treat delivery as ordered or as exactly-once transport. Apply each reference at most once in your ledger. **Return 4xx** for permanent errors (bad request, unauthorized). Earnesty will still retry these — ensure your auth credentials are correctly configured. **Return 5xx** for transient errors (database down, timeout). Earnesty will retry automatically. --- ## Security Earnesty authenticates using the API key you provide during configuration. The key is sent as a Bearer token in the `Authorization` header. - Store your API key securely. - Validate the `Authorization` header on every request. - Reject requests with invalid or missing credentials with 401. ### How we hold your API key Your reward API key is **encrypted at rest** (AES-256-GCM, key held in Google Secret Manager and never in the database). It has to be reversible rather than hashed, because we present it to your endpoint on every delivery — so it is encrypted, not one-way. We never display it back to you after you save it; leaving the field blank on the configuration screen means "unchanged", not "clear it". To replace it, type the new one and save — and send a test reward, which uses the key as typed. ### Your compliance record Every reward exists because we verified, at a recorded moment, that the post carried the required disclosure phrase in the position your market asks for, and your exact brand @handle in the post. These are independent checks: `Ad — I use @Acme` can qualify without putting the phrase beside the handle. That attestation (post URL, posted-at, verified-at, the terms in force, and the market, language, placement and policy version the disclosure passed under) is retained per post and surfaces as `post.verified` in `GET /v1/events`. If a user later deletes the post or edits the disclosure out, the record shows the disclosure was present when the reward was earned and that its removal was the user's act, after the fact — which is the evidence that matters if the question is ever asked. We keep the attestation, not the post's text: what your users write is theirs. ### Revocation At the post's settlement check (five days after posting on X; each other platform's own delay) we fetch the post one more time. Gone, made private, or the disclosure edited out, and the claim is **revoked** — and you are told the same way you are told about a reward: **we POST a notice to your reward endpoint**, signed, retried and requeued like any delivery. You never have to poll for one. ```json { "productUserId": "acct_123", "kind": "revocation", "revokes": "claim:1841…", "amount": 25, "rewardType": "credits", "rewardReference": "revoke:1841…" } ``` `revokes` names the grant to reverse; `amount` is what that grant was worth; the notice's own `rewardReference` is its idempotency key, so a retry is safe. **It is not a negative delivery** — nothing is debited from your side by us. Reverse it, absorb it, or reverse only the unspent part: your ledger, your call. Answer 2xx as you would for any delivery. **The window is the settlement, and it closes.** The check happens once, five days after the post. A post deleted or edited on day six keeps its credits — we do not look again, and a revocation is equally final in the other direction: putting the tag back changes nothing, ever, and the user's next post starts clean. `reward.revoked` still appears in `GET /v1/events` for audit, but you do not need to read it to stay correct. Together with the compliance record above this closes the disclosure loop: present when earned, removal recorded as the user's act, reward revoked and reported. ### The delivery signature Every reward delivery (the console's test button included) carries ``` X-Earnesty-Signature: t=,v1= ``` where `v1 = HMAC-SHA256(signing secret, ".")`. Verify it and the bearer token both: the bearer says who is allowed, the signature says this exact body left Earnesty recently — a request replayed from a proxy log fails your timestamp check even though its bearer is right. ```ts import crypto from 'node:crypto'; function verifySignature(header: string, rawBody: string, secret: string): boolean { const m = header.match(/^t=(\d+),v1=([0-9a-f]{64})$/); if (!m) return false; const [, t, v1] = m; if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false; // 5-minute tolerance const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex'); return crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected)); } ``` Verify against the **raw body bytes**, before any JSON parsing or re-serialisation — a re-stringified object is a different byte sequence and a false negative. ### Your webhook signing secret The secret behind that signature, per app: - **You generate it when you need it**: _Configuration → step 5 → Generate signing secret_, or `POST /v1/apps/:id/signing-secret/rotate`. It is shown once, in that response, and encrypted at rest; we cannot read it back to you afterwards. - **Generating again replaces it.** The previous secret stops signing immediately, and a delivery your endpoint rejects is retried for about three days, which is your window to update `EARNESTY_SIGNING_SECRET`. - **Rotating has no cliff, because retries are the overlap.** We start signing with the new secret immediately, so deliveries in the gap fail your verifier — and are retried for about three days. Update `EARNESTY_SIGNING_SECRET` any time in that window and everything queued arrives. Nothing is lost; there is nothing to coordinate. **Rotating your reward API key** (the bearer you chose) has no server-side overlap either: during a rotation, have your handler accept either of the two values — one `||` in your code — then drop the old one. The signature stays valid throughout, since the signing secret is independent of the bearer. --- ## Summary | Requirement | Detail | | ---------------------- | ------------------------------------------------------------------------------------------- | | **Idempotency** | MUST deduplicate on `rewardReference` | | **Which reward** | Switch on `rewardType` — never on `rewardReference` or `amount` | | **Auth** | Bearer token (your API key) in `Authorization` header | | **Success signal** | Any 2xx status code | | **Retry behavior** | Seven attempts over ~3 days, then automatic redelivery once your endpoint answers 2xx again | | **Duplicate handling** | Skip it, return 2xx | ## Funding, validation deadlines and processing fees A validation request normally receives HTTP 202 and a durable queue receipt. That is permission to process the request, not a reward promise or an ordinary funding reservation. If the available balance cannot cover the check when the worker runs it, for any offer including a Drop, the attempt fails with `funding_unavailable`. If funding runs out between the read and acceptance, acceptance also fails. The request does not wait for a future top-up. After a confirmed top-up, the same unaccepted post can be submitted again using a **new request key** once the previous request is terminal. A repeated old key returns the original receipt; use it only to recover a pending request or uncertain network response. Requests are limited to one per enrolled account per 60 seconds. For both Validate and exact-URL submission, the current post window is **6 days, 23 hours and 30 minutes before the new request's receipt time**, through receipt time. Submit before the post ages out. A queued request currently has a **10-minute recovery deadline**; use the returned `deadlineAt` rather than a client timer as the authority. Provider errors, read budgets and normal eligibility checks can still prevent acceptance. A top-up does not revive a terminal receipt or guarantee that an expired offer or otherwise ineligible post will earn. Drops reserve nothing in advance: each accepted Drop post is charged from the available balance, and a Drop's places are a cap, not a hold. A viewer's place is not reserved either. A Drop requires an eligible validation receipt before its closing time; a new receipt after closing does not recover a missed Drop. An already accepted reward continues delivery and settlement even if general funds subsequently run out. The X processing fee is **5 Earnesty Credits ($0.05) per accepted post validation**, including its later settlement check. One Earnesty Credit represents one US cent. The fee and accepted reward record commit atomically; rollback leaves neither charged nor accepted. A qualifying bonus-only post is still an accepted validation and incurs this fee. | Event | Processing fee effect | | -------------------------------------------------------------- | ------------------------------------------------------------------------ | | Enrollment, empty/invalid checks, duplicates, funding refusals | No accepted-post fee | | Accepted post | One fee at the applicable rate | | Later performance bonus or settlement check | Included; no additional fee | | Delivery retries and duplicate deliveries | No additional fee | | Revocation or an undeliverable reward | No additional fee and no automatic refund of the original processing fee | | Console test deliveries | No processing fee | Rates can change with notice; Billing shows the current rate, and a change applies to Drop posts accepted after it like any other. Processing fees pay Earnesty's work, not the allowance your app grants its users. Auto-recharge is optional and only confirmed funds can be spent. ## Delivery amounts `amount` is a JSON number representing whole units, with no fractional precision. Accept integers from **1 to 2,147,483,647** for `post`, `carry` (the performance bonus) and `test`. For `revocation`, accept **0 to 2,147,483,647**: zero means the original grant was not found; use `revokes` to identify and suppress/reverse the grant, not the numeric amount as a debit. Zero-value post or bonus grants are not delivered. Configuration limits can be lower than this wire/storage bound. Reject strings, fractions, negative numbers and out-of-range values with 400; in JavaScript use `Number.isSafeInteger` plus these bounds. Keep aggregate balances in a wider exact integer type. ## Release an account and acknowledge late deliveries From your backend, send: ```http POST /v1/apps/{appId}/users/{urlEncodedProductUserId}/release Authorization: Bearer $EARNESTY_API_KEY ``` There is **no request body**. URL-encode the product account ID as a path segment. Success is `{"released":true,"alreadyReleased":false}`; repeating a completed release returns `{"released":true,"alreadyReleased":true}`. Unknown app/account IDs return 404. Release stops new earning for that enrollment, disconnects its X accounts and closes unsettled posts without future bonuses. It does not erase history or cancel already-created grants or revocations; these continue delivery and retries. Work already in flight can race with release, so never assume release drains the delivery queue. Re-enrollment with the same ID revives the identity. For a shared workspace, release when that product account is deleted, not when one member leaves. For a permanently deleted product account, authenticate and validate each late delivery, then durably record its reference and disposition against a retained non-personal account identifier. Acknowledge with 2xx after committing, without recreating the account or making rewards spendable. Retain revocations so later grants remain suppressed. Never reuse that account ID for someone else. A missing account with no deletion record is an integration error, not proof of deletion: return a non-2xx response and investigate. A database outage also requires a non-2xx response so the delivery can retry. --- # POST /v1/users — Enrollment Contract Step 3 of the [three-step overview](https://earnesty.app/docs/integration/). Registration is unlimited. Funding and offer eligibility are checked separately when accepting a post; see [processing credits](https://earnesty.app/docs/integration/processing-credits/). ## Overview Call this for every user at signup — not when they show interest, and not as an optional step. It registers them in your earned tier and returns what makes them able to earn: their Claim Code, the string that has to appear in their first post, assigned once and never replaced, and a signed link to their status page. Authentication is an API key (`Authorization: Bearer …`), because your backend is the caller. ``` POST /v1/users Authorization: Bearer {your_api_key} Content-Type: application/json { "appId": "…", // required, UUID, must belong to your organization "productUserId": "…", // required, the USER's id in YOUR system "displayName": "Acme Design Team" // optional account label } ``` Response `201` for a new enrollment, `200` for a repeat call: ```json { "appUserId": "…", "existing": false, "code": "#earnesty_7K4P", "statusPageUrl": "https://…" } ``` ## Choosing `productUserId` Use a stable identifier from your product that your reward endpoint can map to **the account whose allowance the reward expands**. For a product with personal accounts, that is the personal account ID. For a product with team or workspace billing, you have two choices, and per-person is usually the better one: - **Enroll each person** (their user ID). Each teammate gets their own rewards page from their own login, connects their own accounts, and has their own cooldown. Your reward endpoint receives the person's ID and credits the workspace they belong to. - **Enroll the workspace** (its ID). The team shares one rewards page and one cooldown. The first account connects on its own; later ones are approved on the page. Free accounts qualify too; a payment method or paid subscription is not required. Earnesty delivers the supplied `productUserId` to your endpoint. It does not look up a payment-provider customer or infer ownership. Your customer's product account is distinct from your organization's Earnesty processing wallet. The hosted page reports rewards earned; your product keeps the spendable balance. One enrollment can connect up to five X accounts. They share its reward recipient and ordinary cooldown. An X account cannot be connected to multiple enrolled accounts within the same app at once. What that means in practice: - **For a personal product account, enroll its account ID; for a team, enroll each person.** The simple case, and most products. - **A workspace enrollment admits its own members.** Several X accounts can earn into one enrolled id. The FIRST account binds on its own: posting a code that only came from inside your product is proof enough. After that the code is public — it rode a post — so it stops being a way in. The next account that posts it appears on the rewards page as a request for an existing member to approve or turn away, with nothing needed from your backend. The post that asked is credited when it is approved, if the shared cooldown allowed a post at the moment it was made. You never learn anyone's X handle, and you never have to. `binding.pending` in `GET /v1/events` tells you a request is waiting, if you want to nudge someone. Each account disconnects individually. One current limit: the cooldown is per enrolled id, so a team shares one earning cadence. A departed teammate's account is disconnected from the rewards page (each account has its own disconnect); use the owner-side `POST …/unbind` action below when a teammate leaves without disconnecting. - **Switching X accounts, or "changing" the id:** enrollment is registration, so there is nothing to edit. The user disconnects their X account on the rewards page (or you enroll a new `productUserId`, which mints a new code), and their next post carrying the new code binds fresh. An X account still bound elsewhere is refused until it disconnects — that is the hijack guard. History never moves: rewards already credited stay where they landed. ## Optional account display name Send `displayName` to make the owner dashboard recognizable: a person's preferred name for a personal account, or the team/workspace name for a shared account. No legal name or email address is required. The label is for the app owner's reporting, not a public social profile. - A nonempty string, at most 120 characters after trimming, without control characters. - Omitted on repeat enrollment: preserve the existing name. - Supplied on repeat enrollment: replace the name. - Explicit `null`: clear the name. - Empty or whitespace-only strings: `400 invalid_display_name`. The account ID, Claim Code and reward routing never change with this label. Optional metadata remains opaque routing data; Earnesty does not infer names from it. ```json { "appId": "YOUR_APP_UUID", "productUserId": "workspace_123", "displayName": "Acme Design Team" } ``` Earnesty stores the verified platform author ID and known handle for each newly verified post. The dashboard shows the post's author separately from the account receiving rewards. Current connected handles appear with account totals. A handle is a recorded label and can change; profile links use the stable X author ID. Before a name or handle is available, the app's account ID is the fallback and is always available in reporting details. ## Showing the user their status page `statusPageUrl` is the user's own view of their earning status, authenticated by the token in its query string. **Embed it.** The host sets no `X-Frame-Options` and no `frame-ancestors`, so an iframe works from any origin today, and the page sets no cookies — the token in the URL is what authenticates. If we ever add a per-app origin allowlist, registering yours will be part of shipping it and existing embeds will not be broken without notice. Opening it from a button is equally fine; embedding is what most apps want. The link lasts 30 days: store `statusPageUrl` and `statusPageUrlExpiresAt` on the account's server-side record, show it only to that account's signed-in members, and never email it. For automatic sizing and access-link renewal, use the [embed helper](https://earnesty.app/docs/integration/embed/). Custom-rendered white-label UI is planned for a future paid offering. ## Where the link goes: your own limit screen The moment a user reaches a limit — the quota is spent, the plan's allowance is used up, the paywall is about to render — is a moment only you can see. We hold no balance, so nothing on our side can notice it, and no endpoint of ours will ever pretend to. Your limit screen already exists; give it one more line, in your own words, that links to the user's status page. That puts the earned tier inside your product, in your voice, at the point where someone is deciding what to do next — and it needs no knowledge of ours, and gives us none of your plans, prices or units. The call is the one above: `POST /v1/users` from your backend when the screen renders, `statusPageUrl` from the response. It is idempotent, registration is free, and the token is fresh each time. The offer is available regardless of the user’s balance. Your app can surface it when credits run low or keep it in a permanent rewards area; Earnesty does not monitor the balance or trigger that placement. Recurring eligibility follows the configured cooldown. Posts published inside the cooldown window do not become eligible by being submitted later. Drops and Milestones follow their own eligibility rules and can qualify outside the recurring cooldown. Funding and per-user reward limits still apply. ## Errors Every refusal is `{ "error": "", "code": "" }`. Branch on `code` — it is stable; the sentence is for a person and may change. | Status | `code` | When | |---|---|---| | 400 | `invalid_display_name` | `displayName` is not a nonempty name of at most 120 characters without control characters. Omit it to keep the stored name, or send null to clear it. | | 401 | `unauthorized` | No valid API key in the `Authorization` header — one answer for missing, malformed, unknown and revoked keys. | | 400 | `invalid_json` | The body is not JSON. | | 400 | `missing_field` | `appId` or `productUserId` absent or blank. | | 400 | `invalid_app_id` | `appId` is not a UUID. | | 400 | `invalid_product_user_id` | `productUserId` longer than 256 characters, or carrying control characters. | | 400 | `invalid_priority` | `priority` present and not a boolean. | | 400 | `invalid_metadata` | `metadata` not an object of at most 20 bounded string pairs (keys ≤ 40 chars, string values ≤ 500, no control characters). | | 404 | `app_not_found` | No app with that id in the organization the key belongs to. An app another organization owns is a 404, not a 403. | A `200` or `201` never carries `error`. `201` is a new enrollment; `200` is a repeat call. ## `metadata` Optional object of up to 20 string pairs — your tags, stored verbatim and echoed in every reward delivery for this user, so your handler can route a reward without a lookup (`{"team": "org_42"}` is the canonical use). Present replaces the stored object; absent leaves it alone. We never read it. ## Registration and earning availability Register users at signup and show their hosted rewards page. Registration is free and does not spend processing credits. Available offers, cooldowns, limits and wallet funding determine whether a post can earn. The hosted page handles these states. One enrollment can link up to five X accounts, sharing the same reward recipient and recurring cooldown. Release a user when their account is removed; their X accounts disconnect and credited history remains. Registering the same ID again restores the identity. Banning pauses earning without erasing history. Posts made before registration are not retroactively rewarded. ## Owner actions Levers for the situations you cannot leave to the user, addressed by app and your own id — `/v1/apps/{appId}/users/{productUserId}/…` — with your API key (or a console session): - **`POST …/unbind`** — disconnect an account the user cannot or will not disconnect (the teammate who left). Body `{ "authorId": "…", "platform": "youtube" }` for one account (from `binding.created` events or the rewards page); `platform` is `x`, `youtube` or `tiktok` and defaults to `x`, and any other value is refused with `400 invalid_platform`. `{ "platform": … }` alone disconnects every account on that platform, and an empty body disconnects them all. Same effects as the user's own disconnect. - **`POST …/release`** — this user is gone (deleted their account, say). Their accounts are disconnected and credited history stays. Re-enrolling the same id revives them. - **`POST …/ban`** / **`POST …/unban`** — earning off, and back on. Banned, a user's posts never verify and their rewards page says earning is off for this account; everything already credited stays — history never moves. Both idempotent, both audited. - **`POST .../allow-handle`** with `{ "handle": "teammate_x" }` — _optional._ Pre-approve one more account by handle, for the rare product that already knows its users' handles. Add `"platform": "youtube"` or `"platform": "tiktok"` for a video account; without it the handle is an X username. A YouTube channel is named by its @handle, not its channel id, and a TikTok account by its username. The approval counts on that platform only. An unknown platform answers `400 invalid_platform`, and a handle that does not fit the platform answers `400 invalid_handle`. Most apps need nothing here: approval happens on the rewards page, where somebody can actually recognise the account. - **`PATCH …`** with `{ "productUserId": "new_id" }` — rename your identifier for the user. Nothing strands: bindings, rewards and history hang off our internal id; enroll and reward deliveries use the new name from then on. `409 product_user_id_taken` when the new id is already enrolled. Errors follow the usual shape: `{ "error", "code" }`. ## Idempotency Registering the same `productUserId` returns the existing identity and claim code. Refresh the signed `statusPageUrl` when displaying the rewards page; do not store it as a permanent URL. ## Releasing the product account Use `POST /v1/apps/{appId}/users/{urlEncodedProductUserId}/release` with your backend API key and no body. Release stops new earning but does not cancel already-created deliveries. See [release and late-delivery handling](https://earnesty.app/docs/integration/reward-endpoint/#release-an-account-and-acknowledge-late-deliveries) for responses, shared-account handling and acknowledgment after deletion. ## Contextual earning opportunities Use the [posting-offer API and optional button](https://earnesty.app/docs/integration/posting-offer/) to show a currently eligible recurring offer after a useful result or when access runs low. Your app chooses placement and presentation; the hosted page supplies instructions and history. --- # Embedded rewards page Use the Download EARNESTY.md button in Integration for an example with your app's host and settings. The public `embed.js` helper exposes `Earnesty.mount(container, { url, refreshUrl?, onError?, onReady?, onRewarded? })`, returning `setUrl(url)` and `destroy()`. Supply a fresh statusPageUrl from your authenticated backend. The helper adds `embed=1` and the parent's exact origin, creates an accessible titled iframe, and resizes it as content changes. No user data or access token is included in resize/expiry messages. Messages are checked against both iframe window and origin. `refreshUrl` should call your backend, which repeats POST /v1/users for the current user and returns a new statusPageUrl. It runs when expired access is detected. On failure the expired-link message stays visible; `onError` can show a retry action. Destroy the widget on route unmount or logout. Never pass an organization API key into the browser. Avoid adding iframe sandbox restrictions without testing links, forms and clipboard behavior. Earnesty branding remains visible. Load the helper and request the fresh URL concurrently when the user approaches the rewards screen. Preconnect to your rewards-page origin from the host page. For local tabs on that screen, keep the existing mount where practical; destroy it on logout or account changes. Do not put access tokens or reward payloads in persistent browser caches. `onReady({ durationMs })` runs once per URL after real reward data has rendered. It measures mount-to-content time, excluding the host's earlier URL request. Measure from the user's navigation action as well so this earlier delay remains visible. The callback contains no user data. An iframe `load` event only proves that the document loaded; it does not mean reward data is ready. `onRewarded()` runs when a post is accepted on the page. It carries no data: the reward itself still arrives at your reward endpoint, usually within seconds, so use it to re-read the balance your app shows. A plain statusPageUrl link remains supported. For a contextual CTA in your own UI, use the [posting-offer JSON API and optional button](../posting-offer/). Full white-label rewards-page rendering remains a future option. --- # Contextual posting offers Show an earning opportunity where it is useful: after a user creates something worth sharing, as credits run low, or beside an action that needs more access. Your app decides placement. Earnesty lists what this account can earn right now: the recurring reward, open Drops and Milestones. The hosted earnesty.page does the rest: the text to post, where to post it, the post check and the account's history. ## JSON API From your backend, call `POST /v1/posting-offer` with your organization API key: ```http POST /v1/posting-offer Authorization: Bearer YOUR_API_KEY Content-Type: application/json {"appId":"YOUR_APP_UUID","productUserId":"workspace_123"} ``` Resolve productUserId from your authenticated account or workspace membership. Never accept an arbitrary account ID from the browser. Register the account using POST /v1/users first; this read-only endpoint does not enroll or restore accounts. ```json { "eligible": true, "reason": null, "checkedAt": "2026-09-22T10:00:00.000Z", "nextEligibleAt": null, "offer": { "kind": "recurring", "reward": {"amount": 50, "key": "credits", "labelSingular": "credit", "labelPlural": "credits"}, "suggestedLabel": "Post about this to earn 50 credits", "url": "https://your-app.earnesty.page/?t=SIGNED_TOKEN", "expiresAt": "2026-09-22T10:15:00.000Z" }, "offers": [ { "id": "recurring", "kind": "recurring", "name": "Every post", "description": null, "available": true, "reason": null, "reward": {"amount": 50, "key": "credits", "labelSingular": "credit", "labelPlural": "credits"}, "bonusUpTo": 25, "repeat": {"kind": "every_n_days", "days": 7}, "nextEligibleAt": null, "startsAt": null, "endsAt": null, "placesLeft": null, "suggestedLabel": "Post about this to earn 50 credits", "url": "https://your-app.earnesty.page/?t=SIGNED_TOKEN&offer=recurring" }, { "id": "drop:4c1c…", "kind": "drop", "name": "Launch week", "description": "For posts about our launch week.", "available": true, "reason": null, "reward": {"amount": 100, "key": "credits", "labelSingular": "credit", "labelPlural": "credits"}, "bonusUpTo": null, "repeat": {"kind": "once"}, "nextEligibleAt": null, "startsAt": "2026-09-22T00:00:00Z", "endsAt": "2026-09-29T00:00:00Z", "placesLeft": null, "suggestedLabel": "Post for Launch week to earn 100 credits", "url": "https://your-app.earnesty.page/?t=SIGNED_TOKEN&offer=drop%3A4c1c…" } ], "expiresAt": "2026-09-22T10:15:00.000Z" } ``` `eligible`, `reason`, `nextEligibleAt` and `offer` describe the recurring reward. `offers` lists every offer, recurring first, then Drops (open, and scheduled ones with `reason: "not_started"`), then Milestones. Each `url` opens the rewards page with that offer already chosen; it is present only while the offer is `available`. `placesLeft` is null for a Drop with no limit. A Drop or Milestone the account has already earned, or cannot earn now, comes with `available: false` and a `reason` (`already_earned`, `not_started`, `funding_unavailable`, `unavailable`). Use your own button, banner or access screen. Render the reward's labels, not a hard-coded currency. `url` opens the hosted rewards page, which reads current eligibility before showing the posting instructions and X composer. It does not post automatically. Ineligible accounts receive HTTP 200 with `eligible: false`, `offer: null` and a reason: `released`, `banned`, `not_enrolled`, `offer_inactive`, `lifetime_limit`, `funding_unavailable`, `cooldown` or `offer_unavailable`. Only `cooldown` supplies a `nextEligibleAt`; that date does not guarantee funding or future eligibility. Hide the CTA, or explain the state in your own UI. A Drop or Milestone in `offers` can still be open while the recurring reward waits. Eligibility is a snapshot, not a reserved reward. Terms, funding and account status can change. Verification still decides whether the published post qualifies and the amount actually granted, including any remaining lifetime allowance. Refresh when showing the opportunity and when the user returns to your app. Do not persist or log the response, put it in analytics, or share signed links between accounts. Responses are private/no-store; your backend should return the same cache headers. Links expire after 15 minutes (`expiresAt`; null when no offer is available and no link was issued). Errors use `{ "error": "...", "code": "..." }`: 400 `invalid_json`, `invalid_app_id`, `invalid_product_user_id`; 401 `unauthorized`; 404 `app_not_found` or `user_not_found`; 503 `offer_unavailable`. Treat errors as unavailable; do not invent an offer. ## Optional button helper Load `/embed.js` from your rewards-page origin. `mountOffer` uses the same JSON contract; no framework or browser API key is needed. Style the generated anchor with your own CSS. ```html
``` Your authenticated `/api/my-posting-offer` backend calls Earnesty for the current account and returns the JSON. The button shows the recurring reward, or the first open Drop or Milestone while the recurring reward waits. Pass `offerId` (for example `"drop:4c1c…"`, from `offers`) to show one offer only. The helper hides the link during loading, on failure, while nothing is available and after expiry. It refreshes on window focus and ignores stale requests. Destroy and remount when switching accounts. The full rewards-page embed remains available via `Earnesty.mount`; the contextual helper does not replace history or account management. --- # Processing credits See [the integration overview](https://earnesty.app/docs/integration/) for the full integration contract. ## Configure and fund an offering Your system owns end-user rewards; the Earnesty organization wallet pays processing fees. The processing fee is 5 Earnesty Credits per accepted validation on every platform, including its later settlement check. Every $1 buys 100 credits. Registration is free. 1. Configure the reward endpoint and supported reward types, then test delivery to an account of your own. Delivery must be idempotent by `rewardReference`; follow the [complete endpoint contract](https://earnesty.app/docs/integration/reward-endpoint/), including revocations. 2. In Billing, purchase at least $10 for 1,000 credits, or claim the introductory promotion if available. A pending payment is not spendable balance. 3. Ongoing rewards and Milestones use available purchased or promotional credits. A card is optional. For automatic replenishment, enable auto-recharge with an explicit monthly spending ceiling. Low-balance emails prompt manual funding when auto-recharge is off. 4. For a Drop, choose its dates, unique tag, reward and number of places. The places are a cap on how many posts the Drop rewards, not a reservation: each accepted Drop post is charged from the available balance, like any other offer. A time-only Drop's cap is the number of selected participants, and adding participants raises it without reserving anything. Activating a Drop needs only enough available credits for one check. Drops do not require auto-recharge, and a Drop pauses like any offer when the wallet cannot cover a check. 5. Enroll users from your backend and show the returned hosted reward-page link. Refresh the signed link when rendering; do not store it as a permanent URL. Purchased funds do not expire. Promotional funds expire after 90 days and cannot be refunded. Eligible promotional funds are spent oldest first, for every offer type. ## Registration is separate from earning availability Register users with `POST /v1/users`, using your server-side API key, your `appId` and their `productUserId`. Registration is free and unlimited. Enrollment does not guarantee an immediately available posting reward. Read the hosted page or `GET /v1/status?t=…` for current eligibility, funding and offers: - `funding.available` describes general reward funding. Cooldowns, offer terms and user eligibility still apply. - Drops have no funds of their own. When general funding is unavailable, no Drop accepts posts either, and the hosted page shows the Drop as not currently available. - Each Drop exposes its funding and user-specific `fundingAvailable`; Milestones expose their remaining terms and funding availability. Show the hosted page whenever possible so these rules and recovery states stay current. If funding is paused, say that posting rewards are currently unavailable. A user's existing product access and previously delivered rewards are managed by your app. Remaining Drop places are a live snapshot, not a reservation for the viewer. ## Validate after posting Tell users to press **Validate** after publishing. A Drop requires a validation request before its published closing time. Allocation follows authenticated validation receipt order, subject to eligibility; posting earlier alone does not reserve a place. Timely queued requests can finish after closing. The nightly sweep can use remaining capacity only while the Drop is open. For a custom reward page, the current HTTP sequence is: ```http POST /v1/status/check-now Content-Type: application/json {"t":"SIGNED_STATUS_TOKEN","requestKey":"CLIENT_GENERATED_UUID"} ``` For an exact post, use `POST /v1/status/submit` with the same fields plus `"url":"https://x.com/example/status/123456789"`. These endpoints authenticate with the signed user token, not your organization API key. The response is HTTP 202 with `queued`, `requestId`, `state`, `receivedAt` and `deadlineAt`. This acknowledges the request; it does not acknowledge a reward. Persist the request key and, for exact submissions, the URL before sending. If transport fails, retry the same key and URL. Once a receipt exists, poll: ```http GET /v1/status/validation/REQUEST_ID?t=SIGNED_STATUS_TOKEN ``` Poll only while that request is pending, with bounded delays (the hosted page uses five seconds). A completed run can contain rejected or skipped candidates; show success only when a result has `state: "accepted"`. Refresh the user's status when processing finishes. Reward delivery to your backend happens separately and may still be retrying. Never credit your own user from a browser receipt. After an expired-link response, obtain a fresh signed link for the same enrollment and resume the saved request. Keep recovery state scoped to the enrolled user and ignore late responses after switching users. Do not mint new request keys to work around a pending request or a transport error. ## Insufficient funds and retrying the same post A queue receipt does not reserve ordinary processing funds. If funds are insufficient when the worker checks or commits acceptance, the attempt fails; it does not wait for a top-up. After funding returns and the old request is terminal, submit the same post with a new request key while it is still within the validation window and eligible for its offer. The current window is 6 days, 23 hours and 30 minutes, and a receipt has a 10-minute recovery deadline. Reusing the old key returns the old receipt. Drops still require receipt before closing. See [funding, deadlines and fee rules](https://earnesty.app/docs/integration/reward-endpoint/#funding-validation-deadlines-and-processing-fees) for the exact distinction, fee table and exceptions. ## Stopping and refunds An owner can stop new reward acceptance immediately, including active Drops. Already accepted posts still receive delivery and settlement. Unused purchased funds can be refunded; promotional funds never cash out. Stopping a program does not reverse rewards already delivered to your users. ## Earnesty Credits and API amounts The wallet counts Earnesty Credits, and one credit is bought for one USD cent. Amounts in credits are named for credits (`availableCredits`, `processingPriceCredits`). Amounts of money, such as a purchase, its tax or a refund, follow Stripe's convention (`amount`, `taxAmount`): an integer in the currency's smallest unit, with a lowercase ISO 4217 `currency` beside it. For example, `availableCredits: 500` is 500 credits, currently enough for 100 X validations, and a $10 purchase is `amount: 1000, currency: "usd"`. Earnesty Credits are separate from the rewards your app issues to its users. Credit balances do not promise fixed validation counts. Platform rates may vary; future increases receive 30 days’ notice, and a change applies to every post accepted after it, Drop posts included. Purchased credits do not expire; promotional credits expire after 90 days. Refunds return the unused purchased value to the original payment, never promotional value or a recalculation using today’s validation rate. ### Refunds in Billing Payment history records payments and offers status refresh only for unresolved outcomes. A failed payment is labeled “Not paid — no funds added”; a new purchase starts in Add funds. Refund controls live in a separate wallet section showing the total refundable purchased credits and their USD value, including purchases older than the displayed payment history. Promotional credits and pending refund holds are excluded. One confirmed request reserves the whole requested balance atomically, then allocates refunds to original payments. The same request key resumes the same allocation after interruption. No partial reservation is created if the available balance has changed. Provider returns may complete separately; refund history shows each original-payment return. Requests spanning more than 20 payments retain durable pending adjustments for the refund recovery worker. Auto-recharge remains an independent owner setting, with a warning to disable it before refunding if no further automatic purchases are wanted. ## Multiple reward types Use App settings → Reward types to define what the app grants. Each type has a permanent `rewardType` key and editable display names. Marketing can introduce a new type while drafting a Drop or Milestone. Confirm its mapping and test delivery in Integration before launch. Unknown keys must not silently grant the default currency. Handle idempotency by `rewardReference` for each delivery, regardless of type, and verify the test grants only once. Lifetime caps are independent per type; the config field `maxLifetimePerUser` controls the default type only. --- # Testing your integration You test with an account of your own in your app: Earnesty enrolls it like any user, a test reward changes its real balance, and a real post from it is checked and charged like anyone's. The introductory credits cover your testing. Customer testing controls live on **Integration**, not on marketing offer screens. Reusing a ready reward type with new amounts, dates or posting rules does not require another delivery test. ## 1. Enroll an account of yours Run your app's normal enrollment for the account: sign it up, or let your backfill reach it. Then enter its ID in **Integration → Check an account**. The ID is your app's own ID for the account, the `productUserId` your backend sends. If the check says your app has not enrolled the ID, your backend has not yet called `POST /v1/users` for it with this app's API key. If it says the ID is enrolled in another app, your backend is using that app's key. ## 2. Send a test reward Press **Send test reward** beside each reward type. It goes to the account you checked, and we remember that account for this connection. Each test sends one unit, then repeats exactly the same request. Test rewards affect the account's actual spendable balance. Apply `kind: "test"` through your normal balance and deduplication transaction. The account's spendable balance must increase by exactly one unit, not zero or two. An HTTP success proves acceptance; check the balance too. Logging-only or separate-ledger handling is an explicit customization, not the default, and does not satisfy this check. After a test reward is accepted, **Send test revocation** sends `kind: "revocation"` with `revokes` naming that test reward, twice under one reference. Your handler should take the unit back once, so the balance returns to where it started, and answer 2xx both times. A real revocation arrives the same way when a rewarded post is gone at its settlement check, five days after posting on X. Confirm that your app handles each permanent reward key. Offer activation requires that mapping confirmation and a successful test of the saved production connection. Changing its credentials, endpoint or signing secret invalidates the old connection proof. Unsaved-pair tests cannot establish readiness. The **Test live reward delivery** section shows a compact readiness summary and collapses when all live reward types are mapped and tested. Expand it to retest or to reach optional development testing. Tests send a direct reward without a campaign or post; response details stay collapsed. After a successful delivery, unconfirmed types ask the developer to confirm that exactly one unit arrived. **Development connection (optional)** is collapsed by default. Save its endpoint, separate bearer key and signing secret, and a development account ID. A public HTTPS endpoint or tunnel is required when Earnesty is hosted. Development tests never fall back to production credentials, never establish production readiness, and never redirect actual earned-reward deliveries. They do not require posts or consume processing credits. ## 3. Make one real post Before releasing to your users, post on X from the account and press **Check my post** on its rewards page inside your app. **Preview rewards page** in Integration opens the same page. This is the test that proves the disclosure, the account binding and the whole loop as your users will meet them. The post is checked and charged like any accepted post: one processing fee, the same checks, the same cooldown and funding rules. It earns under whatever offer it matches, and its reward reaches your endpoint through the real delivery worker, signature and retries included. A post that carries an open Drop's tag takes one of that Drop's places. The post appears in the dashboard and in Programme operations like any other. Use offers you are ready to run, or a short Drop you end afterwards. --- # GET /v1/events — the event log Everything that happens to your programme, as a retrievable list — poll it to reconcile your ledger and investigate delivery or account-linking activity. When push webhooks ship, they will deliver these same events; building on this log now means changing nothing later. ```http GET /v1/events?product_id=&limit=25 Authorization: Bearer {your_api_key} ``` Reply: `{ "events": [ { "id", "type", "createdAt", "data" } ], "hasMore": true }` — newest first. Page with `starting_after=`. Every `data` carries `productUserId`; the rest is per type: | `type` | When | `data` | | --------------- | ------------------------------------- | ----------- | | `user.enrolled` | A user was enrolled (first call only) | — | | `binding.created` | An account on any platform was connected — a first qualifying post carrying the account code, or a member approving a waiting account | `platform`, `handle` | | `binding.pending` | An account posted the code and is waiting for approval on the rewards page | `platform`, `handle` | | `binding.removed` | An account was disconnected — by the user on the rewards page, or by you as the owner | `platforms` | | `post.verified` | A post passed verification and was credited | `amount`, `rewardType`, `postedAt`, `postUrl` | | `reward.delivered` | Your endpoint accepted a delivery | `rewardReference`, `amount`, `rewardType` | | `reward.revoked` | A credited post was deleted, made private, or had its disclosure removed before its settlement check (five days after posting on X; the platform's own delay elsewhere). **Also pushed to your reward endpoint** as `kind: "revocation"`, so this row is audit rather than the way you find out | `rewardReference`, `amount`, `reason` (`post_deleted` \| `disclosure_removed` \| `no_longer_public`), `postUrl` | | `reward.delivery_failed` | A delivery exhausted its retries (seven over ~3 days) without a 2xx | `rewardReference`, `amount`, `attempts` | Reconciliation recipe: nightly, walk events since your last stored cursor; every `reward.delivered` should exist in your rewards table by `rewardReference`. A `reward.delivery_failed` is a reward your endpoint never accepted — but it is not stranded: once your endpoint answers any delivery with 2xx again, failed rewards are requeued automatically and arrive on their own. Crediting from the event is still sanctioned belt-and-braces (idempotent by reference; a later redelivery dedupes into a 2xx), and `X-Earnesty-Pending` on each successful delivery tells you the backlog size — but with automatic recovery, this log is an audit tool, not a correctness requirement. `product_id` is the App ID — the same value the guide's constants table calls App ID. Errors are `{ "error", "code" }`: `missing_field`, `invalid_limit`, `invalid_cursor` (400), `unauthorized` (401), `app_not_found` (404).