AffinityRx
Products
AffinityRx for Clinics30+ pharmacies in our network. One dashboard / API. Partners save an average of 30%.AffinityRx for TelehealthOne API. 30+ pharmacies in our network. Fewer backorders.AffinityRx for Whitelabel TelehealthOne pharmacy API for every brand you serve.AffinityRx for PharmaciesReach independent practices through one connection.
Company
About UsWhy we built AffinityRx and how it works.Our TeamThe people behind AffinityRx.Contact UsReach our support team directly.CareersDo your life's work at AffinityRx.Partner ProgramEarn 30% of our margin on referrals for 1 year.InvestorsThe business model, market, and team.
Resources
MedicationsThe full catalog and every medication page.PharmaciesPharmacy profiles, state coverage, and FDA actions.SolutionsHow AffinityRx works for each kind of clinic and brand.BlogGuides to compounding pharmacies, pricing, and ordering.
Products
AffinityRx for Clinics30+ pharmacies in our network. One dashboard / API. Partners save an average of 30%.AffinityRx for TelehealthOne API. 30+ pharmacies in our network. Fewer backorders.AffinityRx for Whitelabel TelehealthOne pharmacy API for every brand you serve.AffinityRx for PharmaciesReach independent practices through one connection.
Company
About UsWhy we built AffinityRx and how it works.Our TeamThe people behind AffinityRx.Contact UsReach our support team directly.CareersDo your life's work at AffinityRx.Partner ProgramEarn 30% of our margin on referrals for 1 year.InvestorsThe business model, market, and team.
Resources
MedicationsThe full catalog and every medication page.PharmaciesPharmacy profiles, state coverage, and FDA actions.SolutionsHow AffinityRx works for each kind of clinic and brand.BlogGuides to compounding pharmacies, pricing, and ordering.
Products
AffinityRx for Clinics30+ pharmacies in our network. One dashboard / API. Partners save an average of 30%.AffinityRx for TelehealthOne API. 30+ pharmacies in our network. Fewer backorders.AffinityRx for Whitelabel TelehealthOne pharmacy API for every brand you serve.AffinityRx for PharmaciesReach independent practices through one connection.
Company
About UsWhy we built AffinityRx and how it works.Our TeamThe people behind AffinityRx.Contact UsReach our support team directly.CareersDo your life's work at AffinityRx.Partner ProgramEarn 30% of our margin on referrals for 1 year.InvestorsThe business model, market, and team.
Resources
MedicationsThe full catalog and every medication page.PharmaciesPharmacy profiles, state coverage, and FDA actions.SolutionsHow AffinityRx works for each kind of clinic and brand.BlogGuides to compounding pharmacies, pricing, and ordering.
PricingDocs
Talk to salesGet started
AffinityRx
Talk to salesGet started
Home/Blog/Compounding pharmacy API integration guide: orders, webhooks and Test mode

Compounding pharmacy API integration guide: orders, webhooks and Test mode

WebhooksShipped

How to integrate a compounding pharmacy API: read the catalog, send one signed order request, verify webhooks, handle retries and cancels, and go Live.

Get started

By Tim Yoon. Published September 30, 2026. Updated November 22, 2026

Keep reading

  • Pharmacy Routing vs E-Prescribing: What Is the Difference for Compounded Medications?Engineering
  • Surescripts and DoseSpot vs Compounding Pharmacy APIs for TelehealthEngineering
  • AffinityRx Portal vs Headless API: Which Setup Fits Your Telehealth Brand?Engineering
  • Bulk Orders and Refills at Scale on AffinityRx: Limits, Retries and APIAffinityRx
PreviousCompounding pharmacy failover: how to plan backup pharmacies without duplicate ordersNextBuild vs. buy: multi-pharmacy integrations for telehealth

Every compounding pharmacy in one dashboard

Sign up free to compare prices across the pharmacies live on AffinityRx.

Get started

On this page

  1. The integration at a glance
  2. How do Test and Live mode work?
  3. Step 1: How do you pick the medication?
  4. Step 2: How do you send an order?
  5. What errors should you handle?
  6. How do you retry without creating a duplicate order?
  7. Step 3: How do webhooks work?
  8. What happens after the order is sent?
  9. How do you cancel or replace an order safely?
  10. How do you test failure paths before going Live?
  11. How do you go Live?
  12. Can an AI assistant use the same API?
  13. FAQs
  14. Get started
AffinityRx

30+ pharmacies in our network. One dashboard / API. Save time and money.

