Skip to content

Node.js and PHP SDKs

Flint's official server SDKs let your backend call the Flint API with a typed method for every operation: @flintpay/node for TypeScript and JavaScript, and flintpay/flint for PHP. Both are generated from the same API contract as the API reference, so methods, parameters, and response fields use the names you see there. The latest stable release, 7.0.0, covers 574 operations.

The SDKs handle the parts of an integration that are easy to get wrong over raw HTTP: they keep amounts out of floating point, send and reuse idempotency keys, retry only when a retry can't repeat an action, follow pagination cursors, and verify webhook signatures.

npm

@flintpay/node

Shell
npm install @flintpay/node@next

Node.js 22.3+ as ESM, or 22.12+ to require() it from CommonJS. TypeScript projects need TypeScript 5.9+ with NodeNext module resolution and @types/node 22.16+. Plain JavaScript works too. Package on npm.

Packagist

flintpay/flint

Shell
composer require "flintpay/flint:^8.0@beta"

PHP 8.2+ with the curl and json extensions, and no framework dependency. JWT webhook verification also needs openssl. Package on Packagist.

These commands install the 8.0 prerelease, and the samples below run on it. The 7.x releases differ in method names, argument shapes, errors, and number types; the migration guide lists every change. Until 8.0.0 is stable, the Node method names in the API reference are those of 7.0.0, so check a name against the SDK's own REFERENCE.md if it doesn't exist.

Every Flint API key is secret, so the SDKs run on your server, a worker, or another trusted backend, never in browser or mobile code.

Create a client#

A client holds your credential and sends every request to https://api.withflintpay.com. Constructing one makes no network calls.

TypeScript
import { Client } from "@flintpay/node";

const flint = new Client({ apiKey: process.env.FLINT_API_KEY! });

Call await flint.close() when your process is done with the client, to release any open event streams.

Set the base URL#

A client sends requests to https://api.withflintpay.com unless you set baseUrl. Set it to reach another API server, such as a local development server or a test double. A webhook check reads Flint's keys from the same server.

TypeScript
const flint = new Client({
  apiKey: process.env.FLINT_API_KEY!,
  baseUrl: process.env.FLINT_BASE_URL, // undefined uses https://api.withflintpay.com
});

A plain http:// base URL is refused unless you also set allowInsecureHttp: true, which is meant for localhost only.

Choose a key#

The key decides where requests run. A flint_test_ key runs in test mode against the sandbox it belongs to, and a flint_live_ key runs against your live account. Both use the same hostname and the same code, so moving to production is a change of key.

Default credentials#

When you pass no credential, the client finds one in the environment the first time it sends a request:

  1. FLINT_API_KEY, an API key.
  2. FLINT_ACCESS_TOKEN, an access token you obtained elsewhere. Setting both variables fails with ambiguous_credentials.
  3. A workload identity, when FLINT_WORKLOAD_IDENTITY_ID is set. In GitHub Actions, grant the job permissions: id-token: write and the SDK requests the runner's OIDC token and exchanges it for a short-lived Flint token. On other platforms, put the OIDC token in FLINT_OIDC_TOKEN or the path of a token file in FLINT_OIDC_TOKEN_FILE. The SDK caches the Flint token and refreshes it before it expires.

So with FLINT_API_KEY set, new Client() in Node or new Client(new ClientOptions()) in PHP is enough. A credential you pass always wins over the environment.

An app that calls Flint for many merchants, such as a partner app, should set ambientCredentials: false and pass each merchant's credential explicitly. A request that is missing a merchant's credential then fails instead of running under your app's own key.

Partner app helpers#

A platform that installs a partner app on its merchants' accounts calls the API with partner app tokens. The Node and PHP SDKs include helpers for the OAuth steps, so you don't write the assertion signing, token caching, or 401 retry yourself. They are in the 8.0 prerelease of the SDKs, the version the install commands above fetch. Node imports them from @flintpay/node/custom/partner-oauth.js. PHP has them in the Flint\Partner namespace.

