微信小程序支付 + 公众号支付 (含源码)
注:本文来源于:CodeCow · 程序牛
=> 微信小程序支付 + 公众号支付 (含源码)
为啥会有这篇文章
最近换了个公司,接手了个别人的老项目,从git上拉取代码,导入idea时,我 TM 快哭了。。。
我瞅了眼微信支付
相关代码,顿时想上去就是 一Jao
! 我看到了这样的代码:
我靠,你这么写,倒是一时爽
;维护可就爽歪歪
咯!!!
怎么办,怎么办。。。
支付模块重构
别的先不说,重构之前我们先楼一眼微信部分支付流程图
注:上面是部分支付流程图(完整图片,可上官网查看)
重构项目全貌
- 项目架构:springboot(2.2.2) + mybatis
- 数据库:mysql
- 开发环境:jdk8、idea
- 支付:微信小程序、公众号
重构之后,代码简介、清爽,它不香吗!!
微信支付实操
1、controller层
/**
* Create By CodeCow on 2020/7/19.
*/
@Slf4j
@RestController
@RequestMapping("/pay")
public class WeiXinPayController {
@Resource
private WeiXinPayService weiXinPayService;
@ApiOperation(value = "微信支付(公众号/小程序)", response = WechatPayMiniRespDTO.class)
@ApiResponses({@ApiResponse(code = 0, message = "Success"), @ApiResponse(code = 500, message = "failed")})
@PostMapping(value = "/miniPay", consumes = "application/json", produces = "application/json")
public RespResult<WechatPayMiniRespDTO> weChatMiniBookOrderPay(@RequestBody @Valid WechatPayReqDTO wechatPayReqDTO) {
try {
return weiXinPayService.weChatBookOrderPay(wechatPayReqDTO);
} catch (Exception e) {
log.error("weChatBookOrderPay error: ", e);
return RespResult.error(RespResultEnum.WEIXIN_PAY_ERROR.getCode(),
RespResultEnum.WEIXIN_PAY_ERROR.getMessage() + e.getMessage());
}
}
}
2、service层
/**
* Create By CodeCow on 2020/7/19.
*/
public interface WeiXinPayService {
RespResult weChatBookOrderPay(WechatPayReqDTO wechatPayReqDTO);
}
快快快,拿出小本本,提起纸笔。。。开始装B
3、serviceImpl层
/**
* Create By CodeCow on 2020/7/19.
*/
@Slf4j
@Service
public class WeiXinPayServiceImpl implements WeiXinPayService {
@Resource
private UserMapper userMapper; //用户mapper
@Resource
private WechatConfig wechatConfig; //微信配置(在最后)
@Resource
private OrderMapper orderMapper; //订单mapper
@Resource
private CommonTemplateService templateService; // 自己封装的restTemplate(在最后)
@Override
public RespResult weChatBookOrderPay(WechatPayReqDTO wechatPayReqDTO) {
UserDO userDO = userMapper.selectById(wechatPayReqDTO.getUserId());
Long orderCode = TimeUtil.getTimestamp(); //生成随机订单号
WechatBookOrderReqDTO wechatBookOrderReqDTO //封装微信下单请求参数(此方法在下面)
= getBookOrderReqDTO(wechatPayReqDTO, orderCode, userDO);
String sign = //生成签名(签名工具类在最后)
WeChatSignUtil.getSign(wechatBookOrderReqDTO, wechatConfig.getApiKey());
wechatBookOrderReqDTO.setSign(sign);
String reqXML = XstreamUtil.objectToXml(wechatBookOrderReqDTO); //把请求参数转化成 xml 格式
log.info(">>>> reqXML >>>>:\n " + reqXML); //打印日志
ResponseEntity<String> responseEntity = //使用自己封装的restTemplate向微信发起请求
templateService.executePost(reqXML, wechatConfig.getBookOrderUrl());
if (responseEntity.getStatusCode().value() != HttpStatus.OK.value()) { //判断请求是否成功
return RespResult.error(RespResultEnum.ORDER_ERROR.getCode(),
RespResultEnum.ORDER_ERROR.getMessage() + responseEntity.getBody());
}
WechatBookOrderRespDTO wechatBookOrderRespDTO = // 把微信返回的参数封装到自己DTO中(DTO在最后)
XstreamUtil.xmlToObject(responseEntity.getBody(), WechatBookOrderRespDTO.class);
if (wechatBookOrderRespDTO.getXmlReturnCode().equals(WechatRespEnum.WECHAT_RETURN_CODE_FAIL.getCode())) { //判断微信响应结果
return RespResult.error(RespResultEnum.ORDER_RETURN_ERROR.getCode(),
RespResultEnum.ORDER_RETURN_ERROR.getMessage() + wechatBookOrderRespDTO.getXmlReturnMsg());
} else if (wechatBookOrderRespDTO.getXmlResultCode().equals(WechatRespEnum.WECHAT_RESULT_CODE_FAIL.getCode())) {
return RespResult.error(RespResultEnum.ORDER_RESULT_ERROR.getCode(),
RespResultEnum.ORDER_RESULT_ERROR.getMessage() + wechatBookOrderRespDTO.getXmlErrCodeDes());
}
insertRefuelOrder(userDO, wechatPayReqDTO, orderCode); //向数据库保存订单信息(方法在下面)
String nonceStr = WeChatSignUtil.getNonceStr();
long timestamp = TimeUtil.getTimestamp();
String paySign = WeChatPaySignUtil.getPaySign(wechatConfig.getAppId(), nonceStr, // 重新生成签名(前段调起支付需要)
wechatBookOrderRespDTO.getXmlPrepayId(), wechatConfig.getSignType(), String.valueOf(timestamp), wechatConfig.getApiKey());
WechatPayMiniRespDTO wechatPayMiniRespDTO = // 返回前段支付需要的DTO(DTO在最后)
getPayMiniRespDTO(paySign, nonceStr, timestamp, orderCode, wechatBookOrderRespDTO);
return RespResult.success(wechatPayMiniRespDTO); // 返回数据
}
private WechatBookOrderReqDTO getBookOrderReqDTO(WechatPayReqDTO wechatPayReqDTO, Long orderCode, UserDO userDO) {
return WechatBookOrderReqDTO.builder()
.appid(wechatConfig.getAppId())
.mch_id((wechatConfig.getMchId()))
.openid(userDO.getOpenid())
.trade_type(TradeTypeEnum.WECHAT_JSAPI.getType())
.nonce_str(WeChatSignUtil.getNonceStr())
.sign_type(wechatConfig.getSignType())
.body(wechatPayReqDTO.getDescription())
.out_trade_no(String.valueOf(orderCode))
.total_fee(wechatPayReqDTO.getTotalFee())
.spbill_create_ip(wechatPayReqDTO.getIp())
.time_start(String.valueOf(TimeUtil.getTimestamp()))
.notify_url(wechatConfig.getNotifyUrl())
.build();
}
private void insertRefuelOrder(UserDO userDO, WechatPayReqDTO wechatPayReqDTO, Long orderCode) {
OrderDO orderDO = OrderDO.builder()
.id(TimeUtil.getTimestamp())
.userId(String.valueOf(userDO.getUserId()))
.orderCode(String.valueOf(orderCode))
.status("0")
.totalFee(new BigDecimal(wechatPayReqDTO.getTotalFee()))
.payType("1") //支付类型(1-微信,2-支付宝)
.detail(wechatPayReqDTO.getDescription())
.createTime(TimeUtil.now())
.build();
orderMapper.insert(orderDO);
}
private WechatPayMiniRespDTO getPayMiniRespDTO(String paySign, String nonceStr, long timestamp,
Long orderCode, WechatBookOrderRespDTO wechatBookOrderRespDTO) {
return WechatPayMiniRespDTO.builder()
.paySign(paySign)
.nonceStr(nonceStr)
.outTradeNo(String.valueOf(orderCode))
.ppackage(ColumnNames.PARAM_PREPAY_ID + wechatBookOrderRespDTO.getXmlPrepayId())
.signType(wechatConfig.getSignType())
.timeStamp(String.valueOf(timestamp))
.tradeType(wechatBookOrderRespDTO.getXmlTradeType())
.build();
}
}
4、WechatPayMiniRespDTO
/**
* Create By CodeCow on 2020/7/19.
*/
@Data
@Builder
@ApiModel("微信小程序/公众号支付返回参数")
public class WechatPayMiniRespDTO {
@ApiModelProperty(value = "时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间", required = true)
private String timeStamp;
@ApiModelProperty(value = "随机字符串,不长于32位", required = true)
private String nonceStr;
@ApiModelProperty(value = "统一下单接口返回的 prepay_id 参数值", required = true)
@JsonProperty(value = "package")
private String ppackage;
@ApiModelProperty(value = "MD5", required = true)
private String signType;
@ApiModelProperty(value = "前端调用微信支付功能所需签名", required = true)
private String paySign;
@ApiModelProperty(value = "交易类型", required = true)
private String tradeType;
@ApiModelProperty(value = "订单号")
private String outTradeNo;
}
代码实在有点多,写到这,手都酸了。。。
好文推荐
小声BB
- 由于
支付代码
比较多,小编就不挨个粘贴了 -
若需要完整
“ 源码 ”
可在公众号内回复“微信支付
”,发百度网盘
弱弱问一句
-
看完了,支付还用自己写吗