Validating In-App Purchase Receipts
In-app purchases provide an essential revenue stream for many iOS apps. To ensure the legitimacy of these transactions, app developers need to validate their receipts with Apple's App Store. However, this process can be complex and prone to errors.
Receipt Validation: An Overview
To validate a receipt on the client side, developers must retrieve it from the SKPaymentTransaction object and encode it in base64. The encoded receipt is then transmitted to the developer's server.
Server-Side Verification
The server then forwards the encoded receipt to Apple's App Store using an HTTP POST request. Apple's response will indicate whether the receipt is valid, along with the status of the transaction (e.g., purchased, refunded).
Client-Side Integration
Once the receipt has been verified on the server, the client-side app can retrieve the data and store it locally. This record can then be used to unlock content or grant access to features within the app.
Sample Code
Verifying a receipt in code involves these steps:
Objective-C Client-Side:
<code class="objective-c">- (void)verifyReceipt:(SKPaymentTransaction *)transaction { NSString *receiptData = [self encode:transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length]; // Combine with server URL and query string, perform HTTP request }</code>
Base64 Encoding:
<code class="objective-c">- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length { // Encode the receipt data using base64 }</code>
Server-Side PHP:
<code class="php">$url = "https://sandbox.itunes.apple.com/verifyReceipt"; $receipt = json_encode(array("receipt-data" => $_GET["receipt"])); $response = json_decode(postToURL($url, $receipt)); // Parse and process the Apple response</code>
Troubleshooting and Precautions
Ensure the receipt data is properly formatted and encoded before sending it to Apple. Use an up-to-date version of iOS and the App Store SDK. Consider using asynchronous HTTP requests to avoid blocking the UI thread. It's recommended to use secure HTTPS connections for both client-side and server-side communications.
The above is the detailed content of How to Validate In-App Purchase Receipts?. For more information, please follow other related articles on the PHP Chinese website!