HelperWhat it does
buildAuthorizeUrlMakes no request. Returns the consent screen URL for a merchant's browser, a random state, and the PKCE codeVerifier. Store state and codeVerifier with the attempt on your server.
parseAuthorizeCallbackCompares the callback's state with the stored one and returns the code. Throws AuthorizeCallbackError with error set to state_mismatch, the callback's OAuth error such as access_denied, or invalid_request.
privateKeyJwtSigns a new client assertion for every request with a key you registered. Node signs ES256, ES384, PS256, RS256, and EdDSA. For a workload_identity credential, return your OIDC provider's token from getAssertion() instead.
exchangeCodeExchanges the callback's code, with a fresh assertion. The code expires after 5 minutes and works once.
partnerAppTokensMints and caches partner app tokens for one mode. app() is an app-level token and forMerchant(merchantId) is a merchant-bound one. See Mint and cache tokens with the SDK.
revokeTokenRevokes a partner app token with a fresh assertion.

Send the merchant to install, then exchange the code on your backend:

TypeScript
import { Client } from "@flintpay/node";
import {
  buildAuthorizeUrl,
  exchangeCode,
  parseAuthorizeCallback,
  privateKeyJwt,
} from "@flintpay/node/custom/partner-oauth.js";

const clientAssertion = privateKeyJwt({
  clientId: process.env.FLINT_CLIENT_ID!,
  privateKey: process.env.FLINT_PRIVATE_KEY_PEM!,
  algorithm: "ES256",
  keyId: "backend-2026-10",
});

// 1. Build the URL, save state and codeVerifier, then redirect the browser to url.
const { url, state, codeVerifier } = buildAuthorizeUrl({
  clientId: process.env.FLINT_CLIENT_ID!,
  redirectUri: "https://example.com/flint/oauth/callback",
  mode: "live",
  scope: ["manage_orders", "read_customers"],
});

// 2. On the callback, check state and exchange the code.
const { code } = parseAuthorizeCallback(callbackUrl, { state });
const install = await exchangeCode(new Client({ ambientCredentials: false }), {
  code,
  redirectUri: "https://example.com/flint/oauth/callback",
  codeVerifier,
  clientAssertion,
});

The exchange activates the install and returns a partner app token bound to that merchant, with no refresh token. Store the IDs it returns as Exchange the code describes, and mint later tokens with partnerAppTokens. Omit scope to request the app's default permissions. sandboxId (test mode only), merchantId, and baseUrl are optional on buildAuthorizeUrl.

Exchange the codes from a merchant signup#

A merchant signup returns authorization codes without an authorize URL, and its exchange sends no redirect_uri, which exchangeCode requires. Call oauth.exchangeToken and add the client authentication fields with clientAuthentication. PHP has OAuth::clientAuthentication($clientAssertion) for the same fields.

TypeScript
import { Client } from "@flintpay/node";
import { clientAuthentication, privateKeyJwt } from "@flintpay/node/custom/partner-oauth.js";

const clientAssertion = privateKeyJwt({
  clientId: process.env.FLINT_CLIENT_ID!,
  privateKey: process.env.FLINT_PRIVATE_KEY_PEM!,
  algorithm: "ES256",
  keyId: "backend-2026-10",
});

const token = await new Client({ ambientCredentials: false }).oauth.exchangeToken({
  grant_type: "authorization_code",
  code: liveAuthorizationCode,
  code_verifier: codeVerifier,
  ...(await clientAuthentication(clientAssertion)),
});

Sign a new assertion for each exchange: clientAuthentication does, because each assertion works once.

Take a payment#

Create an order, open a Flint-hosted checkout for it, send the buyer there, and read the paid order back.

TypeScript
const order = await flint.orders.create(
  {
    line_items: [
      {
        type: "custom",
        name: "Design consultation",
        quantity: 1,
        unit_price_money: { amount: "2500", currency: "USD" },
        fulfillment: { requirement: "none" },
      },
    ],
  },
  { idempotencyKey: "first-payment-order-001" },
);

