最近在开发微信小程序过程中,接入了微信支付功能。前后花了不少时间,今天终于发起一笔支付,并且支付成功。现在把微信支付的流程记录下来。
一、准备商户信息
这个需要开通微信支付商户信息,我这里是企业性质,所以按照要求提交营业执照,法人信息就可以申请下来。
商户申请之后,还需要关联小程序appid,登录商户信息,下载开发所需的证书。这里证书是p12格式,一般我们不用这个,需要使用证书apicient_cert.pem和私钥apiclient_key.pem。
还有商户号merchantId,证书序列号merchantSerialNumber。还有一个api-v3-key,这个是我们开发人员自己设置的一个32位字符串,我记着是在申请证书的时候,填入商户信息里面的。开发人员需要保存。另外我个人根据自己的情况,还需要一个公共证书(也是在商户管理页面下载)public_key.pem和一个公钥public-key-id字符串,在公钥页面也能看到,复制给开发人员即可。
二、开发配置
微信支付,主要还是后端开发,这里类似于微信小程序里面调起手机号的功能,前端无法直接发起请求,只能后端发起。
这里java后端的配置,主要有一个证书相关的配置。
引入sdk
<dependency> <groupId>com.github.wechatpay-apiv3</groupId> <artifactId>wechatpay-java</artifactId> <version>0.2.17</version> </dependency>支付配置类WxPayConfig
import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.RSAPublicKeyConfig; import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource("wxpay.properties") @ConfigurationProperties(prefix = "v3") public class WxPayConfig { @Value("${v3.merchant-id}") private String merchantId; @Value("${v3.private-key-path}") private String privateKeyPath; @Value("${v3.public-key-id}") private String publicKeyId; @Value("${v3.public-key-path}") private String publicKeyPath; @Value("${v3.merchant-serial-number}") private String merchantSerialNumber; @Value("${v3.api-v3-key}") private String apiV3Key; @Value("${v3.notify-url}") private String notifyUrl; @Bean public Config wxCustomConfig() { return new RSAPublicKeyConfig.Builder() .merchantId(merchantId) .privateKeyFromPath(privateKeyPath) .publicKeyId(publicKeyId) .publicKeyFromPath(publicKeyPath) .merchantSerialNumber(merchantSerialNumber) .apiV3Key(apiV3Key) .build(); } @Bean public JsapiServiceExtension jsapiService() { return new JsapiServiceExtension.Builder().config(wxCustomConfig()).build(); } public String getMerchantId() { return merchantId; } public String getNotifyUrl() { return notifyUrl; } }wxpay.properties
v3.merchant-id=1102598xxx v3.private-key-path=apiclient_key.pem v3.merchant-serial-number=40A59577488601B83F45C5BE5C45423633B8Dxxx v3.api-v3-key=7E4B94dd83acd6419918b81b7a2caxxx v3.public-key-id=PUB_KEY_ID_0111025983422026011400211558002xxx v3.public-key-path=pub_key.pem v3.notify-url=https://localhost/payment/notify这个配置类里面,使用RSAAutoCertificateConfig配置的时候,报错。所以换了RSAPublicKeyConfig类。
其实,后端支付开发,主要是要根据前端交易信息来生成一个预支付订单,然后小程序拿到这个预支付订单返回的信息,调起微信支付,完成支付。小程序需要发起一个预支付请求。这个预支付请求里面需要携带商品信息,比如:商品描述,价格,还有一个谁支付的,也就是支付人的信息,这里参数叫openid。这个需要前端先发起一个通过wx.login()登录返回的code码调用后端代码获取这个openid请求,换取openid的接口:https://api.weixin.qq.com/sns/jscode2session。
预支付接口service层代码:
PayService.java
public interface PayService { void closeOrder(); Transaction queryOrderById(); Transaction queryOrderByOutTradeNo(); PrepayWithRequestPaymentResponse prepay(ProductVo productVo); void nonce(Map<String,Object> msg); }PayServiceImpl.java主要代码
@Override public PrepayWithRequestPaymentResponse prepay(ProductVo productVo) { PrepayRequest request = new PrepayRequest(); // 必填字段 appid mchid description out_trade_no notify_url amount payer(openid) request.setAppid(appId); request.setMchid(wxPayConfig.getMerchantId()); request.setNotifyUrl(wxPayConfig.getNotifyUrl()); Amount amount = new Amount(); amount.setCurrency("CNY"); amount.setTotal((int) (productVo.getPrice()*100)); request.setAmount(amount); request.setDescription(productVo.getDescription()); request.setOutTradeNo(NumberUtil.generateOutTradeNo()); Payer payer = new Payer(); payer.setOpenid(productVo.getOpenID()); request.setPayer(payer); return jsapiService.prepayWithRequestPayment(request); }调起支付所需的参数,官方示例给的是jsapiservice.prepay()。但是这个方法返回的是一个prepay_id=xxx的参数,我们在前端小程序调起支付的时候,它还需要这些参数:
wx.requestPayment({ "nonceStr":nonceStr, "package": packageVal, "paySign": paySign, "timeStamp": timeStamp, "signType": "RSA", "success": function(res) { console.log(res) }, "fail": function(err) { console.log("err",err) }, "complete": function(res){ console.log("complete",res) } })这里packageVal的值,就是jsapiservice.prepay()返回的。其他的timeStamp,paySign,nonceStr几个参数还是需要我们自己来设置。那么就有了JsapiServiceExtension类,它内部引用了JsapiService类,也会调用它的prepay()方法,同时,还会包装其他几个参数,正好构成我们调起小程序的主要参数,signType我们自己填上,而且只能填写RSA。
我们可以看看JsapiServiceExtension.prepayWithRequestPayment()方法。
public PrepayWithRequestPaymentResponse prepayWithRequestPayment(PrepayRequest request) { String prepayId = this.jsapiService.prepay(request).getPrepayId(); long timestamp = Instant.now().getEpochSecond(); String nonceStr = NonceUtil.createNonce(32); String packageVal = "prepay_id=" + prepayId; String message = request.getAppid() + "\n" + timestamp + "\n" + nonceStr + "\n" + packageVal + "\n"; logger.debug("Message for RequestPayment signatures is[{}]", message); String sign = this.signer.sign(message).getSign(); PrepayWithRequestPaymentResponse response = new PrepayWithRequestPaymentResponse(); response.setAppId(request.getAppid()); response.setTimeStamp(String.valueOf(timestamp)); response.setNonceStr(nonceStr); response.setPackageVal(packageVal); response.setSignType(this.signType); response.setPaySign(sign); return response; }这个方法是sdk推荐的方法。
预支付controller层代码
@RequestMapping("/payment") public class PaymentController { @Autowired private PayService payService; @ApiOperation("预支付") @PostMapping("/prepay") public ResultData prepay(@RequestBody ProductVo productVo) { PrepayWithRequestPaymentResponse response = payService.prepay(productVo); return ResultData.success(response); } @ApiOperation("通知") @PostMapping("/notify") public ResultData paymentNotify(@RequestBody Map<String,Object> msg) { // {id:"",create_time:"",resource_type:"",event_type:"",summary:"",resource:{}} payService.nonce(msg); return ResultData.success(); } }以上就是java后端要作的相关工作,总结一下就是配置商户、证书相关信息。然后调用JsapiServiceExtension类的预支付接口,生成小程序调起支付功能的相关参数。微信小程序端支付成功之后,有一个回调地址,我们需要配置,然后根据支付回调更改订单支付状态。
三、前端开发
前端开发需要配合的就是
第一个需要获取支付人的信息也就是openid。这个可以通过wx.login()返回值code去后台接口换取: https://api.weixin.qq.com/sns/jscode2session。
第二个就是预支付,这里我们传入我们需要支付的商品主要信息:商品描述,商品价格,支付者openid。
第三个调起支付,这里小程序提供了wx.requestPayment()方法。这个方法需要传入五个必填参数:nonceStr,package,timeStamp,paySign,signType。
关于微信支付,主要配置在后端。前端只是通过接口调用。
我这里的需求是微信小程序调起支付,使用的是jsapi这种方式,很多例子里面会提到native这种方式,这种方式也是支付的一种方式,但是它是生成一个商户支付的二维码,然后用户扫码支付,类似于我们在街头买吃的,扫商家码付款。通过jsapi这种方式,我们是直接调起微信支付,少了扫码这个环节。
我在开发者工具里面写好代码,调试的时候,发现在调起支付这里,接口调用是没问题的,但是因为本地开发,无法调起微信支付,所以它弹出了一个二维码,让手机扫码支付。感觉这个功能又有点像native的方式,给你返回一个二维码,扫码支付。