Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expo in app purchases for React Native — how to tell if subscription is current / active?

Current app is Expo for React Native which is ejected to the bare workflow. Using expo-in-app-purchases for IAP.

How can you tell if a subscription is active or not?

When I grab the purchase history via:

const { results } = InAppPurchases.connectAsync();

if you look at the results, a result returns the following fields:

  • purchaseTime
  • transactionReceipt
  • orderId
  • productId
  • acknowledged
  • originalPurchaseTime
  • originalOrderId
  • purchaseState

Now purchaseState is always an integer. I'm mostly seeing 3 (I think I've seen a 1 one time...) Not sure this actually tells me anything valuable as they are all 3s

Short of manually taking the most recent purchase and adding 30 days (this is a monthly subscription) then seeing if this date is in the past, I'm not sure how to find if current user has active subscription. Help!

Thanks in advance!

like image 500
chairsandtable Avatar asked Oct 27 '25 14:10

chairsandtable


1 Answers

Apple gives you the receipt as a signed and base64-encoded string. In order to see the contents of the receipt (including the 'expires at' date), you need to send this receipt to Apple's receipt verification endpoint along with your app-specific password.

More info here: https://developer.apple.com/documentation/storekit/in-app_purchase/validating_receipts_with_the_app_store

A function similar to this worked for me. This retrieves the receipt info as a JSON object and inside there is expires_at_ms, which can be compared to today's date to see if the subscription has expired.

async validateAppleReceipt(receipt) {
  const prodURL = 'https://buy.itunes.apple.com/verifyReceipt'
  const stagingURL = 'https://sandbox.itunes.apple.com/verifyReceipt'
  const appSecret = '1234...'

  const payload = {
    "receipt-data": receipt,
    "password": appSecret,
    "exclude-old-transactions": true,
  }

  // First, try to validate against production
  const prodRes = await axios.post(prodURL, payload)

  // If status is 21007, fall back to sandbox
  if (prodRes.data && prodRes.data.status === 21007) {
    const sandboxRes = await axios.post(stagingURL, payload)
    return sandboxRes.data.latest_receipt_info[0]
  }

  // Otherwise, return the prod data!
  return prodRes.data.latest_receipt_info[0]
}
like image 172
whusterj Avatar answered Oct 30 '25 13:10

whusterj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!