const session = await flint.checkoutSessions.create(
  {
    type: "order",
    order_id: order.order_id,
    redirects: {
      success_url: "https://example.com/thanks",
      cancel_url: "https://example.com/checkout",
    },
  },
  { idempotencyKey: "first-payment-checkout-001" },
);

// Redirect the buyer to this URL.
console.log(session.url);

// After they pay:
const paid = await flint.orders.get(order.order_id);
console.log(paid.payment_status); // "paid"

orders.create returns the order with its totals computed. checkoutSessions.create returns the session, and its url is the hosted page that collects the order's balance. Pay with a test card and orders.get reports payment_status as paid. In production, fulfill from the order.paid webhook, not from the success redirect, because a buyer can close the tab before the redirect happens. Check the order's dispute_status before you fulfill (access rules).

Testing walks through the same three calls over raw HTTP, with the response bodies. To run them in a web app with the webhook that grants access, follow Accept a payment with Next.js, which has an Express tab.

What a call looks like#

Every method has the same shape:

  • Path IDs first, in URL order. flint.orders.get(orderId), flint.customers.update(customerId, { email }), flint.orders.updateLineItem(orderId, lineItemId, { quantity }).
  • Then one flat params object. Body fields and query parameters sit together under the API's wire names, such as unit_price_money and page_size, never camelCase. When a body has alternatives, include the field that picks one, such as type on checkoutSessions.create or refund_type on refunds.create. The SDK rejects fields the operation doesn't declare before sending anything.
  • Then request options. A plain object in Node, a RequestOptions in PHP. Idempotency keys, timeouts, and per-request credentials go here; see Request options.

Operations whose body takes one of several shapes, such as orders.pay and paymentIntents.confirm, follow the same pattern. The params object holds the field that picks the shape, such as action on orders.pay: flint.orders.pay(orderId, { action: "pay", ... }, { idempotencyKey }).

Methods return the resource, not the response envelope: orders.get returns the order. Operations whose response names more than one object return all of them: orders.pay returns { order, order_payment_attempt }. list returns one page, { data, next_page_token }. Binary downloads, such as an invoice PDF, return { data, raw } with the bytes in data and the status and headers on lastResponse. The Node reference and PHP reference give each method's signature and return.

Read the HTTP response#

Every result carries a lastResponse with the response status, headers, requestId, and the complete decoded body. In Node it is a property that JSON.stringify and spreading skip. In PHP it is the lastResponse() method.

TypeScript
const order = await flint.orders.get(orderId);

order.lastResponse.status;    // 200
order.lastResponse.requestId; // include this when you contact Flint about a request
order.lastResponse.body.meta; // the full response envelope

Use it when the status code carries meaning. Create-or-return operations, such as fulfillments.createEvent and customers.create, return 201 when Flint created the resource and 200 when it returned an existing one. body.meta.idempotency_replayed is true when the response replays an earlier request with the same idempotency key.

Exact money#

Money amounts are strings in both SDKs: "2500", not 2500. They are still integers in the currency's minor unit, so "2500" is $25.00, but an amount never passes through floating point on its way to Flint or back. On the wire these are JSON integers; the SDK converts them. Raw HTTP requests must send numbers.

Everything else that counts something is a plain number: quantity, version, expected_version, counts, and seconds. Both SDKs check that they fit in the safe integer range, up to 2^53 - 1 either side of zero, and throw InvalidInputError before sending when they don't. A quantity sent as a string such as "1" fails the same check.

In TypeScript, a Money amount has the type `${bigint}`. Pass a string literal such as "2500" or a bigint such as BigInt(totalMinorUnits). A plain string, such as the result of String(total), doesn't type-check. To add amounts, convert them with BigInt(money.amount) and sum the bigint values. Money and amounts covers minor units and currencies.

Errors#

A failed call throws SdkError. Its most important field is outcome, which says whether the request could have changed anything at Flint:

outcomeWhat happenedWhat to do
not_sentThe SDK rejected the call before sending it, for example a missing required field or idempotency key. Nothing changed.Fix the input and call again.
responseFlint answered with an error. code is the API's error code, such as VERSION_CONFLICT.Branch on code.
unknownThe request may have reached Flint, and the SDK's own retries didn't settle it.Call again with the same input and error.idempotencyKey, or read the resource back first.
TypeScript
import { SdkError } from "@flintpay/node";

