Skip to content

· 16 min read · Nadeera Silva

Payments

App Store Server API 4040010: Fix Transaction Id Not Found

Learn why the App Store Server API returns 4040010 (Transaction id not found), which environment to call, and how to fix it with tested Node code.

A hand searching an oak card catalog box with two open drawers of blank index cards, the lower drawer empty, beside a phone with a blurred screen, like a backend looking up a transaction in production and sandbox

App Store Server API error 4040010 means Apple looked for the transaction ID you sent and could not find it. Your Node backend calls Get Transaction Info, usually right after a Flutter or Swift app finishes a StoreKit 2 purchase, and gets back a 404 with {"errorCode":4040010,"errorMessage":"Transaction id not found."}. The purchase is usually real. In most cases the request went to the wrong environment, or it was signed for the wrong bundle ID. Below are the causes, Apple's documented lookup order and a tested Node module that never unlocks content on a miss, plus the sibling errors 4040005 and 4040006.

Quick answer

Error 4040010 (TransactionIdNotFoundError) means the transaction ID is not in the environment you called for the bundle ID in your JWT. Call the environment that created the transaction, which you can read from the environment field of the signed transaction. If you don't know it, call production first, then sandbox on 4040010. If sandbox also returns 4040010, the ID is in neither environment, and Apple says not to unlock the content.

What this means for your app or business

  • What the customer sees. They paid (or a tester or App Review paid in sandbox) and the app still shows the paywall. That means support tickets, refund requests and, during review, a possible rejection.
  • Why it happens. Purchases from TestFlight, from development builds with a sandbox account and from App Review live in Apple's sandbox, not in production. A server that only asks production can't find them.
  • The risk of a careless fix. Unlocking content whenever Apple can't find a transaction would give away paid features. The safe fix routes each lookup to the right environment and treats "not found" as "not paid".
  • How long it takes. For a backend that already uses Apple's server library, the change below is usually a few hours plus testing.
  • When to get help. If your app sells subscriptions and you can't say which environment each stored transaction belongs to, ask a developer to fix that before your next release.

What does App Store Server API error 4040010 look like?

Apple returns HTTP 404 with a JSON body. With the official Node library, the call throws an APIException:

APIException {
  httpStatusCode: 404,
  apiError: 4040010,            // APIError.TRANSACTION_ID_NOT_FOUND
  errorMessage: 'Transaction id not found.'
}

Apple has two close relatives of this error, and there is one look-alike that is not a lookup error at all:

ResponseNameMessageWhere it comes fromWhat to do
404, 4040010TransactionIdNotFoundErrorTransaction id not found.Get Transaction Info, Get Transaction History, Get All Subscription Statuses, Send Consumption Information and other endpoints that take a transaction IDCheck the JWT bundle ID and the environment; don't unlock
404, 4040005OriginalTransactionIdNotFoundErrorOriginal transaction id not found.Endpoints that take an original transaction ID, such as Extend a Subscription Renewal Date and Set App Account TokenSame checks as 4040010; don't unlock
404, 4040006OriginalTransactionIdNotFoundRetryableErrorOriginal transaction id not found. Please try again.Documented as an error object; no current endpoint page lists itRetry with backoff, then treat as not found
401Unauthenticated (plain text, no code)noneAny endpointA JWT, key or release problem, not a missing transaction

The library's APIError enum in version 3.1.0 has all three codes: TRANSACTION_ID_NOT_FOUND (4040010), ORIGINAL_TRANSACTION_ID_NOT_FOUND (4040005) and ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE (4040006).

Why does Get Transaction Info say "Transaction id not found"?

Apple's TransactionIdNotFoundError page lists two things to check, and adds a rare third case:

  1. The `bid` in your JWT is not the app that owns the transaction. This happens when one backend serves several apps, a white-label build or a staging bundle ID such as com.example.app.dev, and the server signs every request with the main app's bundle ID.
  2. You called the wrong environment. Transactions made in sandbox exist only in sandbox. Apple's sandbox testing guide says apps you download from TestFlight always run in the sandbox environment, and so do development builds signed in with a Sandbox Apple Account. Apple's older receipt validation guide also tells you to use sandbox "while your app is in review", so App Review purchases are sandbox purchases too.
  3. Rare cases. Apple says that in rare cases you can get this error for a transaction ID that returned data before. If you can't resolve it with the checks above, Apple's instruction is still not to unlock the content.

