验证应用内购买收据
应用内购买收据验证是确保通过应用程序进行的交易真实性和有效性的关键步骤你的应用程序。本文旨在通过分享已成功实现的全面代码示例,为在收据验证方面遇到困难的开发人员提供指导。
代码实现
要验证收据,请按照步骤如下:
<code class="objective-c">- (BOOL)verifyReceipt:(SKPaymentTransaction *)transaction { // Encode receipt data NSString *jsonObjectString = [self encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length]; // Construct URL with encoded receipt NSString *completeString = [NSString stringWithFormat:@"http://url-for-your-php?receipt=%@", jsonObjectString]; NSURL *urlForValidation = [NSURL URLWithString:completeString]; // Create request with HTTP GET method NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation]; [validationRequest setHTTPMethod:@"GET"]; // Send request synchronously NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil]; // Parse server response NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSInteger response = [responseString integerValue]; return (response == 0); }</code>
<code class="objective-c">- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length { // Define encoding table static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // Create mutable data buffer NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; uint8_t *output = (uint8_t *)data.mutableBytes; // Encode data in loop for (NSInteger i = 0; i < length; i += 3) { NSInteger value = 0; for (NSInteger j = i; j < (i + 3); j++) { value <<= 8; if (j < length) { value |= (0xFF & input[j]); } } // Add encoded bytes to output NSInteger index = (i / 3) * 4; output[index + 0] = table[(value >> 18) & 0x3F]; output[index + 1] = table[(value >> 12) & 0x3F]; output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; } return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; }</code>
<code class="php"><?php // Fetch receipt data from request parameter $receipt = json_encode(array("receipt-data" => $_GET["receipt"])); // Set URL for receipt verification $url = "https://sandbox.itunes.apple.com/verifyReceipt"; // Send POST request with receipt data $response_json = call-your-http-post-here($url, $receipt); // Decode JSON response $response = json_decode($response_json); // Perform receipt verification and save data accordingly echo $response->status; ?></code>
其他注意事项
以上是如何在 iOS 中验证应用内购买收据?的详细内容。更多信息请关注PHP中文网其他相关文章!