Verify Approval for www.affinityrx.com

Products

  • Clinics
  • Telehealth
  • Whitelabel Telehealth
  • Pharmacies
  • Pricing

Company

  • About Us
  • Our Team
  • Contact Us
  • Careers
  • Partner Program
  • Investors
  • Brand assets

Resources

  • Medications
  • Pharmacy directory
  • Solutions
  • Blog
  • Features
  • Challenges
  • How to choose a pharmacy
  • How to choose an ordering platform

Developers

  • API docs
  • Build an integration
  • Webhooks
  • MCP
  • Changelog

Support

  • Call us: 714-254-5656
  • Email us
  • Service availability
  • Terms of Service
  • Privacy Policy
© 2026 Incubator LLC d/b/a AffinityRx · support@affinityrx.com
Call 714-254-5656Get started

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

StepRequestWhat to keep
1. Read the catalogGET /v1/medicationsmed_ ID, accepted quantities, shippingOptions[].id
2. Create practices (platforms only)POST /v1/practicesprac_ ID
3. Send the orderPOST /v1/ordersord_ ID, updatedAt, your Idempotency-Key
4. Register a webhook endpointPOST /v1/webhook-endpointsEndpoint ID and signing secret
5. Follow and recoverWebhooks, GET /v1/orders/{orderId}, GET /v1/orders?updatedAfter=…Processed event IDs
6. CancelPOST /v1/orders/{orderId}/cancelThe 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:

FieldUse it to
priceThe price of one fill, in cents
quantitiesThe accepted quantity values; when the list is not empty, send one of them
fillWhat one fill holds, for example one 2 mL vial with 60 mg of an ingredient
requirementsWhich optional fields this medication needs, such as compoundingReason or daysSupply
restrictedStatesWhere the medication cannot ship
shippingOptionsThe shipping option IDs to send as shipping.optionId
receivesAllergiesWhether the patient's allergies reach this pharmacy
maxRefillsThe 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?

ResponseMeaningWhat to do
400 invalid_requestA missing or malformed field, or a missing Idempotency-KeyFix the field listed in issues
422 invalid_orderA field breaks a rule: a quantity not in quantities, a restricted state, a missing compounding reason, a placeholder such as "N/A" in a nameFix the field listed in issues
409 order_already_existsexternalOrderId already used for this practiceUse a new ID for a new order
409 idempotency_key_reusedThe same key with a different bodyUse a new key for a different order
409 payment_method_requiredA Live order with no payment method or covering creditAdd a card or bank account in Settings, then Billing
404 not_foundUnknown or archived practice, or a record of another organization or modeUse 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.

EventSent when
order.submittedAffinityRx accepted the order and sends it to the pharmacy
order.processingThe pharmacy has the order
order.shippedAt least one package left the pharmacy
order.deliveredDelivery is reported for every package AffinityRx knows about
order.cancelledThe order was cancelled
order.failedThe order could not proceed; read failureReason on the order
order.updatedA 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>.

  1. Read the raw body as bytes. Do not parse and re-serialize it.
  2. Compute HMAC-SHA256 of ${t}. followed by the raw body, with the whole whsec_… secret as the key, as lowercase hex.
  3. Compare it with v1 in constant time.
  4. 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?

StatusMeaning
submittedAffinityRx accepted the order
processingThe pharmacy received, accepted or is compounding it
shippedAt least one package left the pharmacy; read shipments
deliveredEvery package AffinityRx knows about was delivered
cancelledThe order was cancelled
failedFinal; failureReason explains why
awaiting_approvalOnly 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?

  1. Send POST /v1/orders/{orderId}/cancel with an Idempotency-Key.
  2. 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.
  3. A processing order may already be filled. Perfect Rx refuses a cancel after filling and verification.
  4. A pharmacy can ship after it confirms a cancel, so a cancelled order can still become shipped. Keep applying newer events.
  5. 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 prefixResult
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?

  1. Add a card or bank account in Settings, then Billing. Live orders are charged when AffinityRx sends them to the pharmacy.
  2. Create a Live API key in Settings, then API, on the Live tab.
  3. Platforms: turn on Live for each practice with "liveEnabled": true and the Live key.
  4. Create a Live webhook endpoint with the Live key and store its new secret.
  5. 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.

Get started

Sign up free, read the API docs, and send a first order the same day with a card or bank account at checkout. A demo is optional; request one here. See also AffinityRx for telehealth platforms and the API page.