Java配置
一种类型的支付
package com.hn.framework.config;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* 微信支付自动配置
*/
@Configuration
@Slf4j
public class WxPayAutoConfiguration {
private static WxPayService payService;
public static WxPayService getWxPayService() {
return payService;
}
@Value("${pay.wx.appId}")
private String appId;
@Value("${pay.wx.mchId}")
private String mchId;
@Value("${pay.wx.mchKey}")
private String mchKey;
@PostConstruct
public void init() {
log.info("微信支付初始化 appId={}", appId);
WxPayService wxPayService = new WxPayServiceImpl();
WxPayConfig payConfig = new WxPayConfig();
payConfig.setAppId(appId);
payConfig.setMchId(mchId);
payConfig.setMchKey(mchKey);
wxPayService.setConfig(payConfig);
payService = wxPayService;
log.info("微信支付初始化完毕 ");
}
}Copy to clipboardErrorCopied
多种类型支付
/**
* 微信支付自动配置
*/
@Configuration
@Slf4j
public class WxPayAutoConfiguration {
private static Map<String, WxPayService> wxPayServices = Maps.newHashMap();
public static WxPayService getWxPayService(String appid) {
WxPayService wxPayService = wxPayServices.get(appid);
if (wxPayService == null) {
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
}
return wxPayService;
}
@PostConstruct
public void init() {
log.info("微信支付初始化 userAppId={} lawyerAppId={}",WxConstants.userAppId,WxConstants.lawyerAppId);
// 用户端
put(WxConstants.userAppId);
// 律师端配置
put(WxConstants.lawyerAppId);
// 公众号,pc扫码支付
put(WxConstants.publicAppId);
log.info("微信支付初始化完毕 ");
}
private void put(String appId){
WxPayService wxPayService = new WxPayServiceImpl();
WxPayConfig payConfig = new WxPayConfig();
payConfig.setAppId(appId);
payConfig.setMchId(WxConstants.mchId);
payConfig.setMchKey(WxConstants.mchKey);
payConfig.setKeyPath("classpath:cert/apiclient_cert.p12");
wxPayService.setConfig(payConfig);
wxPayServices.put(appId,wxPayService);
}
}Copy to clipboardErrorCopied
App支付
public Object wxPay(String orderCode, BigDecimal price) {
WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
int totalFee = price.multiply(new BigDecimal("100")).intValue();
request.setTotalFee(totalFee);
request.setBody("共婵娟-充值会员");
request.setOutTradeNo(orderCode);
request.setSpbillCreateIp(IpUtils.getIpAddr());
request.setNotifyUrl(HnConfigUtils.getConfig("pay.wx.notifyUrl"));
request.setTradeType(WxPayConstants.TradeType.APP);
WxPayService wxPayService = WxPayAutoConfiguration.getWxPayService();
try {
return wxPayService.createOrder(request);
} catch (WxPayException e) {
throw new BusinessException(e.getMessage());
}
}Copy to clipboardErrorCopied
测试App支付
需要前端配合