微信支付HMAC-SHA256加解签采坑记录

sign_type也要参与加签

appid=wx28d9f58adc1a2f8e&attach=pay-test&body=native-pay-test&fee_type=THB&mch_id=118875980&nonce_str=20201201114940636&notify_url=https://www.yezhou.cc/callback/notify.php&out_trade_no=wx20201201114940636&sign_type=HMAC-SHA256&sub_mch_id=516669865&time_expire=20201202114940&time_start=20201201114940&total_fee=280&trade_type=NATIVE

加签串需要添加 &key=xxx

public static String hmacSHA256(String data, String key, String charset) throws Exception {
    String content = String.format("%s&key=%s", data, key);
    Mac sha256Hmac = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(charset), "HmacSHA256");
    sha256Hmac.init(secretKey);
    byte[] array = sha256Hmac.doFinal(content.getBytes(charset));
    StringBuilder sb = new StringBuilder();
    for (byte item : array) {
        sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
    }
    return sb.toString();
}

public static boolean verifyHmacSHA256(String text, String sign, String key, String charset) throws Exception {
    String mySign = hmacSHA256(text, key, charset);
    if (mySign.equalsIgnoreCase(sign)) {
        return true;
    } else {
        return false;
    }
}

验签字段是下划线式

验签字段是下划线式,而非驼峰式,序列化及反序列化时应注意

错误验签串:

appid=wx28d9f58adc1a2f8e&attach=product_code=WECHAT_PAY|payment_type=QRCODE&bankType=OTHERS&cashFee=3&cashFeeType=CNY&deviceInfo=appblog.cn&feeType=THB&isSubscribe=Y&mchId=118875980&nonceStr=01422887685418391183670693845884&openid=oaJiE1PwlwP_Tee0Z7uzrQFJeRqE&outTradeNo=132020120102277089&rateValue=21830000&resultCode=SUCCESS&returnCode=SUCCESS&subMchId=516669865&timeEnd=20201201135626&totalFee=15&tradeType=NATIVE&transactionId=4200000817202012015050164846

正确验签串:

appid=wx28d9f58adc1a2f8e&attach=product_code=WECHAT_PAY|payment_type=QRCODE&bank_type=OTHERS&cash_fee=3&cash_fee_type=CNY&device_info=appblog.cn&fee_type=THB&is_subscribe=Y&mch_id=118875980&nonce_str=01422887685418391183670693845884&openid=oaJiE1PwlwP_Tee0Z7uzrQFJeRqE&out_trade_no=132020120102277089&rate_value=21830000&result_code=SUCCESS&return_code=SUCCESS&sub_mch_id=516669865&time_end=20201201135626&total_fee=15&trade_type=NATIVE&transaction_id=4200000817202012015050164846
上一篇 微信开发技术整理
下一篇 微信境外服务商支付
目录
文章列表
1 React-Router路由配置
React-Router路由配置
2
Android实现3种Notification(状态栏通知)
Android实现3种Notification(状态栏通知)
3
阿里巴巴Canal Client同步ElasticSearch
阿里巴巴Canal Client同步ElasticSearch
4
Android判断应用通知权限是否开启以及跳转到设置界面
Android判断应用通知权限是否开启以及跳转到设置界面
5
Android Gradle 4.1以上依赖变化:compile->api和implementation
Android Gradle 4.1以上依赖变化:compile->api和implementation
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。