验证应用内购买收据
应用内购买验证对于确保用户进行合法购买并授予他们访问权限至关重要优质内容或功能。尽管有文档,但实施有效的收据验证可能具有挑战性。
一种方法是将收据数据发送到 PHP 服务器,然后将其转发到 Apple App Store 进行验证。成功的响应确认了购买的有效性,允许您继续在服务器上记录交易。
但是,如果您在收据验证期间遇到“无效状态”响应,则必须检查是否有任何拼写错误你的代码。以下示例代码提供了解决方案:
- (BOOL)verifyReceipt:(SKPaymentTransaction *)transaction { NSString *jsonObjectString = [self encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length]; NSString *completeString = [NSString stringWithFormat:@"http://url-for-your-php?receipt=%@", jsonObjectString]; NSURL *urlForValidation = [NSURL URLWithString:completeString]; NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation]; [validationRequest setHTTPMethod:@"GET"]; NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil]; [validationRequest release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding]; NSInteger response = [responseString integerValue]; [responseString release]; return (response == 0); } - (NSString *)encode:(const uint8_t *)input length:(NSInteger)length { static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /="; NSMutableData *data = [NSMutableData dataWithLength:((length 2) / 3) * 4]; uint8_t *output = (uint8_t *)data.mutableBytes; for (NSInteger i = 0; i > 18) & 0x3F]; output[index 1] = table[(value >> 12) & 0x3F]; output[index 2] = (i 1) > 6) & 0x3F] : '='; output[index 3] = (i 2) > 0) & 0x3F] : '='; } return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; }
此外,可以在您的服务器上使用以下 PHP 代码来处理收据验证并记录交易:
$receipt = json_encode(array("receipt-data" => $_GET["receipt"])); // NOTE: use "buy" vs "sandbox" in production. $url = "https://sandbox.itunes.apple.com/verifyReceipt"; $response_json = call-your-http-post-here($url, $receipt); $response = json_decode($response_json); // Save the data here! echo $response->status;
请记住将“call-your-http-post-here”替换为您首选的 HTTP post 机制。通过实施此代码并确保其准确性,您可以有效地验证收据购买并自信地管理应用内交易。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3