【SpringBoot学习】39、SpringBoot 集成 wxJava 微信小程序:订单支付

SpringBoot 集成 wxJava 微信小程序:订单支付

1、整合 wxJava 小程序

导入相关依赖,最新版本的可以查看官方文档 wxJava

<!-- wxjava支付 -->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-pay</artifactId>
            <version>4.2.0</version>
        </dependency>

2、支付配置类

直接复制粘贴到项目

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Binary Wang
 */

@Configuration
@ConditionalOnClass(WxPayService.class)
@EnableConfigurationProperties(WxPayProperties.class)
@AllArgsConstructor
public class WxPayConfiguration 
{
  private WxPayProperties properties;

  @Bean
  @ConditionalOnMissingBean
  public WxPayService wxService() {
    WxPayConfig payConfig = new WxPayConfig();
    payConfig.setAppId(StringUtils.trimToNull(this.properties.getAppId()));
    payConfig.setMchId(StringUtils.trimToNull(this.properties.getMchId()));
    payConfig.setMchKey(StringUtils.trimToNull(this.properties.getMchKey()));
    payConfig.setSubAppId(StringUtils.trimToNull(this.properties.getSubAppId()));
    payConfig.setSubMchId(StringUtils.trimToNull(this.properties.getSubMchId()));
    payConfig.setKeyPath(StringUtils.trimToNull(this.properties.getKeyPath()));

    // 可以指定是否使用沙箱环境
    payConfig.setUseSandboxEnv(false);

    WxPayService wxPayService = new WxPayServiceImpl();
    wxPayService.setConfig(payConfig);
    return wxPayService;
  }

}

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * wxpay pay properties.
 *
 * @author Binary Wang
 */

@Data
@ConfigurationProperties(prefix = "wx.pay")
public class WxPayProperties {
  /**
   * 设置微信公众号或者小程序等的appid
   */

  private String appId;

  /**
   * 微信支付商户号
   */

  private String mchId;

  /**
   * 微信支付商户密钥
   */

  private String mchKey;

  /**
   * 服务商模式下的子商户公众账号ID,普通模式请不要配置,请在配置文件中将对应项删除
   */

  private String subAppId;

  /**
   * 服务商模式下的子商户号,普通模式请不要配置,最好是请在配置文件中将对应项删除
   */

  private String subMchId;

  /**
   * apiclient_cert.p12文件的绝对路径,或者如果放在项目中,请以classpath:开头指定
   */

  private String keyPath;

  /**
   * 支付回调
   */

  private String notifyUrl;
}

3、application.yml 配置

# 微信配置
wx:
  pay:
    appId: appid
    mchId: 商户id
    mchKey: 秘钥key
    keyPath: 证书地址/apiclient_cert.p12
    notifyUrl: 支付回调地址

4、授权登录流程

控制层

    @Autowired
    private WeiXinPayService weiXinPayService;

    @ApiOperation("统一下单")
    @PostMapping("createOrder")
    public AjaxResult createOrder(@RequestBody WxOrderVo entity) {
        return weiXinPayService.createOrder(entity);
    }

    @ApiOperation("支付回调")
    @RequestMapping("notifyUrl")
    public String notifyUrl() {
        return weiXinPayService.notifyUrl();
    }

service 接口


    /**
     * 统一下单
     *
     * @param entity
     * @return
     */

    AjaxResult createOrder(WxOrderVo entity);

    /**
     * 支付回调
     *
     * @return
     */

    String notifyUrl();

service 接口实现类

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayProperties wxPayProperties;

    @Override
    public AjaxResult createOrder(WxOrderVo entity) {
        try {
            String openId = SecurityUtils.getLoginUser().getUser().getOpenId();
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setSignType(WxPayConstants.SignType.MD5);
            orderRequest.setBody("请求支付订单");
            orderRequest.setOutTradeNo(UUID.randomUUID().toString().substring(032));
            orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(String.valueOf(entity.getPayMoney())));
            orderRequest.setOpenid(openId);
            orderRequest.setSpbillCreateIp(ServletUtils.getClientIP());
            orderRequest.setNotifyUrl(wxPayProperties.getNotifyUrl());
            Object order = wxPayService.createOrder(orderRequest);
            log.error("下单成功:{}", order.toString());
            return AjaxResult.success("下单成功", JSON.toJSONString(order));
        } catch (WxPayException e) {
            log.error("下单失败:{}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
    }

    @Override
    public String notifyUrl() {
        try {
            HttpServletRequest request = ServletUtils.getRequest();
            HttpServletResponse response = ServletUtils.getResponse();
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            log.info("订单支付回调:{}", result);
            // 加入自己处理订单的业务逻辑,需要判断订单是否已经支付过,否则可能会重复调用
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());

            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }

WxOrderVo

import lombok.Data;
import lombok.experimental.Accessors;

import java.math.BigDecimal;

/**
 * 微信订餐参数
 *
 * @author Tellsea
 * @date 2022/3/25
 */

@Data
@Accessors(chain = true)
public class WxOrderVo {

    private BigDecimal payMoney;
}

WxRefundVo

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * 微信退款参数
 *
 * @author Tellsea
 * @date 2022/3/25
 */

@Data
@Accessors(chain = true)
public class WxRefundVo {


}

OK ,到此后端调用逻辑都完成了

5、uniapp 前端

<template>
  <view style="padding: 15px;">
    <u-form :model="form" ref="uForm" label-width="140">
      <u-form-item label="支付金额"><u-input v-model="form.payMoney" /></u-form-item>
      <u-button @click="submit" type="primary">订单支付</u-button>
    </u-form>
  </view>
</template>

<script>
let that;
export default {
  name"createOrder",
  data() {
    return {
      form: {
        payMoney0.01
      }
    }
  },
  onLoad() {
    that = this;
  },
  methods: {
    submit() {
      that.$u.post('/au/weixinPay/createOrder', that.form).then(res => {
        let data = JSON.parse(res.data);
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.packageValue,
          signType: data.signType,
          paySign: data.paySign
        });
      });
    }
  }
}
</script>

<style scoped>

</style>


【SpringBoot学习】39、SpringBoot 集成 wxJava 微信小程序:订单支付【SpringBoot学习】39、SpringBoot 集成 wxJava 微信小程序:订单支付【SpringBoot学习】39、SpringBoot 集成 wxJava 微信小程序:订单支付【SpringBoot学习】39、SpringBoot 集成 wxJava 微信小程序:订单支付

微信公众号


原文始发于微信公众号(花海里):【SpringBoot学习】39、SpringBoot 集成 wxJava 微信小程序:订单支付

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69596.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!