try {
  await flint.refunds.create(
    {
      refund_type: "amount",
      payment_intent_id: paymentIntentId,
      amount_money: { amount: "500", currency: "USD" },
      reason: "requested_by_customer",
    },
    { idempotencyKey: savedKey },
  );
} catch (error) {
  if (!(error instanceof SdkError)) throw error;
  console.error(error.code, error.status, error.requestId);
  if (error.outcome === "unknown") {
    // The refund may exist. Retry with error.idempotencyKey, or read it back first.
  }
}

The class follows the HTTP status, so you can catch one category with instanceof: errors.NotFoundError, errors.ConflictError, errors.RateLimitError, and errors.PermissionError in Node, and the same names in Flint\Errors in PHP. ApiError is the parent of every error Flint answered, so catch it after the specific classes. ConnectionError covers a request that got no usable response, including timeouts. A class never depends on the error code, so a new code from Flint doesn't change which class you catch.

The API's error fields are properties of the error: param, type, details (always an array), remediation, docUrl, and requestId. retryAfterMs is set when Flint sent Retry-After. The code property holds Flint's error code in both languages. In PHP, getCode() returns the same code, and the HTTP status is $error->status.

Some outcomes are not errors. A declined card arrives as a payment attempt in a successful response, which Declines and payment attempts covers. A refund the processor rejects is still a created refund. The response can already carry status: "failed"; if it is pending, follow the refund with a read or event, as Refunds describes.

Retries and idempotency#

A call retries on its own only when the retry can't run your request twice: reads retry, and so do writes that carry an idempotency key. How a write gets its key depends on the operation.

The operation's keyExamplesWhat the SDK does
Requiredrefunds.create, orders.pay, paymentIntents.createRequires your key. TypeScript won't compile the call without idempotencyKey, and PHP throws SdkError with outcome: "not_sent".
OptionalMost writes, such as orders.create and customers.updateUses your key if you pass one. Otherwise it generates one before the first attempt and sends it on every retry of that call.
Not acceptedPreviews and other writes that only compute an answerSends the request once. Passing idempotencyKey fails with outcome: "not_sent".

Operations that move money or stock require your key because the key has to outlive one call. Save it with the action before the first attempt, and every later attempt, from any process, sends the same key and gets the original result instead of running the action again. A key the SDK generates lasts only for one call.

TypeScript
await flint.refunds.create(params, { idempotencyKey: refundJob.idempotencyKey });

The SDK retries when no response arrived, and when Flint's error has remediation.retry: "same_request", which covers rate limits, a request still in progress under the same key, and most 5xx errors. It waits at least as long as Retry-After when Flint sends it, and backs off with jitter otherwise. A call makes at most 3 attempts and stops at its deadlineMs. Errors with remediation.retry of after_refresh or none reach your code on the first attempt. Set maxAttempts: 1 to turn retries off.

When the attempts run out with outcome: "unknown", the error's idempotencyKey is the key that was sent. Call again with that key and the same input, or follow the operation's recovery path in Idempotency. A new key could run the action twice.

Flint accepts a key on 424 writes and requires one on 39 of them. Idempotency lists them and covers choosing keys and how long Flint keeps them.

Request options#

The last argument to any method sets options for that call only. timeoutMs, deadlineMs, maxAttempts, and the credential options also work on the client, where they set the default for every call.

OptionWhat it does
idempotencyKeySent as Idempotency-Key. See Retries and idempotency.
timeoutMsLimit for one attempt, including reading the body. Default 10000, or 150000 for the operations listed below.
deadlineMsLimit for the whole call, including retries and the waits between them. A duration, not a timestamp. Default 30000, or 300000 for the operations listed below. In a listItems or listPages iteration, each page fetch gets its own deadline.
maxAttemptsTotal attempts, including the first, up to the operation's limit of 3. 1 turns retries off.
maxPages, maxItemsCaps for a listItems or listPages iteration. maxPages defaults to 1000.
headersExtra headers for this request. The SDK controls the credential and Flint-Version headers.
apiKeyA different API key for this call. The other credential shortcuts work here too.
signal (Node), cancellation (PHP)Stops the local work. A write Flint already received may still complete.

