Google play支付如何用nodejs验证订单完成的合法性

Google play支付如何用nodejs验证订单完成的合法性

const crypto = require('crypto');

// 把字符串分割为一连串更小的部分
function chunk_split(paramString, paramLength, paramEnd = '\n') {
    let p = [];
    let s = paramString;
    while (s.length > paramLength) {
        let s1 = s.substr(0, paramLength);
        let s2 = s.substr(paramLength);
        s = s2;
        p.push(s1);
    }
    if (s.length > 0) {
        p.push(s);
    }
    p.push('');
    return p.join(paramEnd);
}

// google 公钥
let googlePublicKey = '在 google console 中的开发工具-》服务和API中可以找到';

/**
 * 验证google支付签名是否正确
 * @param {*} params  支付成功收到的参数
 * @param {*} inappDataSignature google 传入的签名 字段名和顺序与用例保持一致  {
    "orderId": "GPA.3341-6034-7995-16517",
    "packageName": "com.exchange.demo",
    "productId": "1006",
    "purchaseTime": 1551281602450,
    "purchaseState": 0,
    "developerPayload": "Coins Package Pack 1",
    "purchaseToken": "jjfbbecohm",
}
 */
function GooglePlayCheck(params, inappDataSignature) {
    let verify = crypto.createVerify('RSA-SHA1');//请注意,这里要用RSA-SHA1

    let PHP_EOL = '\n';//实际上就是换行符
    let inappPurchaseData = JSON.stringify(params);
    //这里要将公钥转换成64个字符一行的文本块。
    let publicKey = "-----BEGIN PUBLIC KEY-----" + PHP_EOL + chunk_split(googlePublicKey, 64, PHP_EOL) + "-----END PUBLIC KEY-----";
    verify.update(inappPurchaseData);//
    let isSuccess = verify.verify(publicKey, Buffer.from(inappDataSignature, 'base64')); //验证数据
    console.log("result:", isSuccess);
}

测试用例

/**
 * 测试用例
 */
GooglePlayCheck({
    "orderId": "GPA.3341-6034-7995-16517",
    "packageName": "com.exchange.demo",
    "productId": "1006",
    "purchaseTime": 1551281602450,
    "purchaseState": 0,
    "developerPayload": "Coins Package Pack 1",
    "purchaseToken": "jjfbbecohm",
}, "Ig1zAZJPZ8dH4id\/0zDDY62OlbACgWrb+ApRNXu08W35A+XLTp5N5krGugSUBG5LN1CRdLECGY+F8kczh10KLubCmgSPbBhB1kxJ\/bpMSfeklvCa0L3qJ00h0J8km7xJw6nTlwWtlHZzCQWu0TjeniVT0+hipTV67jkCjpHV+e8iGMxxKy0X+8qVEwQ5XNA==");

你可能感兴趣的:(Google)