WeChat official account realizes WeChat payment (including the complete code of the front and back end)

I just finished the official account WeChat payment, record it. Before obtaining WeChat payment, you must first obtain the basic information of the user!

The front end uses the H5 developed by uniapp. Friends can change the corresponding grammar accordingly.
First of all, there is a tool class wxApi.js for WeChat payment. Here I put it in the common directory under the project. The code is as follows:

/*
    微信(公众号)支付方法
*/
const wx = require('jweixin-module');
const wexinPay = (data, callback, errorCallback) => {
    
    
	let [appId, timestamp, nonceStr, signature, packages, sign] = [data.appId, data.timeStamp, data.nonceStr, data
		.sign,
		data.package, data.sign
	];

	wx.config({
    
    
		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
		appId, // 必填,公众号的唯一标识
		timestamp, // 必填,生成签名的时间戳
		nonceStr, // 必填,生成签名的随机串
		signature, // 必填,签名,见附录1
		jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
	});
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', {
    
    
			appId: appId, //公众号名称,由商户传入
			timeStamp: timestamp, //时间戳,自1970年以来的秒数
			nonceStr: nonceStr, //随机串
			package: data.package,
			signType: data.signType, //微信签名方式:
			paySign: sign //微信签名
		},
		function(res) {
    
    
			if (res.err_msg == 'get_brand_wcpay_request:ok') {
    
    
				// 使用以上方式判断前端返回,微信团队郑重提示:
				//res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
				//支付成功回调
				callback(res)
				
				/* if (res.err_msg == 'get_brand_wcpay_request:cancel') */
			} else{
    
    
				//支付失败回调
				errorCallback(res)
			}
		}
	)
}

export default {
    
    
	wexinPay
}

Then just call this tool class in the page, the calling code is as follows:

this.$wxPay(payInfo, function(res) {
    
    
								uni.setStorageSync('type', '1')
								uni.showToast({
    
    
									title: '支付成功!',
									duration: 3000
								})
								uni.reLaunch({
    
    
									url: './xxx'
								})
							}, function(e) {
    
    
								uni.showToast({
    
    
									title: '支付失败!',
									duration: 3000
								})
							})

I jumped to another page, judged whether the type is equal to 1 on another page, and when it was equal to 1, modified the corresponding user table and order log table

The backend interface code is as follows:
String appID = xxx;
String mchID =xxx; //Merchant ID
String appSecret = xxx;
String key = “xxx”;

@Autowired
private PayLogService payLogService;
@PostMapping("/xxx")
public CommonResult wxjspay(HttpServletRequest request,PayLog payLog,@RequestParam(value="openid",required = false)String openid,@RequestParam(value="uid",required = false)String uid) throws Exception {

    //创建sdk客户端
    WXPay wxPay = new WXPay(new WXPayConfigCustom());
    //构造请求的参数
    Map<String,String> requestParam = new HashMap<>();

    //生成订单号 时间戳+用户id+6位随机数
    Integer ranNum = Math.toIntExact(Math.round((Math.random() + 1) * 1000));
    String tradeNo = System.currentTimeMillis()/1000+uid+ranNum;
    System.out.println("订单号==="+tradeNo);

    requestParam.put("out_trade_no",tradeNo);//订单号
    requestParam.put("body", "vip");//订单描述
    requestParam.put("fee_type", "CNY");//人民币
    requestParam.put("total_fee", String.valueOf(payLog.getPrice())); //金额
    requestParam.put("spbill_create_ip", IPUtils.getIpAddr(request));//客户端ip
    requestParam.put("notify_url", "none");//微信异步通知支付结果接口,暂时不用
    requestParam.put("trade_type", "JSAPI");

    log.info("ip地址==="+requestParam.get("spbill_create_ip"));

    requestParam.put("openid",openid);
    //调用统一下单接口
    Map<String, String> resp = wxPay.unifiedOrder(requestParam);

    Map resultMap = new HashMap();
    System.out.println("resp===="+resp.toString());
    System.out.println("resp.get(\"result_code\"====)"+resp.get("result_code"));
    if(resp.get("result_code").equals("SUCCESS")){
        System.out.println("同意下单接口==="+resp.toString());

        //准备h5网页需要的数据
        Map<String,String> jsapiPayParam = new HashMap<>();
        jsapiPayParam.put("appId",appID);
        jsapiPayParam.put("timeStamp",System.currentTimeMillis()/1000+"");
        jsapiPayParam.put("nonceStr", UUID.randomUUID().toString());//随机字符串
        jsapiPayParam.put("package","prepay_id="+resp.get("prepay_id"));
        jsapiPayParam.put("signType","HMAC-SHA256");
        jsapiPayParam.put("sign", WXPayUtil.generateSignature(jsapiPayParam,key, WXPayConstants.SignType.HMACSHA256));
        //将h5网页响应给前端
        System.out.println("111==="+jsapiPayParam.toString());

        //将数据添加到支付表
        payLog.setPubopenId(openid);
        payLog.setTransaction_id(tradeNo);
        payLog.setTotal_fee(240000);
        payLog.setResult_status(1);
        payLog.setResult_code(resp.get("result_code"));
        payLog.setReturn_code(resp.get("return_code"));
        payLog.setReturn_data(resp.get("return_data"));
        payLogService.addPayLog(payLog);

        resultMap.put("tradeNo",tradeNo);
        resultMap.put("jsapiPayParam",jsapiPayParam);

        return new CommonResult(200,"查询成功",resultMap);
    }else{
        return new CommonResult(100500,resp.get("err_code_des"));
    }
}
class  WXPayConfigCustom extends WXPayConfig {

    @Override
    protected String getAppID() {
        return appID;
    }

    @Override
    protected String getMchID() {
        return mchID;
    }

    @Override
    protected String getKey() {
        return key;
    }

    @Override
    protected InputStream getCertStream() {
        return null;
    }

    @Override
    protected IWXPayDomain getWXPayDomain() {
        return new IWXPayDomain() {
            @Override
            public void report(String s, long l, Exception e) {

            }

            @Override
            public DomainInfo getDomain(WXPayConfig wxPayConfig) {
                return new DomainInfo(WXPayConstants.DOMAIN_API,true);
            }
        };
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42322886/article/details/121773347
Recommended