Two related situations are easy to confuse with these:

  • Xcode StoreKit testing. Purchases made with a StoreKit configuration file in Xcode have the environment Xcode. They never reach Apple's servers, so no API call can find them. The library refuses to build a client for that environment and throws Xcode is not a supported environment for an AppStoreServerAPIClient.
  • An app with no App Store release yet. You might expect 4040010 when you send a sandbox transaction to production. For an app that has never been released, you get a plain 401 instead. A maintainer of Apple's Node library explained this in app-store-server-library-node issue #60: apps without a production release are not authorized to call any production endpoint. If you are seeing that 401, my App Store Server API 401 guide covers it.

Which environment should my server call?

Apple's App Store Server API overview says to call endpoints that take a transaction ID in the same environment that created it, and that the environment is in the environment field of JWSTransactionDecodedPayload. If you don't have that information, it gives this order: call production; on 4040010, call sandbox; if sandbox also returns 4040010, the transaction is in neither environment.

Flowchart: if the transaction's environment is known, call only that host; if unknown, call production, then sandbox on 4040010, and grant nothing if both return 4040010. A 401 from production branches off as an authentication or unreleased-app problem.
Lookup order for Get Transaction Info, based on Apple's App Store Server API docs.

The production host is api.storekit.apple.com and the sandbox host is api.storekit-sandbox.apple.com. Library 3.1.0 already uses these, following Apple's 5 May 2026 server update; the older itunes.apple.com hosts are still supported.

How do I fix 4040010 in Node.js?

Step 1: send the signed transaction from the app

In Flutter, in_app_purchase_storekit has used StoreKit 2 by default since 0.4.0 (the current version is 0.4.17). With StoreKit 2, serverVerificationData holds the transaction's jwsRepresentation, which includes the environment. Send it with the ID:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:in_app_purchase/in_app_purchase.dart';

Future<bool> verifyOnServer(PurchaseDetails purchase) async {
  final res = await http.post(
    Uri.parse('https://api.example.com/iap/apple/verify'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'transactionId': purchase.purchaseID,
      // With StoreKit 2 (the default since in_app_purchase_storekit 0.4.0)
      // this is the transaction's jwsRepresentation.
      'signedTransaction': purchase.verificationData.serverVerificationData,
    }),
  );
  return res.statusCode == 200;
}

In Swift, send verificationResult.jwsRepresentation. On iOS 16 and later you can also read transaction.environment.

Step 2: add a lookup module that never guesses twice

This module uses the environment when it's known and falls back from production to sandbox only when it isn't. It retries only codes Apple marks as retryable and returns a status for each case your route must handle. Only found can lead to a grant, and only after the signed transaction passes verification.

// lookup.mjs: find a StoreKit 2 transaction in the right App Store environment.
// Tested with @apple/app-store-server-library 3.1.0 on Node 24.
import {
  AppStoreServerAPIClient,
  SignedDataVerifier,
  APIException,
  APIError,
  Environment,
} from '@apple/app-store-server-library';

// "Not found in this environment": try the next environment, if any.
const NOT_FOUND = new Set([
  APIError.TRANSACTION_ID_NOT_FOUND, // 4040010
  APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND, // 4040005
]);

// Apple marks these as safe to retry.
const RETRYABLE = new Set([
  APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, // 4040006
  APIError.GENERAL_INTERNAL_RETRYABLE, // 5000001
]);

export function createClients({ signingKey, keyId, issuerId, bundleId }) {
  return {
    [Environment.PRODUCTION]: new AppStoreServerAPIClient(
      signingKey, keyId, issuerId, bundleId, Environment.PRODUCTION),
    [Environment.SANDBOX]: new AppStoreServerAPIClient(
      signingKey, keyId, issuerId, bundleId, Environment.SANDBOX),
  };
}

export function createVerifiers({ appleRootCerts, bundleId, appAppleId }) {
  const verifiers = {
    [Environment.SANDBOX]: new SignedDataVerifier(
      appleRootCerts, true, Environment.SANDBOX, bundleId),
  };
  // Production needs your numeric Apple ID, which exists once the app is created
  // in App Store Connect. Leave it out until you have it.
  if (appAppleId) {
    verifiers[Environment.PRODUCTION] = new SignedDataVerifier(
      appleRootCerts, true, Environment.PRODUCTION, bundleId, appAppleId);
  }
  return verifiers;
}

