创建app内购买项目
测试环境
在sandbox中验证receipt:https://sandbox.itunes.apple.com/verifyReceipt
在生产环境中验证receipt:https://buy.itunes.apple.com/verifyReceipt
那么如何自动的识别收据是否是sandbox receipt呢?
识别沙盒环境下收据的方法有两种:
- 根据收据字段 environment = sandbox。
- 根据收据验证接口返回的状态码。
如果status=21007,则表示当前的收据为沙盒环境下收据, t进行验证。
苹果反馈的状态码:
注意:
在verifyWithRetry方法中,首先向向真实环境验证票据,如果是21007则向沙盒环境验证;但是在消耗品类型的测试中,使用沙盒票据在真实环境中验证票据得到返回码:21002.所以下面代码在真实环境运行时,沙盒测试消耗型商品得不到正确的验证结果。
/*
verifyWithRetry the receipt
*/
IAPVerifier.verifyWithRetry = function(receipt, isBase64, cb) {
var encoded = null, receiptData = {};
if (isBase64) {
encoded = receipt;
} else {
encoded = new Buffer(receipt).toString('base64');
}
receiptData['receipt-data'] = encoded;
var options = this.requestOptions();
return this.verify(receiptData, options, (function(_this) {
return function(error, data) {
if (error) return cb(error);
if ((21007 === (data != null ? data.status : void 0)) && (_this.productionHost == _this.host)) {
var options_this.requestOptions();
// 指向沙盒测试环境再次验证
options.host = 'sandbox.itunes.apple.com/verifyReceipt';
return _this.verify(receiptData, options, function(err, data) {
return cb(err, data);
});
} else {
return cb(err, data);
}
};
})(this));
};
/*
verify the receipt data
*/
IAPVerifier.verify = function(data, options, cb) {
var post_data, request;
post_data = JSON.stringify(data);
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
};
var request = https.request(options, (function(_this) {
return function(response) {
var response_chunk = [];
response.on('data', function(data) {
if (response.statusCode !== 200) {
return cb(new Error("response.statusCode != 200"));
}
response_chunk.push(data);
});
return response.on('end', function() {
var responseData, totalData;
totalData = response_chunk.join('');
try {
responseData = JSON.parse(totalData);
} catch (_error) {
return cb(_error);
}
return cb(null, responseData);
});
};
})(this));
request.write(post_data);
request.end();
request.on('error', function (exp) {
console.log('problem with request: ' + exp.message);
});
};
IAPVerifier.requestOptions = function() {
return options = {
host: 'buy.itunes.apple.com',
port: 443,
path: '/verifyReceipt',
method: "POST",
rejectUnauthorized: false/*不加:返回证书不受信任CERT_UNTRUSTED*/
};
};