Apple IAP Receipt Validation Node.js

时间:2018-01-07 08:19:07

标签: javascript ios node.js swift receipt-validation

我正在尝试使用here中的Node.js进行IAP收据验证,但它总是在服务器日志上返回错误:“receipt-data属性中的数据格式错误。”

有人可以帮我正确地将base64字符串发送到Node.js并将其解码为相同的base64字符串以进行收据验证吗?我没有使用javascript的经验,并且一直试图让这个简单的代码工作两天,但无济于事。

这是我的Swift代码:

let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)         
let receiptString = receiptData.base64EncodedString(options: [])


var request = URLRequest(url: URL(string: "https://us-central1-calendizer-6a849.cloudfunctions.net/receiptValidation")!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  request.httpMethod = "POST"

// attach receipt data to a request
request.httpBody = receiptString.data(using: .utf8)

print("httpBody: \(request.httpBody?.base64EncodedString())")

Logs.log("✉️ Receipt Validation -> sending request ...")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
...
}

这是我的Node.js代码(Firebase云功能):

const functions = require('firebase-functions');
var iap = require('in-app-purchase');


exports.receiptValidation = functions.https.onRequest((request, response) => {

var receipt_try1 = request.body
var receipt_try2 = request.body.toString('base64');
var receipt_try3 = JSON.stringify(receipt);
var receipt_try4 =  new Buffer(request.body.toString(), 'base64')

console.log("receipt: " + receipt_try1)

iap.config({
   applePassword: 'my shared key', 
   test: true
});

iap.setup(function (error) {
  if (error) {
   console.log("Setup error:" + error) // Failed to validate  
}

iap.validate(iap.APPLE, receipt_try1, function (error, appleResponse) {

    if (error) 
    {
      console.log("Validation error:" + error) // Failed to validate  
    }

    if (iap.isValidated(appleResponse)) {

      console.log("successful validation" + appleResponse)
      response.send(appleResponse)

    }

  });

}); 
});

1 个答案:

答案 0 :(得分:2)

使用json做到了:

let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)

let receiptBase64String = receiptData.base64EncodedString(options: [])
//.replacingOccurrences(of: "+", with: "%2B")


// prepare json data
let json: [String: Any] = ["receipt_string":  receiptBase64String]
let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)


// create post request
var request = URLRequest(url: URL(string: "https://us-central1-calendizer-6a849.cloudfunctions.net/receiptValidation")!)
//request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = jsonData

并在Node.js中简单地说:

var receipt = request.body.receipt_string