// Read the environment claim from a device JWS WITHOUT trusting it.
// It only picks which verifier and host to use; the verifier then checks
// the signature and rejects a JWS whose environment does not match.
export function peekEnvironment(jws) {
  try {
    const payload = JSON.parse(Buffer.from(jws.split('.')[1], 'base64url').toString('utf8'));
    return payload.environment; // 'Production' | 'Sandbox' | 'Xcode' | undefined
  } catch {
    return undefined;
  }
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function withRetry(call, { attempts = 3, baseDelayMs = 1000, sleep = wait } = {}) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await call();
    } catch (err) {
      const retryable = err instanceof APIException && RETRYABLE.has(err.apiError);
      if (!retryable || attempt >= attempts) throw err;
      await sleep(baseDelayMs * 2 ** (attempt - 1));
    }
  }
}

function environmentsToTry(environment, hasProductionRelease) {
  if (environment === Environment.PRODUCTION || environment === Environment.SANDBOX) {
    return [environment]; // known: never fall back
  }
  // Unknown: Apple's documented order is production, then sandbox on 4040010.
  // An app with no App Store release gets 401 from production, so skip it.
  return hasProductionRelease
    ? [Environment.PRODUCTION, Environment.SANDBOX]
    : [Environment.SANDBOX];
}

/**
 * Run one App Store Server API call in the right environment.
 * `call` receives a client, e.g. (c) => c.getTransactionInfo(id).
 * Returns { status: 'found', environment, result, tried } or
 * { status: 'not_found' | 'unauthenticated' | 'retry_later' | 'unsupported_environment', ... }.
 */
export async function callInEnvironment(clients, call, {
  environment, hasProductionRelease = true, retry,
} = {}) {
  if (environment === Environment.XCODE || environment === Environment.LOCAL_TESTING) {
    // Xcode StoreKit testing transactions never reach Apple's servers.
    return { status: 'unsupported_environment', environment, tried: [] };
  }
  const tried = [];
  for (const env of environmentsToTry(environment, hasProductionRelease)) {
    tried.push(env);
    try {
      const result = await withRetry(() => call(clients[env]), retry);
      return { status: 'found', environment: env, result, tried };
    } catch (err) {
      if (!(err instanceof APIException)) throw err;
      if (NOT_FOUND.has(err.apiError)) continue;
      if (err.httpStatusCode === 401) {
        // Bad JWT, or production for an app with no release yet. Not a lookup miss.
        return { status: 'unauthenticated', environment: env, tried };
      }
      if (RETRYABLE.has(err.apiError) || err.httpStatusCode === 429 || err.httpStatusCode >= 500) {
        return { status: 'retry_later', environment: env, apiError: err.apiError, tried };
      }
      throw err;
    }
  }
  return { status: 'not_found', tried };
}

export function findTransaction(clients, transactionId, options) {
  return callInEnvironment(clients, (c) => c.getTransactionInfo(transactionId), options);
}

/**
 * Look up, verify, and only then grant. Anything other than a verified,
 * unrevoked transaction for this app returns { granted: false }.
 */
export async function verifyAndGrant({
  clients, verifiers, transactionId, environment, hasProductionRelease, grant, retry,
}) {
  const lookup = await findTransaction(clients, transactionId, {
    environment, hasProductionRelease, retry,
  });
  if (lookup.status !== 'found') return { granted: false, ...lookup };

  const verifier = verifiers[lookup.environment];
  if (!verifier) return { granted: false, status: 'no_verifier', environment: lookup.environment };

  const tx = await verifier.verifyAndDecodeTransaction(lookup.result.signedTransactionInfo);
  if (tx.revocationDate) return { granted: false, status: 'revoked', environment: lookup.environment };

  await grant(tx);
  return { granted: true, status: 'found', environment: lookup.environment, productId: tx.productId };
}

A few design choices are worth explaining:

  • A known environment gets exactly one call. If a verified sandbox transaction is missing from sandbox, asking production won't help.
  • hasProductionRelease: false skips production while the app has never been released, because production answers 401 for those apps rather than 4040010.
  • A 401 stops the lookup. Falling back to sandbox on a 401 would hide a broken key in a released app.
  • peekEnvironment reads the claim without trusting it. It only picks a host and a verifier. SignedDataVerifier then checks Apple's signature chain and rejects a transaction whose environment doesn't match the verifier.

Step 3: call it from your route

// server.mjs: one verify route (Express). Wire up your own auth and storage.
import { readFileSync } from 'node:fs';
import express from 'express';
import { createClients, createVerifiers, peekEnvironment, verifyAndGrant } from './lookup.mjs';