Request option defaults#

A request's own option wins over the client's, the client's wins over the operation's default, and the operation's default wins over the global default of 10000 for timeoutMs and 30000 for deadlineMs. Payment and order writes take longer, so 23 operations default to 150000 for timeoutMs and 300000 for deadlineMs. They include orders.pay, orders.create, paymentIntents.create, paymentIntents.confirm, paymentIntents.capture, and refunds.create. If your own server enforces a request budget, make it longer than the deadline these calls can use, or set timeoutMs and deadlineMs on the call. A timeoutMs or deadlineMs set on the client applies to these operations too, so a client set to 10000 cuts a payment off after 10 seconds. The Node and PHP runtime guides list every operation.

Pagination#

Every list operation has an Items companion that follows next_page_token for you and yields one resource at a time, with your filters applied to every page:

TypeScript
for await (const order of flint.orders.listItems(
  { payment_status: ["paid"], page_size: 100 },
  { maxItems: 1000 },
)) {
  console.log(order.order_id, order.pricing_amounts.total_money.amount);
}

Iteration is lazy: the SDK fetches the next page only when you reach it. listPages yields whole pages instead, and list fetches a single page. Pagination covers sorting, filters, and what a cursor holds.

Verify a webhook#

New webhook endpoints sign each delivery with a Flint JWT, which you verify against Flint's public keys and your endpoint's ID. There is no shared secret. The SDK checks the token, its issuer, audience, and lifetime, and that it signs the exact body you received. It fetches and caches Flint's keys from /.well-known/jwks.json on the client's base URL, https://api.withflintpay.com unless you set another.

TypeScript
import express from "express";
import { SdkError } from "@flintpay/node";

const app = express();

// Register before express.json(), so the handler gets the raw bytes.
app.post("/webhooks/flint", express.raw({ type: "application/json" }), async (req, res) => {
  let verified;
  try {
    verified = await flint.verifyWebhookAsync(req.body, req.headers, {
      endpointIds: [process.env.FLINT_WEBHOOK_ENDPOINT_ID!],
    });
  } catch (error) {
    if (error instanceof SdkError && error.code === "webhook_jwks_unavailable") {
      return res.sendStatus(503); // Flint's keys couldn't be loaded: ask Flint to retry.
    }
    return res.sendStatus(400);
  }

  if (verified.known) {
    // verified.event is typed by its event_type.
  }
  // Record the event durably, then acknowledge it.
  res.sendStatus(200);
});

Pass the raw request body. Verifying JSON you parsed and serialized again fails, because the signature covers the exact bytes. On a failed check the SDK throws SdkError with a code such as webhook_invalid_token, webhook_invalid_audience, webhook_token_expired, or webhook_body_mismatch; answer 400 and process nothing.

known is false for an event the SDK doesn't recognize, usually an event type newer than your SDK release, and reason says why. The delivery is still authentic. Store it for review rather than treating it as handled.

HMAC endpoints#

An endpoint with hmac in its signing_methods signs deliveries with a shared secret instead, in the Standard Webhooks format. Flint returns the secret once, when you create the endpoint:

TypeScript
const endpoint = await flint.webhookEndpoints.create({
  url: "https://example.com/webhooks/flint",
  enabled_events: ["order.paid"],
  signing_methods: ["hmac"],
});

// Store endpoint.secret in your secret manager now. Reads never return it.

Verify those deliveries with verifyWebhook and a list of secrets. Pass the current and previous secret while you rotate:

TypeScript
const { event, known } = flint.verifyWebhook(req.body, req.headers, [
  process.env.FLINT_WEBHOOK_SECRET!,
]);

It checks the webhook-id, webhook-timestamp, and webhook-signature headers and rejects a timestamp more than 300 seconds from your clock. To add HMAC to an existing endpoint, see Change signing methods.

