背景描述
项目对接华为HMS SDK的应用内支付IAP SDK3.x以后,支付成功后,可从PurchaseResultInfo对象中获取到购买数据InAppPurchaseData及其签名数据,需要使用在华为AppGallery Connect分配的公钥进行签名验证。
具体参考文档如下描述:
https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/dev-guide-0000001050130254#ZH-CN_TOPIC_0000001050130254__section183174113342
代码开发
这里随手用PHP写了一个小demo,验证拿到的购买数据、签名数据和公钥能否正常验签成功。同时也分享给大家,方便大家快速定位问题,比如公钥错误等问题。
代码
<?php
//收到的实际支付回调,不要做任何处理,请复制原始数据。
//这里xxxx等信息都是我屏蔽了一些个人数据,实际大家复制自己的回调数据就好
$content = '{"autoRenewing":false,"orderId":"201912250949586652ebf220c1.10xxxx75","packageName":"com.example.xxxxxxexample_netease.huawei","applicationId":10xxxx75,"kind":0,"productId":"3","productName":"test33333","purchaseTime":1577238608000,"purchaseTimeMillis":1577238608000,"purchaseState":0,"developerPayload":"09815772385983110000000191996123","purchaseToken":"0000016f3abf3a78a4ef7b217523ea5a346825ab632c152b864c2e5251433c9d599c5986ab8c89b1.1.10xxxx75","consumptionState":0,"acknowledged":0,"currency":"CNY","price":100,"country":"CN","payOrderId":"Aed0f1fbd9929f803d9d23b523b14575","payType":"4"}';
//sign值需要使用回调中的原始值,不要做urlencode或urldecode处理。
$sign = 'IuCnJI3bCDr92uomUbxamp6VeC8vN+o3GTtB7aVwTGpkk9QgeR9KdUjDya1tJXKX8HZgTTLpj7v4A1lP8xrOq3+knykn32Tup6STnn4qpee8J3sS9kjpIHmhIbh3QfnsHksCaT4ib9BurIWnH7yEtNlwqmOOibJw8FgFXofrfPsDwjuCy4/X9rlbimjmyAiFZLXCTNQoGollqUVEjqabhjh/a+VY89A6Z02F2bJkes39a7lQMer42egha86w65L3UYYSLOyxQPIfIZ1BG5yirZN4JgcD17CMk+vQvtVDXhC+e4xN//txWlG/qIgviZbmhLFGjA/gfP0o8LpY7booiA==';
//支付公钥需要处理成以下RSA格式,中间内容为公钥64位换行
$pubKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq7iOD9qLMxMCEsY+l+IE
6kdI9HKHQoDG29ebPZFD+U1pdDewmkEcQzv/k0NmE9oeNIcxUqhg7ZwRrQ0g9xje
BCkiLTg4DOygOPOcZykuKZXDv/9aFn6FR5BVCrrOzmeR+/aEYcZZp86iWX+W4BdJ
L41i8qYonVRD6sDNuidAdg0UkNMPVRiHd5EYBgRHpPma7oeRVqfX4Iq/rL4DFOpu
uLiaLKmWSMOCLnIH+EXjjw3ttJOrB4Rq2fq6KrORgc8JMq2TPf/kK6r8NW9eWRWa
zmFvAZ8bUA7Idu4W8Z4SENwEO+ZeyWQx5I/piYEmBvmn3dy2l2bP3cZMUBVACkAE
jwIDAQAB
-----END PUBLIC KEY-----';
$openssl_public_key = @openssl_get_publickey($pubKey);
// SHA256 要根据实际回调中signType字段的取值确定,signType=RSA256时 使用以下字段值,其他任何情况都是用SHA1
$ok = @openssl_verify($content, base64_decode($sign), $openssl_public_key,'SHA256');
@openssl_free_key($openssl_public_key);
$result = "";
if($ok)
{
$result = "0";// success
}
else
{
$result = "1";// failure
}
$res = "{ \"result\": $result} ";
echo $res;
?>
运行
直接百度搜索个PHP在线运行工具,比如我这里随时用的:
复制代码进去后,运行返回0表示数据均正常。
原文链接:https://developer.huawei.com/consumer/cn/forum/topic/0202460337200900948?fid=0101271690375130218
原作者:Mayism