Unity IAP客户端接入之后,服务器需要对订单有效性做验证。
两种方法-传送门:google Play iap 服务端验证(java) 这位大神写的已经非常清楚了。
第一种:需要从客户端提取出signatureData和signature,然后发到Server端,Server直接本地及用PublicKey进行校验就可以了。虽然是服务器本地验证,但是完全安全,不可伪造的。
第二种:服务器稍微有点麻烦,但直接拷贝大神的代码就可以了。这种方式,客户端需要传递ProductID和Token,那么token如何获取到,在Unity的Manual里面没有提到,需要的可以参考下段代码。使用UnityEngine.Purchasing.Security.CrossPlatformValidator去解析Unity回调的PurchaseEventArgs参数。
private UnityEngine.Purchasing.Security.CrossPlatformValidator validator;
validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
/// 注:这里省略了Unity IAP的代码
try
{
var result = validator.Validate(args.purchasedProduct.receipt);
foreach(UnityEngine.Purchasing.Security.IPurchaseReceipt purchaseReceipt in result )
{
BH.Logger.LogError( "ProductID:{0} PurchaseDate:{1} Transaction:{2}",
purchaseReceipt.productID, purchaseReceipt.purchaseDate, purchaseReceipt.transactionID );
AppleInAppPurchaseReceipt apple = purchaseReceipt as AppleInAppPurchaseReceipt;
if( null != apple )
{
BH.Logger.LogError("Apple ID:{0} ExpDate:{1} CancelDate:{2} Quality:{3}",
apple.originalTransactionIdentifier, apple.subscriptionExpirationDate,
apple.cancellationDate, apple.quantity);
// TODO: Apple发到服务器校验
}
GooglePlayReceipt google = purchaseReceipt as GooglePlayReceipt;
if( google != null)
{
/// 这里可以拿到productID, token,发到服务器去校验
PayModel.Instance.currentProductId = args.purchasedProduct.definition.id;
PayModel.Instance.currentReceipt = google.purchaseToken;
PayModel.Instance.currentChannelOrderID = google.transactionID;
}
}
}catch(IAPSecurityException )
{
BH.Logger.LogError("Invalid receipt, not unlocking content");
}
// Return a flag indicating whether this product has completely been received, or if the application needs
// to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
// saving purchased products to the cloud, and when that save is delayed.
return PurchaseProcessingResult.Complete;
}
因为客户端的解析我都做好了,懒得改消息包格式,所以我用了第二种方法做校验。然后,碰到了下面的问题:
Provider Error!或者是:service account with owner rights has insufficient permissions!
这个首先是要确认你的权限是给到了(在Google Developers Console里面设置),并且Email Address和P12 Key都对了,还是不可以的话,就是等待。Google的结论大约是24小时生效。我上周五下午测试一直有问题,今天早上试了下,结果就OK了。