本文主要讲的是小程序实现微信支付功能,后台采用java。
一.准备工作
1.小程序
2.微信商户号
1.商户号申请
这里对小程序的申请不做赘述。
如果没有微信商户号的同学,点击该链接https://pay.weixin.qq.com/,按照下属步骤进行商户号申请。
扫码之后点击"成为商家",这里主要有个体工商户和企业,按照事实填写,然后按照步骤填写就行了。
主要需要营业执照,法人信息,公账信息等。
2.微信商户号关联小程序
点击"产品中心"的"开发配置",点击"新增授权申请单"。
输入你的小程序appid,点击下一步。
然后到小程序后台>微信支付>商户号管理里,会出现一个申请单,点击“查看”。
点击确认绑定,这样你的商户号就与小程序进行绑定了。
二.代码编写
1.小程序
小程序这块主要是调用一下后台接口获取参数,然后通过参数拉起微信支付。
orderpay(payinfo){ let that = this wx.requestpayment({ 'timestamp': payinfo.timestamp, 'noncestr': payinfo.noncestr, 'package': payinfo.package, 'signtype': payinfo.signtype, 'paysign': payinfo.paysign, 'success': function (res) { // 支付成功的回调 }, 'fail': function (res) { console.log(json.stringify(res)); wx.showtoast({title: '支付失败', icon: 'none',duration: 2000,mask: true}) } }) },
这里的payinfo就是从后台接口获取的支付参数,通过wx.requestpayment就可以拉起微信支付了。具体的参数信息在下面会进行讲解。
2.服务端(java)
服务端这边主要是三个接口:
1.提交支付订单
这个主要是为了获取提交支付订单,获取前端拉起支付的参数。
2.微信支付回调
当你小程序拉起支付并且成功支付后,会将支付结果回调到这个接口
3.支付订单查询
你也可以主动通过订单号查询支付订单状态
下面是我的代码,包含了我的业务代码,大家将就着看吧
controller:
import com.smart.iot.gmt.app.bean.commonreponse; import com.smart.iot.gmt.app.constant.responsecontant; import com.smart.iot.gmt.app.constant.sessionkeyconstants; import com.smart.iot.gmt.app.request.wechatpay.paymentrequest; import com.smart.iot.gmt.app.request.wechatpay.querypayorderrequest; import com.smart.iot.gmt.app.response.wechat.wechatpaymentresponse; import com.smart.iot.gmt.app.response.wechat.wechatquerypayorderresponse; import com.smart.iot.gmt.app.service.commonservice; import com.smart.iot.gmt.app.service.pay.wechat.wxpayservice; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.httpservletrequest; import java.util.map; @slf4j @restcontroller public class wxpaycontroller { @autowired private wxpayservice service; @autowired private commonservice commonservice; /** * * @author rick chou * @date 2024/7/18 15:33 * 提交支付 * */ @postmapping("/payment") public commonreponse payment(@requestbody paymentrequest paymentrequest) { integer price = paymentrequest.getprice(); string orderid = paymentrequest.getorderid(); map<string, object> result = service.payment(price, orderid, userid); commonreponse commonresponse = commonservice.getcommonresponse(responsecontant.success_code, responsecontant.success, result); return new wechatpaymentresponse(commonresponse,result); } /** * * @author rick chou * @date 2024/7/15 16:57 * 微信支付回调 * */ @postmapping("/paynotify") public void paynotify(httpservletrequest request) throws exception { service.paynotify(request); } /** * * @author rick chou * @date 2024/7/15 16:57 * 支付查询 * */ @postmapping("/querypayorder") public commonreponse querypayorder(@requestbody querypayorderrequest request) { map<string, object> result = service.querypayorder(request); commonreponse commonresponse = commonservice.getcommonresponse(responsecontant.success_code, responsecontant.success, result); return new wechatquerypayorderresponse(commonresponse,result); } }
service:
import com.alibaba.fastjson.json; import com.smart.iot.constant.rediskeys; import com.smart.iot.device.dto.locknotifymessagedto; import com.smart.iot.device.service.devicerediscacheservice; import com.smart.iot.gmt.app.annotation.springutil; import com.smart.iot.gmt.app.bo.*; import com.smart.iot.gmt.app.entity.memberorderdetailentity; import com.smart.iot.gmt.app.enums.memberorderstateenum; import com.smart.iot.gmt.app.request.wechatpay.querypayorderrequest; import com.smart.iot.gmt.app.service.locknotifymessageservice; import com.wechat.pay.java.service.payments.model.transaction; import lombok.extern.slf4j.slf4j; import org.springframework.stereotype.service; import javax.servlet.http.httpservletrequest; import javax.transaction.transactional; import java.util.map; @slf4j @service public class wxpayservice { public map<string, object> payment(integer price, string orderid, string userid){ map<string, object> result = wechatpaybo.payment(price, orderid, userid); return result; } @transactional public void paynotify(httpservletrequest request) throws exception { transaction parse = wechatpaybo.paynotify(request); updateaccountdetail(parse,false); } @transactional public map<string,object> querypayorder(querypayorderrequest request) { string orderid = request.getorderid(); transaction parse = wechatpaybo.querypayorder(orderid); return updateaccountdetail(parse,true); } /** * * @author rick chou * @date 2024/7/16 11:03 * 支付回调处理 * 1.更新订单状态 * 2.添加支付记录 * 3.通知小程序 * */ public map<string,object> updateaccountdetail(transaction parse, boolean active) { string orderid = parse.getouttradeno(); transaction.tradestateenum tradestate = parse.gettradestate(); if(tradestate==transaction.tradestateenum.success) { if(orderbo.check(orderid).getstate() == memberorderstateenum.in_progress.code) { orderbo order = this.updateorder(orderid); this.renewmember(orderid); this.saverecord(parse, order.getuserid()); } } if(active){ return json.parseobject(buildparse(parse),map.class); }else{ this.paynoticemessage(parse,orderid); } return null; } /** * * @author rick chou * @date 2024/7/19 15:31 * 更新订单状态 * */ private orderbo updateorder(string orderid){ orderbo order = orderbo.check(orderid); order.finish(); string key = rediskeys.add_order_pay_time_prefix + orderid; springutil.getbean(devicerediscacheservice.class).delete(key); return order; } /** * * @author rick chou * @date 2024/7/19 15:32 * 更新会员时间 * */ private void renewmember(string orderid){ memberorderdetailentity orderdetail = orderdetailbo.getbyorderid(orderid); usermemberbo.renew(orderdetail); } /** * * @author rick chou * @date 2024/7/19 15:33 * 保存支付记录 * */ private void saverecord(transaction parse,string userid){ string orderid = parse.getouttradeno(); integer amount = parse.getamount().gettotal(); string tradetype = parse.gettradetype().name(); payrecordbo.create(userid,orderid,amount,tradetype); } /** * * @author rick chou * @date 2024/7/19 15:38 * 将支付结果下发小程序 * */ private void paynoticemessage(transaction parse,string orderid){ memberorderdetailentity detail = orderdetailbo.getbyorderid(orderid); locknotifymessageservice service = springutil.getbean(locknotifymessageservice.class); locknotifymessagedto dto = new locknotifymessagedto(); dto.setlockid(detail.getdeviceid()); dto.setmessageparams(buildparse(parse)); service.dealpayresultnotifymessage(dto); } private string buildparse(transaction parse){ parse.setmchid(null); parse.setappid(null); parse.setbanktype(null); parse.setbanktype(null); parse.setattach(null); return json.tojsonstring(parse); } }
bo:
import com.smart.iot.gmt.app.annotation.springutil; import com.smart.iot.gmt.app.entity.payrecordentity; import com.smart.iot.gmt.app.service.pay.wechat.payinfoconfig; import com.smart.iot.gmt.app.service.pay.wechat.wxpayutil; import com.smart.iot.util.stringutil; import com.wechat.pay.java.core.config; import com.wechat.pay.java.core.rsaautocertificateconfig; import com.wechat.pay.java.core.exception.serviceexception; import com.wechat.pay.java.core.exception.validationexception; import com.wechat.pay.java.core.notification.notificationconfig; import com.wechat.pay.java.core.notification.notificationparser; import com.wechat.pay.java.core.notification.requestparam; import com.wechat.pay.java.service.payments.jsapi.jsapiservice; import com.wechat.pay.java.service.payments.jsapi.model.*; import com.wechat.pay.java.service.payments.model.transaction; import lombok.extern.slf4j.slf4j; import org.springframework.stereotype.component; import javax.servlet.http.httpservletrequest; import java.io.ioexception; import java.util.hashmap; import java.util.map; import java.util.uuid; import java.util.stream.collectors; import java.util.stream.stream; import static com.wechat.pay.java.core.http.constant.*; /** * * @author rick chou * @date 2024/7/16 9:10 * 微信支付bo * */ @slf4j @component public class wechatpaybo extends payrecordentity { private static payinfoconfig getconfig(){ payinfoconfig payinfoconfig = springutil.getbean(payinfoconfig.class); return payinfoconfig; } /** * * @author rick chou * @date 2024/7/16 9:35 * 构建支付请求service * */ public static jsapiservice getservice(){ payinfoconfig payinfoconfig = getconfig(); config config = new rsaautocertificateconfig.builder() .merchantid(payinfoconfig.getmchid()) .privatekeyfrompath(payinfoconfig.getkeypath()) .merchantserialnumber(payinfoconfig.getmchserialno()) .apiv3key(payinfoconfig.getapikey()) .build(); jsapiservice service = new jsapiservice.builder().config(config).build(); return service; } /** * * @author rick chou * @date 2024/7/16 10:31 * 构造notify_config * */ private static notificationconfig buildnotifyconfig(){ payinfoconfig payinfoconfig = getconfig(); notificationconfig config = new rsaautocertificateconfig.builder() .merchantid(payinfoconfig.getmchid()) .privatekeyfrompath(payinfoconfig.getkeypath()) .merchantserialnumber(payinfoconfig.getmchserialno()) .apiv3key(payinfoconfig.getapikey()) .build(); return config; } /** * * @author rick chou * @date 2024/7/16 9:35 * 构建支付请求参数 * */ private static prepayrequest buildparam(integer price, string orderid, string userid){ payinfoconfig payinfoconfig = getconfig(); prepayrequest prepayrequest = new prepayrequest(); amount amount = new amount(); amount.settotal(price); prepayrequest.setamount(amount); prepayrequest.setappid(payinfoconfig.getappid()); prepayrequest.setmchid(payinfoconfig.getmchid()); prepayrequest.setnotifyurl(payinfoconfig.getnotifyurl()); // 回调接口地址 prepayrequest.setdescription("微信支付"); prepayrequest.setouttradeno(orderid); // 订单号 prepayrequest.setattach("member"); // 订单类型(回调时可根据这个数据辨别订单类型或其他) //根据token拿到openid,指定该预支付订单的支付者身份 payer payer = new payer(); payer.setopenid(weixinuserbo.getopenid(userid)); prepayrequest.setpayer(payer); return prepayrequest; } /** * * @author rick chou * @date 2024/7/16 9:53 * 解析支付结果 * */ private static map<string,object> parsepay(prepayresponse response){ payinfoconfig payinfoconfig = getconfig(); map<string, object> params = new hashmap<>(); long timestamp = system.currenttimemillis() / 1000; string substring = uuid.randomuuid().tostring().replaceall("-", "").substring(0, 32); string signaturestr = stream.of( payinfoconfig.getappid(), string.valueof(timestamp), substring, "prepay_id=" + response.getprepayid() ).collect(collectors.joining("\n", "", "\n")); string sign = wxpayutil.getsign(signaturestr, payinfoconfig.getkeypath()); params.put("timestamp", string.valueof(timestamp)); params.put("noncestr", substring); params.put("paysign", sign); params.put("signtype", "rsa"); params.put("package", "prepay_id=" + response.getprepayid()); return params; } /** * * @author rick chou * @date 2024/7/16 10:33 * 解析回调结果 * */ private static requestparam parsenotify(httpservletrequest request)throws ioexception { string data = stringutil.getstringforinput(request.getinputstream()); string timestamp = request.getheader(wechat_pay_timestamp); string nonce = request.getheader(wechat_pay_nonce); string signtype = request.getheader("wechatpay-signature-type"); string serialno = request.getheader(wechat_pay_serial); string signature = request.getheader(wechat_pay_signature); requestparam requestparam = new requestparam.builder() .serialnumber(serialno) .nonce(nonce) .signature(signature) .timestamp(timestamp) .signtype(signtype) // 若未设置signtype,默认值为 wechatpay2-sha256-rsa2048 .body(data) .build(); return requestparam; } /** * * @author rick chou * @date 2024/7/16 9:47 * 调起支付 * */ public static map<string, object> payment(integer price, string orderid, string userid){ jsapiservice service = getservice(); prepayrequest prepayrequest = buildparam(price, orderid, userid); prepayresponse response = service.prepay(prepayrequest); map<string, object> result = parsepay(response); result.put("orderid",orderid); return result; } /** * * @author rick chou * @date 2024/7/16 10:16 * 支付回调 * */ public static transaction paynotify(httpservletrequest request) throws exception { notificationconfig config = buildnotifyconfig(); notificationparser parser = new notificationparser(config); requestparam requestparam = parsenotify(request); transaction parse = null; try { parse = parser.parse(requestparam, transaction.class); }catch (validationexception e){ log.error("sign verification failed", e); } return parse; } /** * * @author rick chou * @date 2024/7/16 11:17 * 查询订单 * */ public static transaction querypayorder(string orderid) { payinfoconfig payinfoconfig = getconfig(); jsapiservice service = getservice(); queryorderbyouttradenorequest queryrequest = new queryorderbyouttradenorequest(); queryrequest.setmchid(payinfoconfig.getmchid()); queryrequest.setouttradeno(orderid); transaction parse = null; try { parse = service.queryorderbyouttradeno(queryrequest); }catch (serviceexception e){ log.info("code=[%s], message=[%s]\n", e.geterrorcode(), e.geterrormessage()); log.info("reponse body=[%s]\n", e.getresponsebody()); } return parse; } }
payinfoconfig
import lombok.data; import lombok.tostring; import org.springframework.boot.context.properties.configurationproperties; import org.springframework.stereotype.component; @data @tostring @component @configurationproperties(prefix = "wx") public class payinfoconfig { //小程序appid private string appid; //商户号 private string mchid; //证书序列号 private string mchserialno; //小程序秘钥 private string appsecret; //api秘钥 private string apikey; //回调接口地址 private string notifyurl; //证书地址 private string keypath; }
上述的payinfoconfig中的参数第二、三、五、七个参数去商户号后台获取。
三.补充说明
在实际的支付开发中需要注意一些比较重要的点,假设你现在做的是一个会员开通功能。
1.在你点击开通的时候,你需要做的肯定是调用你自己的后台业务接口生成一个会员订单,同时调用微信支付获取支付参数返回到前端。这样用户看到的就是直接拉起支付。
2.当你执行支付操作后你的支付回调接口会收到支付结果,这个时候你服务端要主动通知小程序,并且当小程序拉起支付后要定时调用支付查询接口来主动查询支付完成支付。做个双保险比较好。
3.微信支付完成后有个"完成"按钮,点击后就会回到wx.requestpayment的success回调里,这里最好也要查询下订单状态。
4.还有点我还没怎么做处理,也是个题外话,就是当支付回调时服务器挂了咋整,得想个万全之策,这个就交给你们解答了。
到此这篇关于利用微信小程序+java实现微信支付的文章就介绍到这了,更多相关微信小程序 java实现微信支付内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论