A compounding pharmacy API integration on AffinityRx has five parts: read the catalog, get the clinician's approval, send one POST /v1/orders request that creates, signs and sends the order, keep your copy current from signed webhooks, and cancel or replace orders safely. A 200 response means AffinityRx accepted the order; it does not mean the pharmacy accepted or shipped it, which the webhooks tell you.
AffinityRx publishes this guide and the API it describes. The public docs are at docs.affinityrx.com, and the API version in these examples is 2026-11-01.
The integration at a glance
| Step | Request | What to keep |
|---|
| 1. Read the catalog | GET /v1/medications | med_ ID, accepted quantities, shippingOptions[].id |
| 2. Create practices (platforms only) | POST /v1/practices | prac_ ID |
| 3. Send the order | POST /v1/orders | ord_ ID, updatedAt, your Idempotency-Key |
| 4. Register a webhook endpoint | POST /v1/webhook-endpoints | Endpoint ID and signing secret |
| 5. Follow and recover | Webhooks, GET /v1/orders/{orderId}, GET /v1/orders?updatedAfter=… | Processed event IDs |
| 6. Cancel | POST /v1/orders/{orderId}/cancel | The status and cancelRequestedAt |
Every request sends Authorization: Bearer <key> and Affinity-Version: 2026-11-01. Each API key can make 25 requests per second, with bursts of 50.
How do Test and Live mode work?
The API key sets the mode. A sk_test_ key acts in Test; a sk_live_ key acts in Live. The API address is the same for both.
- Test orders go to a test system for each pharmacy. No medication is made, nothing ships, and Test orders are never billed.
- Test orders have the same validation, statuses and webhook events as Live orders.
- Only Perfect Rx Test orders finish on their own: they reach
processing when accepted, ship at about 10 minutes and deliver at about 30 minutes.
- Medication and shipping option IDs are the same in Test and Live.
Test mode is free and optional. An organization you create starts with Live access, so a team can send a real order the same day once it adds a card or bank account.
Step 1: How do you pick the medication?
GET /v1/medications?query=tirzepatide searches the name, ingredients, strength, form, route, brands, category and pharmacy name. A medication ID names one strength, one form, one fill size and one pharmacy, so the same drug at two pharmacies has two IDs. Add expand=variants to a medication read to get its other strengths, forms, fill sizes and pharmacies in one request.
Read these fields before you build the order:
| Field | Use it to |
|---|
price | The price of one fill, in cents |
quantities | The accepted quantity values; when the list is not empty, send one of them |
fill | What one fill holds, for example one 2 mL vial with 60 mg of an ingredient |
requirements | Which optional fields this medication needs, such as compoundingReason or daysSupply |
restrictedStates | Where the medication cannot ship |
shippingOptions | The shipping option IDs to send as shipping.optionId |
receivesAllergies | Whether the patient's allergies reach this pharmacy |
maxRefills | The largest refills value accepted |
A platform sends practiceId on catalog reads to quote the prices of one of its practices.
Step 2: How do you send an order?
Get the clinician's approval of the exact order in your product first. Then send one request. Save the Idempotency-Key with the order before the first attempt.
curl https://api.affinityrx.com/v1/orders \
-H "Authorization: Bearer $AFFINITY_API_KEY" \
-H "Affinity-Version: 2026-11-01" \
-H "Idempotency-Key: $ORDER_KEY" \
-H "Content-Type: application/json" \
--data @order.json
A shortened order.json, with synthetic Test data:
{
"practiceId": "prac_01j9z3k4m5n6p7q8r9s0t1v2w3",
"externalOrderId": "order-123",
"prescriber": { "npi": "1234567893", "firstName": "Sam", "lastName": "Lee" },
"signatureAttestation": true,
"shipping": { "optionId": "shp_…" },
"patient": {
"externalId": "patient-88",
"firstName": "Test",
"lastName": "Patient",
"dateOfBirth": "1988-04-02",
"sex": "female",
"phone": "+15125550100",
"email": "test.patient@example.com",
"address": {
"line1": "100 Example St",
"city": "Austin",
"state": "TX",
"postalCode": "78701"
},
"allergies": []
},
"prescriptions": [
{
"medicationId": "med_…",
"quantity": 6,
"refills": 0,
"directions": "Clinician-written directions",
"substitutionPermitted": true
}
]
}
The rules that matter most:
- One request, no draft step.
POST /v1/orders creates the order, signs it for the prescriber and sends it to the pharmacy. There are no public draft, sign or submit routes.
signatureAttestation: true states that the named prescriber approved and signed this order in your product. AffinityRx checks the NPI's format and check digit; it does not look up the name in the NPI registry.
- One pharmacy per order. An order has one practice, one patient, one prescriber and 1 to 20 prescriptions, all from one pharmacy.
practiceId is required with a platform key. A practice's own key can omit it.
- Shipping destination. Omit
shipping.destination to ship to the patient. Send { "type": "practice" } or { "type": "address", "address": {…} } to ship elsewhere.
- Refills.
refills authorizes pharmacy refills in addition to the first fill. If you send a new order for each monthly fill, send refills: 0 each time.
The response is 200 with the whole order: id, status (submitted), each prescription's pharmacy and price, shipping.option and total. All prices are integers in cents, and the order keeps them after later catalog changes.
What errors should you handle?
| Response | Meaning | What to do |
|---|
400 invalid_request | A missing or malformed field, or a missing Idempotency-Key | Fix the field listed in issues |
422 invalid_order | A field breaks a rule: a quantity not in quantities, a restricted state, a missing compounding reason, a placeholder such as "N/A" in a name | Fix the field listed in issues |
409 order_already_exists | externalOrderId already used for this practice | Use a new ID for a new order |
409 idempotency_key_reused | The same key with a different body | Use a new key for a different order |
409 payment_method_required | A Live order with no payment method or covering credit | Add a card or bank account in Settings, then Billing |
404 not_found | Unknown or archived practice, or a record of another organization or mode | Use an active practice you own |
A 400 or 422 does not use up the idempotency key. Each error body includes code, detail and requestId.
How do you retry without creating a duplicate order?
When a request times out, send it again with the same Idempotency-Key and the same body. AffinityRx returns 200 with the order the first request created, as it is now. Never make a new key for a retry: a new key with the same body is a new order.
Step 3: How do webhooks work?
Register a public https endpoint with POST /v1/webhook-endpoints. The response includes the signing secret once; store it. Register Test and Live endpoints separately, with a Test key and a Live key. Each mode allows up to 16 endpoints.
| Event | Sent when |
|---|
order.submitted | AffinityRx accepted the order and sends it to the pharmacy |
order.processing | The pharmacy has the order |
order.shipped | At least one package left the pharmacy |
order.delivered | Delivery is reported for every package AffinityRx knows about |
order.cancelled | The order was cancelled |
order.failed | The order could not proceed; read failureReason on the order |
order.updated | A shipment was added, changed or voided, or a cancel was refused |
AffinityRx sends no order.created, because your request already returned the order. Event payloads carry order status, shipments and tracking, not patient data. Read GET /v1/orders/{orderId} for the full order.
How do you verify the signature?
Each request has an Affinity-Signature header of the form t=<Unix seconds>,v1=<signature>.
- Read the raw body as bytes. Do not parse and re-serialize it.
- Compute HMAC-SHA256 of
${t}. followed by the raw body, with the whole whsec_… secret as the key, as lowercase hex.
- Compare it with
v1 in constant time.
- Reject the request if
t is more than 300 seconds from your clock.
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyAffinityWebhook(
rawBody: Uint8Array,
header: string | null | undefined,
secret: string,
now = Date.now() / 1000,
): boolean {
if (typeof header !== "string") return false;
const parts: Record<string, string | undefined> = Object.fromEntries(
header.split(",").map((part) => part.split("=", 2)),
);
const timestamp = Number(parts.t);
if (!Number.isInteger(timestamp) || Math.abs(now - timestamp) > 300) return false;
const expected = createHmac("sha256", secret)
.update(`${timestamp}.`, "utf8")
.update(rawBody)
.digest("hex");
const received = Buffer.from(parts.v1 ?? "", "utf8");
return received.length === expected.length && timingSafeEqual(received, Buffer.from(expected));
}
The docs also give Python, Go and Bash versions.
How fast must you answer, and what are the retries?
Answer with a 2xx status within 10 seconds: store the event, answer, then do the work. AffinityRx does not follow redirects. A failed delivery is retried up to 12 times, waiting 2^n minutes after attempt n (2, 4, 8 minutes and so on), capped at 24 hours, so the last attempt comes about 58 hours after the first. After you fix a broken receiver, POST /v1/webhook-endpoints/{id}/resend-failed queues failed deliveries from the last 30 days.
How do you handle duplicates and out-of-order events?
- Duplicates. An event can arrive more than once.
Affinity-Event-Id equals the event id. Store it before you do the work, process each ID once, and keep IDs for at least 30 days.
- Order of events. Each endpoint gets one order's events in sequence, but an older event can still arrive late after long failures. Keep the copy with the newest
updatedAt, which strictly increases with each change. Never let an old order.submitted replace a shipped copy.
- Race with the response.
order.submitted can arrive before the POST /v1/orders response. Match it by externalOrderId, or read the order.
- Missed events. Poll
GET /v1/orders?updatedAfter=… with a fixed cutoff and follow every nextCursor.
What happens after the order is sent?
| Status | Meaning |
|---|
submitted | AffinityRx accepted the order |
processing | The pharmacy received, accepted or is compounding it |
shipped | At least one package left the pharmacy; read shipments |
delivered | Every package AffinityRx knows about was delivered |
cancelled | The order was cancelled |
failed | Final; failureReason explains why |
awaiting_approval | Only for orders an AI assistant created; waits for an admin to click Send |
A pharmacy can skip a status, for example from submitted to shipped. Some pharmacies never report delivery, so a Live order can stay shipped. A pharmacy can send an order in more than one package; a later package arrives as order.updated and the order stays delivered. In Live mode, an order never becomes failed automatically, and a failed order always carries a written reason.
AffinityRx does not email or text patients. Your platform tells the patient about each status.
How do you cancel or replace an order safely?
- Send
POST /v1/orders/{orderId}/cancel with an Idempotency-Key.
- A cancel is not final until the order is
cancelled. While cancelRequestedAt is set, the pharmacy can still refuse. A refusal returns 409 cancel_refused or arrives as order.updated.
- A
processing order may already be filled. Perfect Rx refuses a cancel after filling and verification.
- A pharmacy can ship after it confirms a cancel, so a
cancelled order can still become shipped. Keep applying newer events.
- To replace a failed or cancelled order, read
failureReason, then send a new order with a new externalOrderId and a new Idempotency-Key.
AffinityRx never moves an order to another pharmacy on its own. A replacement at a different pharmacy is a new order that the prescriber approves and signs. See compounding pharmacy failover.
How do you test failure paths before going Live?
Perfect Rx Test orders accept a notes prefix on every prescription:
notes prefix | Result |
|---|
test_fail_ | The test pharmacy refuses the order; you get order.submitted, then order.failed |
test_cancel_refused_ | The order reaches processing; a cancel is refused with 409 cancel_refused or order.updated |
test_split_shipment_ | Two packages with separate tracking numbers; the second arrives as order.updated |
Before Live traffic, prove that your integration:
- returns the same order when you resend a request with the same key and body;
- applies a duplicate webhook once;
- ignores an older event that arrives after a newer one;
- rejects a webhook with a bad signature;
- waits for a cancel's outcome before it sends a replacement.
How do you go Live?
- Add a card or bank account in Settings, then Billing. Live orders are charged when AffinityRx sends them to the pharmacy.
- Create a Live API key in Settings, then API, on the Live tab.
- Platforms: turn on Live for each practice with
"liveEnabled": true and the Live key.
- Create a Live webhook endpoint with the Live key and store its new secret.
- Switch the key and secret in your configuration together, then send the first Live order.
Can an AI assistant use the same API?
Yes, through MCP at https://api.affinityrx.com/v1/mcp. An assistant such as ChatGPT or Claude signs in as a user and can read the catalog and prepare orders. Every order it creates waits as awaiting_approval until an admin clicks Send in AffinityRx. Orders sent with POST /v1/orders and an API key never wait for approval.
FAQs
How many API calls does it take to send a compounding order?
One. POST /v1/orders creates, signs and sends the order. Reading the catalog first is a separate read.
Can one order go to more than one pharmacy?
No. Every prescription in an order goes to one pharmacy. Send a separate order for each pharmacy.
Does a 200 response mean the pharmacy accepted the order?
No. It means AffinityRx accepted it. order.processing tells you the pharmacy has it.
What happens if my webhook endpoint is down?
AffinityRx retries each delivery up to 12 times over about 58 hours. After that, resend failed deliveries from the last 30 days, or poll orders with updatedAfter.
Does AffinityRx fail over to another pharmacy automatically?
No. The clinic or platform picks the pharmacy for each order. A canceled or unfilled order is refunded in full, and a replacement is a new order.
Which pharmacies can I order from through the API?
AffinityRx works with a network of 30+ vetted pharmacies. Today a new account can order from four: Perfect Rx, ProCompounding, Rx Route and National Health Rx.