微信虚拟支付接入(道具支付)
1.描述本文档为最近因微信虚拟支付之前使用的是普通微信支付旧模式的支付wx.requestPayment此类支付其实只适用于实物商品ios端不支持会被封禁因其费率更低大概在0.6%所以之前一直使用的都是此支付模式 而从2026年4月1日微信发布了新的公告《小程序虚拟支付业务管理规范更新公告》所有涉及虚拟支付的小程序必须全终端包括 iOS、安卓等接入官方虚拟支付接口。 所以现在是小程序因为不合规导致被封禁必须修改支付方式对接升级为官方的小程序虚拟支付微信官方给出的虚拟支付wx.requestVirtualPaymentps语言为java且本人为后端主视角为后端开发流程微信文档地址微信小程序虚拟支付流程https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment.html虚拟支付技术服务费https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/devplan.html微信小程序拉起虚拟支付https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestVirtualPayment.htmluniapp拉起虚拟支付https://uniapp.dcloud.net.cn/api/plugins/virtualPayment.html#requestvirtualpayment虚拟支付中又分为道具支付与代币支付因我的小程序中都是关于vip类的需求很明显二选一中是道具支付更贴切现在的逻辑需求所以下方的对接流程与文档都只针对于道具支付2.后端准备步骤流程虚拟支付流程图道具支付微信方相关配置虚拟支付的新商户号虚拟支付的appKey虚拟支付配置上的OfferID(支付应用ID)道具创建好后的配置道具id推荐使用会员上的id道具金额推荐和会员金额一致否则拉起支付不一定成功---这玩意微信那边是分哦记得转换后端请求流程设计按照拉起支付流程除了上述微信配置上的所需数据外还需要确保一点就是用户的小程序会话key必须有且有效所以第一步是需要在原有的逻辑上进行一步校验的操作微信登陆后小程序拿到下同的token只要还能正常请求就不进行其他的登陆认证等其实按照正常的流程来说应该使用微信的会话key和系统token是否失效共同来判断用户当前是否应该重新登陆1.检查用户小程序会话key是否已经失效接口没有的呢肯定得重新登陆重新获取// 登陆时就要拿到并存储一下用户的session_key如果没有的让用户重新登陆 /** * 检查用户session_key是否有效 * param request 请求对象 * return session_key有效性结果 */ AutoLog(value 检查session_key有效性) ApiOperation(value检查session_key有效性, notes检查当前用户session_key是否有效) PostMapping(/checkSession) public Result checkSession(HttpServletRequest request) { try { SysUser loginUser (SysUser) SecurityUtils.getSubject().getPrincipal(); String userId loginUser.getId(); SysUser user sysUserService.getById(userId); if(user null || StringUtils.isBlank(user.getAppOpenid())){ return Result.error(用户信息为空); } if (StringUtils.isEmpty(user.getSessionKey())){ return Result.error(400,会话凭证为空请重新登陆); } String openid user.getAppOpenid(); String sessionKey user.getSessionKey(); // 获取access_token String accessToken tokenUtils.findAccessToken(); // 使用空字符串对session_key进行签名 String signature calcSignature(, sessionKey); // 调用微信检查session接口 String checkUrl https://api.weixin.qq.com/wxa/checksession?access_token accessToken signature signature openid openid sig_methodhmac_sha256; String result HttpRequest.sendGet(checkUrl, null); System.out.println(check_session返回: result); JSONObject resultObj JSON.parseObject(result); Integer errcode resultObj.getInteger(errcode); // 错误码87009invalid signature无效的签名 // 错误码87007 session_key is not existd or expired if(errcode ! null errcode 87009 || errcode 87007){ return Result.error(400,会话凭证已失效请重新登录); } if(errcode ! null errcode ! 0){ return Result.error(检查session失败: resultObj.getString(errmsg)); } MapString, Object data new HashMap(); data.put(valid, true); return Result.OK(data); } catch (Exception e) { e.printStackTrace(); return Result.error(检查session异常: e.getMessage()); } }此接口返回为400的会要求前端让用户重新进行一次登陆2.接收指定订单id并返回要向微信请求的数据结构订单用户有效数据和微信配置组装我的项目中订单是在小程序上前端调用此接口前进行创建的此接口传入了刚创建完成的订单数据/** * 获取虚拟支付配置数据 * param payVo 支付参数 * param request 请求对象 * return 虚拟支付配置数据 */ AutoLog(value 获取虚拟支付配置) ApiOperation(value获取虚拟支付配置, notes获取小程序虚拟支付所需配置数据) PostMapping(/getVirtualPayConfig) JLock(lockKey virtual-pay-lock) public Result getVirtualPayConfig(RequestBody PayVo payVo, HttpServletRequest request) { // 使用虚拟支付中的道具支付 try { SysUser loginUser (SysUser) SecurityUtils.getSubject().getPrincipal(); String userId loginUser.getId(); SysUser user sysUserService.getById(userId); // 判断当前环境 Boolean isProd ENVIRONMENT.equals(prod); if(user null){ return Result.error(400,用户信息为空); } if(StringUtils.isBlank(user.getSessionKey())){ return Result.error(400,会话凭证为空请重新登录); } String topUpId payVo.getTopUpId(); if(StringUtils.isBlank(topUpId)){ return Result.error(订单号未传入); } AtTopup atTopup atTopupService.getById(topUpId); if(atTopup null){ return Result.error(没有此订单); } if(!atTopup.getUserId().equals(userId)){ return Result.error(此订单不属于你); } if(atTopup.getTopupStatus() ! null 1.equals(atTopup.getTopupStatus())){ return Result.error(订单已支付); } // 构建signData MapString, Object signData new TreeMap(); // 微信虚拟支付页面管理上配置的参数 signData.put(offerId, OfferId); // 购买数量 signData.put(buyQuantity, 1); // 环境配置 0正式环境 1沙箱环境 if (isProd){ signData.put(env, 0); }else{ signData.put(env, 1); } // 支付金额币种 signData.put(currencyType, CNY); // 道具ID signData.put(productId, atTopup.getMembersId()); // 道具商品价格必须与微信对应道具的价格一致 signData.put(goodsPrice, atTopup.getMoney().multiply(new BigDecimal(100)).intValue()); // 订单号 signData.put(outTradeNo, atTopup.getId()); // 附加数据 signData.put(attach, userId - topUpId); // mode为道具直购 String mode short_series_goods; // signData.put(mode, mode); // 可选优惠价格如果传入优惠价格必须比道具价格便宜且一旦传入则实际支付按照优惠价格 // if(payVo.getActivitySellingPrice() ! null){ // signData.put(activitySellingPrice, payVo.getActivitySellingPrice().multiply(new BigDecimal(100)).intValue()); // } // 将signData转为JSON字符串 String signDataJson JSON.toJSONString(signData); // 计算paySig String uri requestVirtualPayment; String paySig null; paySig calcPaySig(uri, signDataJson, AppKey); // 计算signature用户态签名 String signature calcSignature(signDataJson, user.getSessionKey()); // 返回给前端的数据 MapString, Object result new HashMap(); result.put(signData, signData); result.put(paySig, paySig); result.put(signature, signature); result.put(mode, mode); return Result.OK(result); } catch (Exception e) { e.printStackTrace(); return Result.error(获取虚拟支付配置异常: e.getMessage()); } } /** * 支付请求签名算法 * * param uri 当前请求的API的uri部分不带query_string例如/xpay/query_user_balance * param postBody HTTP POST的数据包体JSON字符串 * param appKey 对应环境的AppKey * return 支付请求签名pay_sig十六进制字符串 */ public static String calcPaySig(String uri, String postBody, String appKey) { String needSignMsg uri postBody; return hmacSha256(needSignMsg, appKey); } /** * HMAC-SHA256 签名并返回小写十六进制字符串 */ private static String hmacSha256(String data, String key) { try { Mac mac Mac.getInstance(HmacSHA256); SecretKeySpec secretKeySpec new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HmacSHA256); mac.init(secretKeySpec); byte[] hash mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); return bytesToHex(hash); } catch (Exception e) { throw new RuntimeException(HMAC-SHA256计算失败, e); } } /** * 字节数组转小写十六进制字符串 */ private static String bytesToHex(byte[] bytes) { StringBuilder sb new StringBuilder(); for (byte b : bytes) { sb.append(String.format(%02x, b)); } return sb.toString(); } /** * 用户登录态signature签名算法 * * param postBody HTTP POST的数据包体JSON字符串 * param sessionKey 当前用户有效的session_key * return 用户登录态签名signature十六进制字符串 */ public static String calcSignature(String postBody, String sessionKey) { return hmacSha256(postBody, sessionKey); }前端拉起支付孩子不是前端跳过后端支付接收回调如果微信调用指定的回调接口说明是支付成功了只有支付成功才会调用指定的回调接口本次写的回调接口只针对xpay_goods_deliver_notify通知类型进行处理微信方请求结构示意(我接到的是沙箱类型、1分钱对了微信的沙箱也是实际扣款的哟只是不给你加手续费而已哦记得使用安卓实验苹果的沙箱不支持、还有苹果少于1元的也不行哦){ ToUserName: gh_32c1a*******, FromUserName: *****6zm328OZRIJmCUZa7z*****, CreateTime: 177934****, MsgType: event, Event: xpay_goods_deliver_notify, OpenId: *****6zm328OZRIJmCUZa7z*****, OutTradeNo: *****553091461*****, WeChatPayInfo: { MchOrderNo: *****05211458250626*****, TransactionId: *****001682026052129114*****, PaidTime: 177934**** }, Env: 1, GoodsInfo: { ProductId: *****710771245*****, Quantity: 1, OrigPrice: 1, ActualPrice: 1, Attach: 我调起支付时传入的数据 }, RetryTimes: 0 }回调处理接口RequestMapping(/wxCallBack) ResponseBody public String wxNotify(HttpServletRequest request, HttpServletResponse response) throws IOException { log.info( 微信虚拟支付回调开始 ); try { // 1. 读取请求参数 String encryptType request.getParameter(encrypt_type); // 2. 读取请求体 InputStream inputStream request.getInputStream(); BufferedReader in new BufferedReader(new InputStreamReader(inputStream, UTF-8)); StringBuilder sb new StringBuilder(); String line; while ((line in.readLine()) ! null) { sb.append(line); } in.close(); inputStream.close(); String requestBody sb.toString(); log.info(收到微信回调请求encryptType: {}, requestBody: {}, encryptType, requestBody); String echostr request.getParameter(echostr); if (echostr ! null encryptType null){ // 说明在验证接口要取出echostr然后直接返回 log.info(收到微信回调请求encryptType: {}, echostr: {}, encryptType, echostr); return echostr; } // 3. 验证签名如果是安全模式需要解密 String decryptedBody requestBody; if (aes.equals(encryptType)) { // TODO: 如果需要支持安全模式需要实现AES解密逻辑 log.warn(当前为安全模式需要实现AES解密逻辑); // 这里可以使用微信提供的示例代码进行解密 // decryptedBody decryptAES(requestBody, msgSignature, signature, timestamp, nonce); } // 4. 解析JSON数据 JSONObject notifyData JSON.parseObject(decryptedBody); String event notifyData.getString(Event); String msgType notifyData.getString(MsgType); log.info(收到事件类型: {}, 消息类型: {}, event, msgType); // 5. 根据不同事件类型处理 String result ; if (xpay_coin_pay_notify.equals(event)) { // 代币支付推送 log.warn(不支持的事件类型: {}仅支持 xpay_goods_deliver_notify, event); result {\ErrCode\: -1, \ErrMsg\: \不支持的事件类型\}; } else if (xpay_goods_deliver_notify.equals(event)) { // 道具发货推送 result handleGoodsDeliverNotify(notifyData); } else if (xpay_refund_notify.equals(event)) { // 退款推送 log.warn(不支持的事件类型: {}仅支持 xpay_goods_deliver_notify, event); result {\ErrCode\: -1, \ErrMsg\: \不支持的事件类型\}; } else { log.warn(未处理的事件类型: {}, event); result success; } // 6. 返回响应给微信 log.info( 微信虚拟支付回调结束 ); return result; } catch (Exception e) { log.error(处理微信虚拟支付回调异常, e); // 返回错误响应微信会重试 String errorResponse {\ErrCode\: -1, \ErrMsg\: \ e.getMessage() \}; return errorResponse; } } private String handleGoodsDeliverNotify(JSONObject notifyData) { try { log.info( 处理道具发货推送 ); // 获取基本信息 String appId notifyData.getString(AppId); String openid notifyData.getString(OpenId); Long createTime notifyData.getLong(CreateTime); String outTradeNo notifyData.getString(OutTradeNo); // 商户订单号 Integer env notifyData.getInteger(Env); // 0-正式环境 1-沙箱环境 // 获取微信支付信息 JSONObject wechatPayInfo notifyData.getJSONObject(WeChatPayInfo); if (wechatPayInfo null) { log.error(WeChatPayInfo为空); return {\ErrCode\: -1, \ErrMsg\: \WeChatPayInfo为空\}; } String transactionId wechatPayInfo.getString(TransactionId); // 微信支付订单号 String MchOrderNo wechatPayInfo.getString(MchOrderNo); // 不知道什么的单号 Integer totalFee wechatPayInfo.getInteger(TotalFee); // 订单金额分 Integer payTime wechatPayInfo.getInteger(PaidTime); // 支付时间 // 获取道具信息 JSONObject goodsInfo notifyData.getJSONObject(GoodsInfo); if (goodsInfo null) { log.error(GoodsInfo为空); return {\ErrCode\: -1, \ErrMsg\: \GoodsInfo为空\}; } String attach goodsInfo.getString(Attach); // 附加数据拉起支付时放置的attach参数 String productId goodsInfo.getString(ProductId); // 道具ID Integer quantity goodsInfo.getInteger(Quantity); // 道具数量 log.info(道具发货通知 - 订单号: {}, 微信支付单号: {}, 金额: {}分, 道具ID: {}, 数量: {}, 附加数据: {}, outTradeNo, transactionId, totalFee, productId, quantity, attach); // 判断环境 boolean isSandbox (env ! null env 1); log.info(当前环境: {}, isSandbox ? 沙箱环境 : 正式环境); // 可以在此处理自己的业务逻辑喽 log.info( 道具发货推送处理成功 ); return {\ErrCode\: 0, \ErrMsg\: \OK\}; } catch (Exception e) { log.error(处理道具发货推送异常, e); return {\ErrCode\: -1, \ErrMsg\: \ e.getMessage() \}; } }此接口微信要调用记得免token处理或者接口接收微信传入的token代码中进行比对也可微信小程序的后台上配置回调接口的时候还会验证接口是否可用可以用微信自带的调试工具验证url配置验证是否通过https://developers.weixin.qq.com/apiExplorer?typemessagePush拿一下项目当前的accessToken再放一下自己项目的回到地址添加token请求就行了譬如我本次在进行验证的时候总是不通过改了发测试三五次都不行第一次是参数没接到第二次是token拦截到了直接将此接口进行了免token的处理第三次是接口里面的操作有问题验证时的参数没有我接口操作处理的参数导致中途报错第四次是返回参数和微信要的不一样我看微信的是返回success或空都可但这个是正常调用的时候接验证要参数是echostr ...服了微信要求的是接口上收到参数后自行检查验证我省事验证到接口传入的有echostr就直接返回
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2633199.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!