const bundleId = process.env.APPLE_BUNDLE_ID;
const clients = createClients({
  signingKey: readFileSync(process.env.APPLE_IAP_KEY_PATH, 'utf8'), // In-App Purchase .p8
  keyId: process.env.APPLE_IAP_KEY_ID,
  issuerId: process.env.APPLE_ISSUER_ID,
  bundleId,
});
const verifiers = createVerifiers({
  appleRootCerts: [readFileSync('./certs/AppleRootCA-G3.cer')],
  bundleId,
  appAppleId: Number(process.env.APPLE_APP_ID) || undefined,
});

const app = express();
app.use(express.json());

app.post('/iap/apple/verify', async (req, res) => {
  const { transactionId, signedTransaction } = req.body ?? {};
  if (!/^\d+$/.test(String(transactionId))) return res.status(400).json({ error: 'bad_transaction_id' });

  const result = await verifyAndGrant({
    clients,
    verifiers,
    transactionId: String(transactionId),
    environment: signedTransaction ? peekEnvironment(signedTransaction) : undefined,
    hasProductionRelease: process.env.APP_HAS_PRODUCTION_RELEASE === 'true',
    grant: async (tx) => {
      // Save tx.transactionId, tx.productId and tx.environment with the user.
      console.log('grant', tx.productId, tx.environment);
    },
  });

  if (result.granted) return res.json({ ok: true, environment: result.environment });
  const status = result.status === 'retry_later' ? 503 : result.status === 'unauthenticated' ? 500 : 404;
  console.warn('apple lookup failed', result);
  return res.status(status).json({ ok: false, reason: result.status });
});

app.listen(3000);

Store tx.environment with every transaction you save, so later calls such as status checks, refund lookups or renewal extensions go straight to the right host. Each App Store Server Notification carries the environment too, as I showed in the App Store Server Notifications V2 guide.

What about 4040005 and 4040006?

OriginalTransactionIdNotFoundError (4040005) is the same problem for endpoints that take an original transaction ID. Apple's page gives exactly the same checks as for 4040010: the bundle ID in the JWT, then the environment. Because the module above accepts any call, you can reuse the routing:

const r = await callInEnvironment(
  clients,
  (c) => c.setAppAccountToken(originalTransactionId, { appAccountToken }),
  { environment: savedEnvironment },
);

OriginalTransactionIdNotFoundRetryableError (4040006) has the message "Original transaction id not found. Please try again." Apple documents the error object, but none of the current endpoint pages I checked list it as a response, so treat it as possible rather than common. The module retries it up to three times with backoff, then returns retry_later. It never treats it as a grant.

How do I test this without Apple keys?

A real 4040010 needs an In-App Purchase key and real transactions, so I tested the logic with nock intercepting Apple's two hosts. The library signs a real ES256 JWT with a throwaway P-256 key, and nock returns the response Apple documents:

nock('https://api.storekit.apple.com')
  .get('/inApps/v1/transactions/2000000123456789')
  .reply(404, { errorCode: 4040010, errorMessage: 'Transaction id not found.' });

All 13 tests pass on Node 24.22.1 with library 3.1.0:

✔ library surfaces 4040010 as APIException with apiError and message
✔ known Sandbox environment calls sandbox only
✔ unknown environment: production 4040010 falls back to sandbox
✔ unknown environment: 4040010 in both means not found and nothing is granted
✔ known Production environment does not fall back to sandbox on 4040010
✔ app with no production release skips production
✔ production 401 (plain text) is unauthenticated, not a miss: no sandbox call, no grant
✔ found and verified transaction is granted once
✔ 4040005 on an original-transaction endpoint falls back like 4040010
✔ 4040006 is retried, then succeeds
✔ 4040006 every time ends as retry_later, never as found
✔ Xcode transactions are not sent to Apple, and the library refuses an Xcode client
✔ peekEnvironment reads the claim from a device JWS
ℹ tests 13
ℹ pass 13
ℹ fail 0

On a device, run the app from Xcode without a StoreKit configuration file and a Sandbox Apple Account, or install a TestFlight build. Both create sandbox transactions your server can look up. Builds that use a StoreKit configuration file create Xcode transactions, so cover those with unit tests like the ones above.

