主要参数都是从后端获取的,非常考验后端的签名,签名不对就要调试很久,切记官方的 java-sdk
可能是有问题的总是签名失败,当然也许是我们的后端使用方式不对
import { useState } from "react";const usePay = (success: () => void, failed?: () => void) => {const [payLoading, setPayLoading] = useState(false);// jsapi方法const onBridgeReady = (appId: any, timeStamp: any, nonceStr: any, pkg: any, paySign: any, signType: any) => {try {console.log("Pay log", {appId, timeStamp, nonceStr, pkg, signType, paySign });(window as any).WeixinJSBridge.invoke("getBrandWCPayRequest",{appId: appId, // 需要在微信绑定商户号,成功之后会生成有appidtimeStamp: timeStamp, // 时间戳,自1970年以来的秒数,前端需要从后台获取该数据nonceStr: nonceStr, // 随机串,前端需要从后台获取该数据package: pkg, // 前端需要从后台获取该数据signType: signType, // 微信签名方式,默认为"MD5",也可以从后台获取paySign: paySign, // 微信签名,前端需要从后台获取该数据},function (res) {console.log(res.err_msg);if (res.err_msg == "get_brand_wcpay_request:ok") {console.log("购买成功");success();} // 使用以上方式判断前端返回, 微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。else {console.log("购买失败");failed?.();}setPayLoading(false);});} catch (error) {console.log("usePay-onBridgeReady error:", error);setPayLoading(false);}};const payAction = async (payParams: {appId: string;timeStamp: string;nonceStr: string;pkg: string;paySign: string;signType: string;}) => {try {setPayLoading(true);const { appId, timeStamp, nonceStr, pkg, paySign, signType } = payParams;const pay = () => {onBridgeReady(appId, timeStamp, nonceStr, pkg, paySign, signType);}if (typeof (window as any).WeixinJSBridge == "undefined") {if (document.addEventListener) {(document.addEventListener as any)("WeixinJSBridgeReady", pay, false);} else if ((document as any).attachEvent) {(document as any).attachEvent("WeixinJSBridgeReady", pay);(document as any).attachEvent("onWeixinJSBridgeReady", pay);}} else {// 传入下面参数,这些参数需要从后台获取 (下单接口获取, 问后台要)pay()}} catch (error) {console.log("usePay-payAction error:", error);setPayLoading(false);}};return { payAction, payLoading };
};
export default usePay;