ios.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // iOS 充值校验
  2. var https = require('https');
  3. var events = require('events');
  4. var util = require('util');
  5. var iOS = function(sandbox) {
  6. this.emitter = new events.EventEmitter(this);
  7. if (sandbox) {
  8. this.url = 'sandbox.itunes.apple.com';
  9. } else {
  10. this.url = 'buy.itunes.apple.com';
  11. }
  12. }
  13. var parse = function(emitter, status, receipt) {
  14. if (status != 0) {
  15. var message;
  16. if (status == 21000) {
  17. message = "App Store无法读取你提供的JSON数据(21000)";
  18. } else if (status == 21002) {
  19. message = "收据数据不符合格式(21002)";
  20. } else if (status == 21003) {
  21. message = "收据无法被验证(21003)";
  22. } else if (status == 21004) {
  23. message = "你提供的共享密钥和账户的共享密钥不一致(21004)";
  24. } else if (status == 21005) {
  25. message = "收据服务器当前不可用(21005)";
  26. } else if (status == 21006) {
  27. message = "收据是有效的,但订阅服务已经过期(21006)";
  28. } else if (status == 21007) {
  29. message = "收据信息是测试用(sandbox),但却被发送到产品环境中验证(21007)";
  30. } else if (status == 21008) {
  31. message = "收据信息是产品环境中使用,但却被发送到测试环境中验证(21008)";
  32. } else {
  33. message = "未知状态码(" + status + ")";
  34. }
  35. emitter.emit('error', new Error(message))
  36. return;
  37. }
  38. var in_app = receipt.in_app
  39. var length = in_app.length
  40. for (var i=0; i< length; ++i) {
  41. var order = in_app[i]
  42. if (order && order.product_id) {
  43. emitter.emit('progress', order, i, length);
  44. }
  45. }
  46. }
  47. iOS.prototype.verify = function(receipt) {
  48. var bytes = JSON.stringify({"receipt-data":receipt});
  49. var options = {
  50. hostname: this.url,
  51. port: 443,
  52. path: '/verifyReceipt',
  53. method: 'POST',
  54. headers: {
  55. 'Content-Type': 'Application/json',
  56. 'Content-Length':bytes.length
  57. }
  58. };
  59. var emitter = this.emitter
  60. var req = https.request(options, function (res){
  61. var byteArray = [];
  62. var size = 0;
  63. res.on('data', function (data){
  64. byteArray.push(data);
  65. size += data.length;
  66. });
  67. res.on('end', function (){
  68. var buf = Buffer.concat(datas, size);
  69. var content = JSON.parse(buf.toString())
  70. parse(emitter, content.status, content.receipt)
  71. });
  72. res.on('error', function (err) {
  73. emitter.emit('fault', err)
  74. });
  75. }).on('error', function(err){
  76. emitter.emit('fault', err)
  77. });
  78. req.write(bytes);
  79. req.end();
  80. return this
  81. }
  82. iOS.prototype.on = function(eventName, callback) {
  83. this.emitter.on(eventName, callback);
  84. return this
  85. }
  86. util.inherits(iOS, events.EventEmitter); //继承
  87. module.exports = iOS