Verify Purchase in iOS App Using Python

Tiempo de lectura: < 1 minuto

We will create a function today that allows us to verify an in-app purchase made from iOS using Apple and written in Python.

We will create a utility function like this:

import requests def verify_ios_purchase(purchase_token: str, testMode: bool = False) -> dict: print(purchase_token) print("---------------------------") """ Verifies the iOS receipt with Apple servers. Args: purchase_token (str): The receipt-data sent by the app. testMode sandbox (bool): True if it's a testing environment, False if it's production. Returns: dict: JSON response from Apple. """ url = "https://sandbox.itunes.apple.com/verifyReceipt" if testMode else "https://buy.itunes.apple.com/verifyReceipt" payload = { "receipt-data": purchase_token, "password": SHARED_SECRET_IOS_IAP, "exclude-old-transactions": True } headers = { "Content-Type": "application/json" } try: response = requests.post(url, json=payload, headers=headers, timeout=10) response.raise_for_status() print(response.json()) return response.json() except requests.exceptions.RequestException as e: return {"status": "error", "message": str(e)} 

We use it like this:

result = verify_ios_purchase(compra_iap.purchaseToken, testMode=compra_iap.test) # Check the result if result.get("status") == 0: print("Valid purchase") print(result) else: print("Invalid purchase") print(result.get("message")) #Raises exception raise HTTPException(status_code=400, detail=f"Invalid Apple purchase: {result.get('message')}")

This function must receive a transactionReceipt, not to be confused with the purchaseToken of Android or the jwsRepresentationIOS from storekit2.

To obtain the SHARED_SECRET_IOS_IAP we need to do the following:

We must go to our account at Apple Developer > Users and Access > Shared Secret

You copy the key that returns.

Here’s how to do it in PHP: https://devcodelight.com/validar-compra-en-aplicacion-compras-in-app-de-ios-usando-php/

Leave a Comment