alipay / alipay-sdk-nodejs-all

支付宝开放平台 Alipay SDK for Node.js
https://docs.open.alipay.com/54/103419/
Other
406 stars 62 forks source link

接口内容加密方式如何验证 #140

Closed StringKe closed 1 month ago

StringKe commented 1 month ago

https://opendocs.alipay.com/common/02mse3

AES 验签名,比如 https://opendocs.alipay.com/mini/api/getphonenumber 返回的数据进行验证

StringKe commented 1 month ago

utils.ts 有相关方法,没有对外

fengmk2 commented 1 month ago

我看看

fengmk2 commented 1 month ago

@StringKe https://github.com/alipay/alipay-sdk-nodejs-all?tab=readme-ov-file#%E5%AF%B9%E5%8A%A0%E5%AF%86%E5%86%85%E5%AE%B9%E8%BF%9B%E8%A1%8C%E8%A7%A3%E5%AF%86 暴露出来了

StringKe commented 1 month ago

response 能解密,还有一个 sign 参数需要校验,校验要调度那个方法?可以举个例子么? java sdk 中有一个 AlipaySignature.rsaCheck 方法

fengmk2 commented 1 month ago

https://github.com/alipay/alipay-sdk-nodejs-all?tab=readme-ov-file#%E9%80%9A%E7%9F%A5%E9%AA%8C%E7%AD%BE 这个?

StringKe commented 1 month ago

我尝试调度过这个失败,手机号获取那边没有 sign_type 这些参数

fengmk2 commented 1 month ago

@StringKe 具体是那个文档?手机号码这个我看只需要解密成功即可。

StringKe commented 1 month ago

https://opendocs.alipay.com/mini/api/getphonenumber#success%20%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0

比如这个它会返回 sign 参数,还是需要验证一下的吧

fengmk2 commented 1 month ago

我找到一个示例代码,我先看看 https://opendocs.alipay.com/common/02mse3 ,搞定给你写到文档里面去。

String response = "小程序前端返回的加密信息";
    //1. 获取验签和解密所需要的参数
    Map<String, String> openapiResult = JSON.parseObject(response,new TypeReference<Map<String, String>>() {}, Feature.OrderedField);
    String signType = "RSA2";
    String charset = "UTF-8";
    String encryptType = "AES";
    String sign = openapiResult.get("sign");
    String content = openapiResult.get("response");
    //判断是否为加密内容
    boolean isDataEncrypted = !content.startsWith("{");
    boolean signCheckPass = false;
    //2. 验签
    String signContent = content;
    String signVeriKey = "你的小程序对应的支付宝公钥(为扩展考虑建议用appId+signType做密钥存储隔离)";
    String decryptKey = "你的小程序对应的加解密密钥(为扩展考虑建议用appId+encryptType做密钥存储隔离)";//如果是加密的报文则需要在密文的前后添加双引号
    if (isDataEncrypted) {    
   signContent = "\"" + signContent + "\"";
    } try {    
    signCheckPass = AlipaySignature.rsaCheck(signContent, sign, signVeriKey, charset, signType);
    } catch (AlipayApiException e) {    
    // 验签异常, 日志
    } if (!signCheckPass) {   
   //验签不通过(异常或者报文被篡改),终止流程(不需要做解密)    
    throw new Exception("验签失败");
    }
    //3. 解密
    String plainData = null;
    if (isDataEncrypted) {    
    try {        
        plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);    
    } catch (AlipayApiException e) {       
   //解密异常, 记录日志       
    throw new Exception("解密异常");   
   }} else {    
     plainData = content;
    }
fengmk2 commented 1 month ago

@StringKe https://github.com/alipay/alipay-sdk-nodejs-all/pull/142