Skip to Content
Payments

App Store

Verify and track Apple App Store purchases and subscriptions from your backend.

Usage

import { appstore } from "@dapplelight/signet-payments/appstore"
import { createPayments } from "@dapplelight/signet-payments"
import { app } from "./app"
import { db } from "./db"
import { env } from "./env"

export const apple = appstore({
  issuerId: env.APPSTORE_ISSUER_ID,
  keyId: env.APPSTORE_KEY_ID,
  privateKey: env.APPSTORE_P8, // In-App Purchase key, PKCS#8 PEM
  bundleId: "com.example.notes",
  appAppleId: 1234567890,
})

export const payments = createPayments({ gateways: [apple], db })

// The app sends the transaction id after a StoreKit purchase.
app.post("/purchases", async (c) => {
  const { transactionId, originalTransactionId, userId } = await c.req.json()
  await payments.verifyPurchase({ gateway: "appstore", id: transactionId, userId })
  return c.json(await payments.gateway("appstore").getSubscription(originalTransactionId))
})

// Server Notifications V2
app.post("/webhooks/appstore", (c) => payments.handleWebhook("appstore", c.req.raw))

Purchases happen on the device, so createCheckout is UNSUPPORTED.

API

ExportWhat it does
appstore(config)An AppStoreGateway named appstore over the App Store Server API
toAppStorePayment(transaction)Map a decoded transaction to a Payment (approximate: true)
checkConsumptionRequest(body)Return a clean ConsumptionRequest, or throw BAD_INPUT
APPLE_ROOT_CA_G3_SHA256Pinned fingerprint of Apple Root CA - G3
AppStoreConfig, AppStoreGateway, ConsumptionRequest, ConsumptionDeliveryStatusTypes

appstore(config)

OptionTypeDefault
issuerIdstringRequired. From App Store Connect, Users and Access, Keys
keyIdstringRequired
privateKeystringRequired. The .p8 contents
bundleIdstringRequired. Payloads for another bundle are rejected
appAppleIdnumberWhen set, production notifications must carry it
allowSandboxbooleanfalseWith sandbox: false, also accept Sandbox-signed data (a staging server)
trustedRootsstring[]Apple Root CA - G3SHA-256 fingerprints of trusted roots

Plus the shared sandbox (api.storekit-sandbox.apple.com), baseUrl, fetch, retries, retryDelayMs.

Extra methods

MethodWhat it does
decodeTransaction(jws)Verify a StoreKit jwsRepresentation and normalise it
transactionHistory(anyTransactionId, query?)Every transaction for the customer: { payments, revision?, hasMore }
refundHistory(anyTransactionId, revision?)Refunded transactions, same shape
sendConsumptionInfo(transactionId, body)Answer a CONSUMPTION_REQUEST notification

Restore purchases

import { ent } from "./entitlements"
import { payments } from "./payments"

export async function restore(userId: string, jwsRepresentation: string) {
  const { restored, refused } = await payments.restorePurchases({
    userId,
    purchases: [{ gateway: "appstore", signedTransaction: jwsRepresentation }],
  })
  for (const r of restored) if (r.subscription) await ent.applySubscription(r.subscription, { subject: userId }) // signet-db
  return refused
}

A purchase that is already another user's lands in refused with BAD_INPUT, a forged JWS with BAD_SIGNATURE. An outage throws, so retry the call.

Notes

  • Ids. A payment is a transactionId. A subscription is its originalTransactionId, which is also Payment.orderId, so renewals link to the first purchase.
  • Amounts are approximate. They are Apple's configured price, not settled revenue. Payments carry approximate: true and ledger postings use kind capture:approximate and refund:approximate. There is no settlement report, so they are never reconciled.
  • Status. past_due covers billing retry and grace period, and inGracePeriod: true means access continues. cancelled with a future currentPeriodEnd means renewal is off.
  • Refunds and cancelling are unsupported: customers ask Apple and cancel in their account settings.
  • Signatures. Every signed payload is verified up the x5c chain to Apple Root CA - G3, then the ES256 signature. Revocation (OCSP) is not checked.
  • Environments. A production adapter rejects Sandbox data unless allowSandbox: true. A sandbox: true adapter rejects Production data.
  • Events. SUBSCRIBED is subscription.created, DID_RENEW is subscription.charged, REFUND is refund.processed. A CONSUMPTION_REQUEST arrives as unknown with Apple's reason in raw.payload.data.

Examples

Answer a refund request

import { apple } from "./payments"

// `apple` is the value `appstore({...})` returned: the extra methods are on it, not on `payments.gateway()`.
const transactionId = "2000000123456789"
await apple.sendConsumptionInfo(transactionId, {
  customerConsented: true, // for a customer who did not consent, send nothing
  deliveryStatus: "DELIVERED",
  sampleContentProvided: false,
  consumptionPercentage: 12_000, // milliunits of a percent: 12%
  refundPreference: "DECLINE",
})