How do I verify the fix?

  1. Make a sandbox purchase and confirm your logs show tried: ['Sandbox'] when the JWS was sent, or ['Production', 'Sandbox'] when it wasn't.
  2. Send a made-up ID such as 2000000000000001. The route must return 404 and grant nothing.
  3. Before the first release, set APP_HAS_PRODUCTION_RELEASE=false and check that production is never called.
  4. With a real JWT, this curl call should return JSON, not a bare 401:
curl -s -H "Authorization: Bearer $TOKEN" \
  https://api.storekit-sandbox.apple.com/inApps/v1/transactions/2000000000000001
# expected: {"errorCode":4040010,"errorMessage":"Transaction id not found."}

A JSON 4040010 for a made-up ID proves authentication works.

How do I stop 4040010 coming back?

  • Send the StoreKit 2 JWS, not just the transaction ID, from every app version.
  • Save the environment with every transaction and pick the host from it.
  • Sign each request with the bundle ID of the app that made the purchase, and keep one client pair per app if you serve several.
  • Keep the production-then-sandbox fallback only for IDs whose environment is truly unknown.
  • Treat 401 as an authentication problem, never as "try sandbox".
  • Log tried and apiError for every failed lookup so a rare 4040010 is visible, not silent.
  • When a customer reports a missing purchase, ask them to restore first. A restore makes the app send its signed transactions again, as covered in Flutter restore purchases not working.

Frequently asked questions

What does App Store Server API error 4040010 mean?

It is TransactionIdNotFoundError, returned with HTTP 404 and the message "Transaction id not found." Apple could not find the transaction ID for the bundle ID in your JWT in the environment you called.

Why does a TestFlight purchase return 4040010 in production?

TestFlight builds always use the sandbox environment, so their transactions exist only in sandbox. Call api.storekit-sandbox.apple.com for them, ideally by reading the environment from the signed transaction.

Should I fall back from production to sandbox on 4040010?

Only when you don't know the transaction's environment. Apple documents that order: call production, call sandbox on 4040010, and if sandbox also returns 4040010 the transaction is in neither environment.

Is it safe to unlock content when the App Store Server API returns 4040010?

No. Apple says not to unlock the service or content unless you resolve the error. Return an error to the app and let it retry or restore purchases.

What is the difference between 4040010 and 4040005?

4040010 is for endpoints that take a transaction ID, such as Get Transaction Info. 4040005 means an original transaction ID was not found, on endpoints such as Extend a Subscription Renewal Date and Set App Account Token. Apple gives the same fix for both.

What is App Store Server API error 4040006?

It is OriginalTransactionIdNotFoundRetryableError, with the message "Original transaction id not found. Please try again." Retry with backoff, and treat it as not found if it keeps failing.

Why do I get 401 instead of 4040010 from the production App Store Server API?

Apps that have never had an App Store release are not authorized to call production endpoints, so production returns 401. Call sandbox until the first release, and check your JWT and key if a released app gets 401.

Can the App Store Server API look up Xcode StoreKit testing transactions?

No. Transactions from a StoreKit configuration file in Xcode never reach Apple's servers, and Apple's Node library refuses to create a client for the Xcode environment. Test those flows locally.

Sources

  1. TransactionIdNotFoundError (Apple Developer)
  2. OriginalTransactionIdNotFoundError (Apple Developer)
  3. OriginalTransactionIdNotFoundRetryableError (Apple Developer)
  4. App Store Server API (Apple Developer)
  5. Get Transaction Info (Apple Developer)
  6. Set App Account Token (Apple Developer)
  7. Extend a Subscription Renewal Date (Apple Developer)
  8. JWSTransactionDecodedPayload (Apple Developer)
  9. App Store Server API changelog (Apple Developer, 2026-11-17)
  10. Testing In-App Purchases with sandbox (Apple Developer)
  11. Validating receipts with the App Store (Apple Developer)
  12. Transaction.environment (StoreKit) (Apple Developer)
  13. APIException.apiError 4040010 is missing (issue #60) (Apple on GitHub, 2024-01-16)
  14. docs: add verification through gettransctioninfo api sample (PR #80) (Apple on GitHub, 2024-02-06)
  15. Is dynamic fallback to Sandbox API correct when receiving error 4040010 during App Review? (Apple Developer Forums)
  16. @apple/app-store-server-library 3.1.0 (npm, 2026-05-06)
  17. in_app_purchase_storekit 0.4.17 (pub.dev, 2026-11-04)
  18. nock 15.0.7 (npm)
SharePost on XLinkedIn

Comments

Share a question or note about this article.

Loading comments…