Events that flint listen forwards to localhost are Flint-signed JWT deliveries, so verify them with verifyWebhookAsync (Node) or verifyWebhookDelivery (PHP), using the whep_... endpoint ID the CLI prints as FLINT_WEBHOOK_ENDPOINT_ID. They don't use the shared secret above.

Verification is not deduplication. Retries and resends deliver the same event more than once; Webhooks covers storing webhook_event_id so you process each event once.

Credential modes#

Most operations take your API key, which is the merchant mode. Operations that act for a signed-in buyer, a checkout, an invoice, or an account still being set up take a different credential. Each authenticated mode has a shortcut option that selects it and supplies its token, on the client or on one request.

ModeShortcutCredentialUsed by
merchantapiKeyYour API key, or an access tokenMost of the API
customercustomerTokenA customer session secret, flint_cses_...The /v1/me operations, under flint.me
checkoutcheckoutTokenThe checkout_auth_token from a checkout sessionThat session's checkout and order calls, when you build your own checkout
invoiceinvoiceTokenThe access token from an invoice's public URLThat invoice's buyer detail, PDF, and checkout session
onboardingonboardingTokenThe token from POST /v1/onboarding/verify-emailSetting up an account before it has an API key, in its default sandbox
noneNo credentialshops.getPublic, shops.getListingPublic, and shops.resolve

For these public shop operations, omit the key and set ambientCredentials: false so the SDK can't pick up a key from your server's environment.

TypeScript
import { Client } from "@flintpay/node";

const publicFlint = new Client({ ambientCredentials: false });
PHP
use Flint\{Client, ClientOptions};

$publicFlint = new Client(new ClientOptions(ambientCredentials: false));
TypeScript
const myOrders = await flint.me.listOrders({}, { customerToken: sessionSecret });

const order = await flint.orders.get(orderId, undefined, {
  checkoutToken: checkoutAuthToken,
});

In TypeScript, each method accepts only the modes its operation allows, so passing customerToken to a merchant-only method doesn't compile. A request sends one credential: give one shortcut, or authMode with credentials, not both. Authentication covers each credential and what it can reach.

Versions and upgrades#

Each SDK release is generated for one API version and sends it as Flint-Version on every request, so a response shape doesn't change under a deployed app, except for the breaking changes that currently ship into supported versions in place. The latest stable release, 7.0.0, of both packages targets API version 2026-09-07. To move to a new API version, upgrade the SDK. The version table shows which release targets which API version, and API versions and upgrades covers what changes between versions.

Major SDK releases can change method signatures. Before you upgrade across one, read the migration guide. The changes most integrations notice:

  • 8.0.0 gives every method the same arguments, path IDs then params then options, so orders.pay takes (orderId, { action, ... }, options). Errors follow the HTTP status and carry code and requestId directly, kind and meta are gone, and counters such as quantity and version are numbers while money amounts stay strings. Results carry lastResponse instead of a WithResponse companion, and 98 methods have new names.
  • 7.0.0 calls the API's current paths, such as /v1/sandboxes. A few methods have new names, such as me.listPaymentIntents for me.listPayments, and the old names still work. Bodies with alternatives need the field that picks one, such as type on invoices.create, and the SDK rejects undeclared fields.
  • 6.0.0 made required idempotency keys part of the TypeScript signatures, and made reads and keyed writes retry on their own. Remove your own retry loop around SDK calls, or set maxAttempts: 1. It also added JWT webhook verification.
  • 5.1.0 added default credentials from the environment.

Examples for every operation#

Each package ships a runnable script per operation, named for its resource and method: node/examples/orders-create.mjs and php/examples/orders-create.php in flint-pay/flint-sdks. The generated references document every method's parameters, return, and accepted credential modes.

Node referenceEvery method on @flintpay/node, with parameters, returns, and examples. (opens in a new tab)PHP referenceEvery method on flintpay/flint, with parameters, returns, and examples. (opens in a new tab)

Next steps#

Was this helpful?