第8章 支付.md 43 KB

谷粒随享

第8章 微信支付充值业务

学习目标:

  • 微信支付(对接第三方支付平台)
  • 基于微信支付完成订单付款
  • 基于微信支付完成充值业务

1、微信支付

1.1 保存交易记录

需求:当用户进行订单、充值 微信支付为每笔交易产生一条本地交易记录,将来用于对账。

1.1.1 获取订单对象

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/100

已有Restful接口实现。只需要在service-order-client模块中新增Feign远程调用方法

OrderFeignClient

package com.atguigu.tingshu.order.client;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.impl.OrderDegradeFeignClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * <p>
 * 订单模块远程调用API接口
 * </p>
 *
 * @author atguigu
 */
@FeignClient(value = "service-order", path = "api/order", fallback = OrderDegradeFeignClient.class)
public interface OrderFeignClient {


    /**
     * 根据订单编号查询订单详情(订单商品明细、订单优惠明细)
     *
     * @param orderNo
     * @return
     */
    @GetMapping("/orderInfo/getOrderInfo/{orderNo}")
    public Result<OrderInfo> getOrderInfo(@PathVariable String orderNo);

}

OrderDegradeFeignClient熔断类:

package com.atguigu.tingshu.order.client.impl;


import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OrderDegradeFeignClient implements OrderFeignClient {

    @Override
    public Result<OrderInfo> getOrderInfo(String orderNo) {
        log.error("[订单模块]提供远程调用getOrderInfo服务降级");
        return null;
    }
}

1.1.2 获取充值记录信息

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/101

service-account 微服务RechargeInfoApiController控制器中添加

package com.atguigu.tingshu.account.api;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "充值管理")
@RestController
@RequestMapping("api/account")
@SuppressWarnings({"all"})
public class RechargeInfoApiController {

	@Autowired
	private RechargeInfoService rechargeInfoService;


	/**
	 * 根据充值订单编号查询充值记录
	 * @param orderNo
	 * @return
	 */
	@Operation(summary = "根据充值订单编号查询充值记录")
	@GetMapping("/rechargeInfo/getRechargeInfo/{orderNo}")
	public Result<RechargeInfo> getRechargeInfo(@PathVariable String orderNo){
		RechargeInfo rechargeInfo = rechargeInfoService.getRechargeInfo(orderNo);
		return Result.ok(rechargeInfo);
	}

}

RechargeInfoService接口

package com.atguigu.tingshu.account.service;

import com.atguigu.tingshu.model.account.RechargeInfo;
import com.baomidou.mybatisplus.extension.service.IService;

public interface RechargeInfoService extends IService<RechargeInfo> {

    /**
     * 根据充值订单编号查询充值记录
     * @param orderNo
     * @return
     */
    RechargeInfo getRechargeInfo(String orderNo);
}

RechargeInfoServiceImpl实现类

package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	/**
	 * 根据充值订单编号查询充值记录
	 * @param orderNo
	 * @return
	 */
	@Override
	public RechargeInfo getRechargeInfo(String orderNo) {
		LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
		return rechargeInfoMapper.selectOne(queryWrapper);
	}
}

远程调用模块service-account-clientAccountFeignClient增加远程调用方法

/**
 * 根据充值订单编号查询充值记录
 * @param orderNo
 * @return
 */
@GetMapping("/rechargeInfo/getRechargeInfo/{orderNo}")
public Result<RechargeInfo> getRechargeInfo(@PathVariable String orderNo);

AccountDegradeFeignClient熔断类:

@Override
public Result<RechargeInfo> getRechargeInfo(String orderNo) {
    log.error("[账户服务]提供远程调用接口getRechargeInfo服务降级");
    return null;
}

1.1.3 保存本地交易记录

service-payment模块中增加保存本地交易业务处理

PaymentInfoService

package com.atguigu.tingshu.payment.service;

import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.baomidou.mybatisplus.extension.service.IService;

public interface PaymentInfoService extends IService<PaymentInfo> {

    /**
     * 保存本地交易记录
     *
     * @param paymentType 支付类型  支付类型:1301-订单 1302-充值
     * @param orderNo     订单编号
     * @param userId      用户ID
     * @return
     */
    PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId);

}

PaymentInfoServiceImpl实现类

package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;


    /**
     * 保存本地交易记录
     *
     * @param paymentType 支付类型  支付类型:1301-订单 1302-充值
     * @param orderNo     订单编号
     * @param userId      用户ID
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {
        //1.根据订单编号查询本地交易记录 如果存在则返回即可
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfoDB = this.getOne(queryWrapper);
        if (paymentInfoDB != null) {
            return paymentInfoDB;
        }
        //2.构建本地交易记录对象
        paymentInfoDB = new PaymentInfo();
        //2.1 基本属性赋值 用户ID、交易类型、订单编号、付款方式(微信)、交易状态:未支付(1401)
        paymentInfoDB.setUserId(userId);
        paymentInfoDB.setOrderNo(orderNo);
        paymentInfoDB.setPaymentType(paymentType);
        paymentInfoDB.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfoDB.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //2.2 封装交易内容及金额(远程调用订单服务或者账户服务获取)
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //远程调用订单服务获取订单金额及购买项目(VIP会员,专辑、声音)
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在!");
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
                throw new GuiguException(211, "订单状态错误!");
            }
            paymentInfoDB.setAmount(orderInfo.getOrderAmount());
            paymentInfoDB.setContent(orderInfo.getOrderTitle());
        } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //远程调用账户服务获取充值金额
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录不存在!");
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
                throw new GuiguException(211, "充值订单状态错误!");
            }
            paymentInfoDB.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfoDB.setContent("充值" + rechargeInfo.getRechargeAmount());
        }
        //3.保存本地交易记录且返回
        this.save(paymentInfoDB);
        return paymentInfoDB;
    }
}

1.2 对接微信支付

异步回调需要在微信端配置,并且只能配置一个接口地址,而现在这个接口地址有其他项目在使用。所以我们在前端模拟了一下回调功能,主动查询一下结果!

接收前端传递的支付类型以及订单编号

  1. 先在配置文件中添加支付相关信息配置:

    spring.application.name=service-payment
    spring.profiles.active=dev
    spring.main.allow-bean-definition-overriding=true
    spring.cloud.nacos.discovery.server-addr=192.168.200.130:8848
    spring.cloud.nacos.config.server-addr=192.168.200.130:8848
    spring.cloud.nacos.config.prefix=${spring.application.name}
    spring.cloud.nacos.config.file-extension=yaml
    wechat.v3pay.appid=wxcc651fcbab275e33
    wechat.v3pay.merchantId=1631833859
    wechat.v3pay.privateKeyPath=E:\\tingshu\\apiclient_key.pem
    wechat.v3pay.merchantSerialNumber=4AE80B52EBEAB2B96F68E02510A42801E952E889
    wechat.v3pay.apiV3key=84dba6dd51cdaf779e55bcabae564b53
    wechat.v3pay.notifyUrl=http://127.0.0.1:8500/api/payment/wxPay/notify
    
  2. apiclient_key.pem 商户API私钥路径 的私钥要放入指定位置,让程序读取!

  3. 注意:RSAAutoCertificateConfig 对象必须在配置文件中注入到spring 容器中,不要直接使用原生的,否则会报错!

    package com.atguigu.tingshu.payment.config;
    
    import com.wechat.pay.java.core.RSAAutoCertificateConfig;
    import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ConfigurationProperties(prefix="wechat.v3pay") //读取节点
    @Data
    public class WxPayV3Config {
    
    private String appid;
    /** 商户号 */
    public String merchantId;
    /** 商户API私钥路径 */
    public String privateKeyPath;
    /** 商户证书序列号 */
    public String merchantSerialNumber;
    /** 商户APIV3密钥 */
    public String apiV3key;
    /** 回调地址 */
    private String notifyUrl;
    
    @Bean
    public RSAAutoCertificateConfig rsaAutoCertificateConfig(){
        return new RSAAutoCertificateConfig.Builder()
                .merchantId(this.merchantId)
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3key)
                .build();
    }
    
    /**
     * 调用JSAPI-小程序、APP场景使用的服务类对象
     * @return
     */
    @Bean
    public JsapiServiceExtension service(){
        return new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig()).build();
    }
    }
    

1.2.1 支付控制器

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/102

package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.payment.service.WxPayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;


    /**
     * 调用微信支付获取 调起支付所需的所有参数,用于小程序端调起支付
     *
     * @param paymentType 订单、充值
     * @param orderNo
     * @return
     */
    @GuiGuLogin
    @Operation(summary = "调用微信支付获取 调起支付所需的所有参数,用于小程序端调起支付")
    @PostMapping("/wxPay/createJsapi/{paymentType}/{orderNo}")
    public Result<Map<String, String>> getWxPayParams(@PathVariable String paymentType, @PathVariable String orderNo) {
        Map<String, String> wxPayParams = wxPayService.getWxPayParams(paymentType, orderNo);
        return Result.ok(wxPayParams);
    }

}

1.2.2 支付接口

package com.atguigu.tingshu.payment.service;

import java.util.Map;

public interface WxPayService {

    /**
     * 调用微信支付获取 调起支付所需的所有参数,用于小程序端调起支付
     *
     * @param paymentType
     * @param orderNo
     * @return
     */
    Map<String, String> getWxPayParams(String paymentType, String orderNo);
}

1.2.3 支付实现类

微信支付:小程序调起支付需要返回的参数

支付文档入口:https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestPayment.html 对接方式:https://github.com/wechatpay-apiv3/wechatpay-java

package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    //调用微信支付获取小程序端所需参数用于拉起微信支付app

    @Autowired
    private JsapiServiceExtension jsapiServiceExtension;

    @Autowired
    private WxPayV3Config wxPayV3Config;

    /**
     * 调用微信支付获取 调起支付所需的所有参数,用于小程序端调起支付
     *
     * @param paymentType
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> getWxPayParams(String paymentType, String orderNo) {
        try {
            Long userId = AuthContextHolder.getUserId();
            //1.先保存本地交易记录对象
            PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo, userId);
            if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
                throw new GuiguException(211, "该交易已支付!");
            }
            //2.对接微信获取小程序端调起支付所需参数
            //2.1 预下单请求对象
            PrepayRequest prepayRequest = new PrepayRequest();
            Amount amount = new Amount();
            //微信支付金额单位:分
            amount.setTotal(1);
            prepayRequest.setAmount(amount);
            prepayRequest.setAppid(wxPayV3Config.getAppid());
            prepayRequest.setMchid(wxPayV3Config.getMerchantId());
            prepayRequest.setDescription(paymentInfo.getContent());
            prepayRequest.setNotifyUrl("https://notify_url");
            prepayRequest.setOutTradeNo(orderNo);
            //TODO 开发阶段指定付款人信息wxopenId 需要将OpenID改为自己的(在小程序开发者列表)
            Payer payer = new Payer();
            payer.setOpenid("odo3j4qp-wC3HVq9Z_D9C0cOr0Zs");
            prepayRequest.setPayer(payer);
            //2.2 调用获取微信支付所需参数
            PrepayWithRequestPaymentResponse response = jsapiServiceExtension.prepayWithRequestPayment(prepayRequest);
            if (response != null) {
                Map<String, String> map = new HashMap<>();
                map.put("timeStamp", response.getTimeStamp());
                map.put("package", response.getPackageVal());
                map.put("paySign", response.getPaySign());
                map.put("signType", response.getSignType());
                map.put("nonceStr", response.getNonceStr());
                return map;
            }
            return null;
        } catch (GuiguException e) {
            log.error("[支付服务]获取微信支付参数异常:{}", e);
            throw new RuntimeException(e);
        }
    }
}

1.3 查询支付状态(同步)

需求:当用户微信付款后,在小程序端需要通过查询微信端交易状态(轮询查询交易状态),如果用户已支付,给小程序端响应结果,展示支付成功页面(展示给用户)。

微信支付接口说明:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_2.shtml

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/103

WxPayApiController控制器:

/**
 * 小程序端轮询查询交易支付状态
 * @param orderNo
 * @return true:已支付(小程序展示支付成功页面) false:未支付(继续轮询)
 */
@Operation(summary = "小程序端轮询查询交易支付状态")
@GetMapping("/wxPay/queryPayStatus/{orderNo}")
public Result<Boolean> queryPayStatus(@PathVariable String orderNo){
    Boolean isPaid = wxPayService.queryPayStatus(orderNo);
    return Result.ok(isPaid);
}

WxPayService接口:

/**
 * 根据商户订单编号,支付微信支付支付状态
 *
 * @param orderNo
 * @return
 */
Boolean queryPayStatus(String orderNo);

WxPayServiceImpl实现类:

/**
 * 查询交易支付状态(根据商户订单号查询交易状态)
 *
 * @param orderNo
 * @return
 */
@Override
public Boolean queryPayStatus(String orderNo) {
    try {
        //1.构建根据商户订单号查询交易请求对象
        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
        request.setMchid(wxPayV3Config.getMerchantId());
        request.setOutTradeNo(orderNo);
        //2.调用wxPay业务对象查询订单交易对象得到支付状态
        Transaction transaction = jsapiServiceExtension.queryOrderByOutTradeNo(request);
        if (transaction != null) {
            //获取交易状态
            Transaction.TradeStateEnum tradeState = transaction.getTradeState();
            if (Transaction.TradeStateEnum.SUCCESS == tradeState) {
                return true;
            }
        }
    } catch (Exception e) {
        log.error("[支付服务]查询订单:{},支付交易状态异常:{}", orderNo, e);
        throw new RuntimeException(e);
    }
    return false;
}

同学代码:

/**
 * 查询交易支付状态(根据商户订单号查询交易状态)
 *
 * @param orderNo
 * @return
 */
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public Boolean queryPayStatus(String orderNo) {
    //TODO 约定默认客户端微信支付成功 默认返回true
    //更新本地交易状态及后续业务处理
    Boolean flag = false;
    try {
        Transaction transaction = new Transaction();
        transaction.setOutTradeNo(orderNo);
        //随机产生
        transaction.setTransactionId(IdUtil.getSnowflakeNextIdStr());
        TransactionAmount transactionAmount = new TransactionAmount();
        transactionAmount.setTotal(1);
        transactionAmount.setPayerTotal(1);
        transaction.setAmount(transactionAmount);
        paymentInfoService.updatePaymentInfoSuccess(transaction);
        flag = true;
    } catch (Exception e) {
        flag = false;
        throw new RuntimeException(e);
    } finally {
        return flag;
    }
}

1.4 支付异步回调

微信异步回调说明:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_5.shtml

1.4.1 内网穿透工具

内网穿透工具:https://natapp.cn/

  1. 注册账户,实名认证

  2. 购买免费隧道,设置域名映射本地IP及端口

image-20231204105254982

  1. 修改netapp程序配置文件

    image-20231204105336040

    #将本文件放置于natapp同级目录 程序将读取 [default] 段
    #在命令行参数模式如 natapp -authtoken=xxx 等相同参数将会覆盖掉此配置
    #命令行参数 -config= 可以指定任意config.ini文件
    [default]
    authtoken=改为自己申请隧道对应的authtoken      #对应一条隧道的authtoken
    
  2. 启动netapp程序

    image-20231204105456254

  3. 修改Nacos中支付系统配置文件中异步回调地址改为最新域名

    image-20231204105544046

  4. 启动支付系统,拉取最新配置

  5. 创建购买订单或充值记录,产生微信交易

1.4.2 支付服务集成Seata

  1. tingshu_payment数据库中新增undo_log日志表

    CREATE TABLE `undo_log` (
     `id` bigint NOT NULL AUTO_INCREMENT,
     `branch_id` bigint NOT NULL,
     `xid` varchar(100) NOT NULL,
     `context` varchar(128) NOT NULL,
     `rollback_info` longblob NOT NULL,
     `log_status` int NOT NULL,
     `log_created` datetime NOT NULL,
     `log_modified` datetime NOT NULL,
     `ext` varchar(100) DEFAULT NULL,
     PRIMARY KEY (`id`),
     UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3;
    
  2. service-payment模块pom.xml中增加Seata启动依赖

    <!--seata-->
    <dependency>
       <groupId>com.alibaba.cloud</groupId>
       <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
       <!-- 默认seata客户端版本比较低,排除后重新引入指定版本-->
       <exclusions>
           <exclusion>
               <groupId>io.seata</groupId>
               <artifactId>seata-spring-boot-starter</artifactId>
           </exclusion>
       </exclusions>
    </dependency>
    <dependency>
       <groupId>io.seata</groupId>
       <artifactId>seata-spring-boot-starter</artifactId>
    </dependency>
    
  3. 订单微服务service-order模块新增Seata配置

    seata:
     enabled: true
     tx-service-group: ${spring.application.name}-group # 事务组名称
     service:
       vgroup-mapping:
         #指定事务分组至集群映射关系,集群名default需要与seata-server注册到Nacos的cluster保持一致
         service-payment-group: default
     registry:
       type: nacos # 使用nacos作为注册中心
       nacos:
         server-addr: 192.168.200.6:8848 # nacos服务地址
         group: DEFAULT_GROUP # 默认服务分组
         namespace: "" # 默认命名空间
         cluster: default # 默认TC集群名称
       
    

1.4.3 支付服务-处理异步回调

微信异步回调说明:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_5.shtml

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/104

WxPayApiController控制器:

/**
 * 处理微信支付成功后异步回调
 * @param request
 * @return
 */
@Operation(summary = "处理微信支付成功后异步回调")
@PostMapping("/wxpay/notify")
public ResponseEntity notify(HttpServletRequest request){
    Map<String, String> map = wxPayService.notifySuccess(request);
    return ResponseEntity.ok(map);
}

WxPayService接口

/**
 * 处理微信异步回调
 *
 * @param request
 * @return
 */
Map<String, String> notifySuccess(HttpServletRequest request);

WxPayServiceImpl实现类

@Autowired
private RSAAutoCertificateConfig rsaAutoCertificateConfig;


/**
 * 处理微信异步回调
 *
 * @param request
 * @return
 */
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public Map<String, String> notifySuccess(HttpServletRequest request) {
    try {
        //1.验证签名-避免出现虚假通知

        //1.1.尝试获取请求头中信息(进需要请求头中)
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");  //签名
        String nonce = request.getHeader("Wechatpay-Nonce");  //签名中的随机数
        String timestamp = request.getHeader("Wechatpay-Timestamp"); //时间戳
        String signature = request.getHeader("Wechatpay-Signature"); //签名类型
        String requestBody1 = PayUtil.readData(request);
        //基于获取头信息-构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(requestBody1)
                .build();
        //2.NotificationParser用于真正验签
        NotificationParser parser = new NotificationParser(rsaAutoCertificateConfig);

        //3.支付通知回调为例,验签、解密并转换成 Transaction
        Transaction transaction = parser.parse(requestParam, Transaction.class);
        //4.判断交易结果 判断支付结果及支付金额
        if (transaction != null) {
            if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
                //TODO 上线后改为本地交易记录金额 测试:使用1(产生微信支付交易金额:1)
                if (transaction.getAmount().getTotal().intValue() == 1) {
                    //5.触发更新本地交易记录及后续业务
                    paymentInfoService.updatePaymentInfoSuccess(transaction.getOutTradeNo());
                    //6.响应正确应答
                    Map<String, String> map = new HashMap<>();
                    map.put("code", "SUCCESS");
                    map.put("message", "SUCCESS");
                    return map;
                }
            }
        }
    } catch (Exception e) {
        //捕获到异常全局事务回滚,微信再次按照一定频率通知商户端
        log.error("[支付系统]异步回调异常:{}", e);
        throw new RuntimeException(e);
    }
    return null;
}

1.4.3.1 更新本地交易记录

PaymentInfoService

/**
 * 更新本地交易记录状态:改为支付成功
 * @param orderNo
 */
void updatePaymentInfo(String outTradeNo, Transaction transaction);

PaymentInfoServiceImpl


@Autowired
private UserFeignClient userFeignClient;


/**
 * 更新本地交易记录、新订单状态、充值、购买记录
 *
 * @param orderNo     商户的订单编号
 * @param transaction
 */
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePaymentInfo(String orderNo, Transaction transaction) {
    //1.根据订单编号查询本地交易记录,如果本地交易记录已支付(说明更新过了,不处理)
    LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
    PaymentInfo paymentInfo = this.getOne(queryWrapper);
    if (paymentInfo != null && SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
        return;
    }
    paymentInfo.setCallbackTime(new Date());
    paymentInfo.setCallbackContent(transaction.toString());
    paymentInfo.setOutTradeNo(transaction.getTransactionId());
    paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
    this.updateById(paymentInfo);

    //2.更新订单支付状态或者充值记录交易状态
    if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
        //2.1 远程调用订单服务更新订单状态
        Result orderPaySuccessResult = orderFeignClient.orderPaySuccess(orderNo);
        if(200!=orderPaySuccessResult.getCode()){
            throw new GuiguException(211, "更新订单失败");
        }
    } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
        //2.2 充值记录-远程调用账户服务更新订单状态
        Result rechargeResult = accountFeignClient.rechargeSuccess(orderNo);
        if(200 != rechargeResult.getCode()) {
            throw new GuiguException(211, "充值失败");
        }
    }
}

1.4.3.2 订单服务-更新订单状态

YAPI接口地址:

service-order模块OrderInfoApiController处理订单支付成功

/**
 * 订单支付成功
 * @param orderNo
 * @return
 */
@Operation(summary = "支付成功修改订单状态")
@GetMapping("/orderInfo/orderPaySuccess/{orderNo}}")
public Result orderPaySuccess(@PathVariable String orderNo){
    orderInfoService.orderPaySuccess(orderNo);
    return Result.ok();
}

OrderInfoService

/**
 * 订单支付成功
 * @param orderNo
 * @return
 */
void orderPaySuccess(String orderNo);

OrderInfoServiceImpl

/**
 * 更新订单状态:已支付、新增用户购买记录
 *
 * @param orderNo
 */
@Override
@Transactional(rollbackFor = Exception.class)
public void orderPaySuccess(String orderNo) {
    //1.根据订单编号查询订单信息,更新订单状态:已支付(幂等性)
    OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
    orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
    orderInfoMapper.updateById(orderInfo);

    //2.远程调用“用户服务”新增用户购买记录 UserPaidRecordVo
    UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
    userPaidRecordVo.setOrderNo(orderNo);
    userPaidRecordVo.setUserId(orderInfo.getUserId());
    userPaidRecordVo.setItemType(orderInfo.getItemType());
    //获取订单明细 封装用户购买项ID集合
    List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderInfo.getId()));
    if (CollectionUtil.isNotEmpty(orderDetailList)) {
        List<Long> itemIdList = orderDetailList.stream().map(OrderDetail::getItemId).collect(Collectors.toList());
        userPaidRecordVo.setItemIdList(itemIdList);
        Result result = userFeignClient.savePaidRecord(userPaidRecordVo);
        if(200!=result.getCode()){
            throw new GuiguException(211, "新增购买记录异常!");
        }
    }
}

service-order-client模块OrderFeignClient中新增Feign远程调用方法

/**
 * 订单支付成功
 * @param orderNo
 * @return
 */
@GetMapping("/orderInfo/orderPaySuccess/{orderNo}")
public Result orderPaySuccess(@PathVariable String orderNo);

OrderDegradeFeignClient服务降级类

@Override
public Result orderPaySuccess(String orderNo) {
    return null;
}

1.4.3.3 账户服务-更新账户信息

见第2小节。

2、充值业务

点击我的---->我的钱包

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/105

service-account 模块中添加控制器

前端传递充值金额与充值方式,所以我们需要封装一个实体类接受前端传递的数据.

实体类RechargeInfoVo

@Data
@Schema(description = "充值对象")
public class RechargeInfoVo {

   @Schema(description = "充值金额")
   private BigDecimal amount;

   @Schema(description = "支付方式:1101-微信 1102-支付宝")
   private String payWay;

}

service-account模块中控制器:RechargeInfoApiController

/**
 * 用户余额充值(保存充值记录)
 *
 * @param rechargeInfoVo
 * @return
 */
@GuiGuLogin
@Operation(summary = "用户余额充值-保存充值记录")
@PostMapping("/rechargeInfo/submitRecharge")
public Result<Map<String, String>> submitRecharge(@RequestBody RechargeInfoVo rechargeInfoVo) {
    Map<String, String> map = rechargeInfoService.submitRecharge(rechargeInfoVo);
    return Result.ok(map);
}

RechargeInfoService接口:

/**
 * 用户余额充值(保存充值记录)
 *
 * @param rechargeInfoVo
 * @return
 */
Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo);

实现类:

/**
 * 用户余额充值(保存充值记录)
 *
 * @param rechargeInfoVo
 * @return
 */
@Override
public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
    //1.为本次充值记录生成订单编号-保存充值记录(未支付)
    RechargeInfo rechargeInfo = new RechargeInfo();
    rechargeInfo.setUserId(AuthContextHolder.getUserId());
    rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
    rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
    rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
    String orderNo = "CZ" + DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
    rechargeInfo.setOrderNo(orderNo);
    rechargeInfoMapper.insert(rechargeInfo);

    //3.TODO 利用延迟队列,延迟关闭充值记录
    Map<String, String> map = new HashMap<>();
    map.put("orderNo", orderNo);
    return map;
}

2.1 充值成功业务处理

在支付成功之后,会在支付服务中提供异步回调处理支付成功业务。

  • service-account 模块添加处理充值成功的充值订单业务Restful接口即可

2.1.1 修改充值状态

YAPI接口文档地址:http://192.168.200.6:3000/project/11/interface/api/154

在这个RechargeInfoApiController类中添加数据

/**
 * 充值支付成功,修改充值状态及变更余额
 * @param orderNo
 * @return
 */
@Operation(summary = "充值支付成功,修改充值状态及变更余额")
@PostMapping("/rechargeInfo/rechargePaySuccess/{orderNo}")
public Result rechargePaySuccess(@PathVariable String orderNo){
	rechargeInfoService.rechargePaySuccess(orderNo);
	return Result.ok();
}

RechargeInfoService接口

/**
 * 充值支付成功,修改充值状态及变更余额
 * @param orderNo
 * @return
 */
void rechargePaySuccess(String orderNo);

RechargeInfoServiceImpl实现

@Autowired
private UserAccountService userAccountService;

/**
 * 充值支付成功,修改充值状态及变更余额
 *
 * @param orderNo
 * @return
 */
@Override
@Transactional(rollbackFor = Exception.class)
public void rechargePaySuccess(String orderNo) {
    //1.根据订单编号查询充值记录状态 如果已支付 则直接返回
    LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
    RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(queryWrapper);
    if (rechargeInfo != null && SystemConstant.ORDER_STATUS_PAID.equals(rechargeInfo.getRechargeStatus())) {
        return;
    }
    //2.修改充值记录状态:已支付
    rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
    rechargeInfoMapper.updateById(rechargeInfo);

    //3.更新账户余额:总金额、可用余额、收入金额
    userAccountService.add(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());

    //4.新增账户变动日志
    userAccountService.saveUserAccountDetail(rechargeInfo.getUserId(), "充值", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), rechargeInfo.getOrderNo());
}

2.1.2 账户充值

UserAccountService

新增 user_account 与 user_account_detail 表数据

/**
 * 新增余额
 * @param userId
 * @param rechargeAmount
 */
void add(Long userId, BigDecimal rechargeAmount);
/**
 * 新增余额
 * @param userId
 * @param rechargeAmount
 */
@Override
public void add(Long userId, BigDecimal rechargeAmount) {
    int count = userAccountMapper.add(userId, rechargeAmount);
    if(count==0){
        throw new GuiguException(212, "账户充值失败");
    }
}

UserAccountMapper

/**
 * 账户充值
 * @param userId
 * @param rechargeAmount
 * @return
 */
int add(@Param("userId") Long userId, @Param("amount") BigDecimal rechargeAmount);

UserAccountMapper.xml

<!--账户充值-->
<update id="add">
	UPDATE user_account
	SET total_amount = total_amount + #{amount},
		available_amount = available_amount + #{amount},
		total_income_amount = total_income_amount + #{amount}
	WHERE
		user_id = #{userId}
</update>

2.1.3 提供Feign接口

service-account-client模块中提供远程调用Feign接口

AccountFeignClient

/**
 * 充值支付成功,修改充值状态及变更余额
 * @param orderNo
 * @return
 */
@PostMapping("/rechargeInfo/rechargePaySuccess/{orderNo}")
public Result rechargePaySuccess(@PathVariable String orderNo);

AccountDegradeFeignClient服务降级类

@Override
public Result rechargePaySuccess(String orderNo) {
    log.error("[账户服务]提供远程调用接口rechargePaySuccess服务降级");
    return null;
}

2.2 充值记录

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/106

用户充值记录回显信息保存到实体类:

package com.atguigu.tingshu.model.account;

import com.atguigu.tingshu.model.base.BaseEntity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.math.BigDecimal;

@Data
@Schema(description = "UserAccountDetail")
@TableName("user_account_detail")
public class UserAccountDetail extends BaseEntity {

   private static final long serialVersionUID = 1L;

   @Schema(description = "用户id")
   @TableField("user_id")
   private Long userId;

   @Schema(description = "交易标题")
   @TableField("title")
   private String title;

   @Schema(description = "交易类型:1201-充值 1202-锁定 1203-解锁 1204-消费")
   @TableField("trade_type")
   private String tradeType;

   @Schema(description = "金额")
   @TableField("amount")
   private BigDecimal amount;

   @Schema(description = "订单编号")
   @TableField("order_no")
   private String orderNo;

}

service-account 微服务 UserAccountApiController 控制器添加

/**
 * 分页获取用户充值记录"
 *
 * @param page
 * @param limit
 * @return
 */
@GuiGuLogin
@Operation(summary = "分页获取用户充值记录")
@GetMapping("/userAccount/findUserRechargePage/{page}/{limit}")
public Result<Page<UserAccountDetail>> getUserRechargePage(@PathVariable int page, @PathVariable int limit) {
    Long userId = AuthContextHolder.getUserId();
    Page<UserAccountDetail> pageInfo = new Page<>(page, limit);
    userAccountService.getUserRechargePage(userId, pageInfo);
    return Result.ok(pageInfo);
}

接口:

/**
 * 分页获取用户充值记录"
 *
 * @return
 */
void getUserRechargePage(Long userId, Page<UserAccountDetail> pageInfo);

实现类:

/**
 * 分页获取用户充值记录"
 *
 * @return
 */
@Override
public void getUserRechargePage(Long userId, Page<UserAccountDetail> pageInfo) {
    userAccountDetailMapper.getUserRechargePage(pageInfo, userId, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT);
}
package com.atguigu.tingshu.account.mapper;

import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserAccountDetailMapper extends BaseMapper<UserAccountDetail> {

    Page<UserAccountDetail> getUserRechargePage(Page<UserAccountDetail> pageInfo, @Param("userId") Long userId, @Param("tradeType") String tradeType);
}

xml 配置文件

<select id="getUserRechargePage" resultType="com.atguigu.tingshu.model.account.UserAccountDetail">
	SELECT * from user_account_detail where user_id = #{userId} and trade_type = #{tradeType} and is_deleted = 0 order by create_time desc
</select>

2.3 消费记录

消费记录

YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/107

在service-account 微服务中添加

/**
 * 分页获取用户消费记录
 *
 * @param page
 * @param limit
 * @return
 */
@GuiGuLogin
@Operation(summary = "分页获取用户消费记录")
@GetMapping("/userAccount/findUserConsumePage/{page}/{limit}")
public Result<Page<UserAccountDetail>> getUserUserConsumePage(@PathVariable int page, @PathVariable int limit) {
    Long userId = AuthContextHolder.getUserId();
    Page<UserAccountDetail> pageInfo = new Page<>(page, limit);
    userAccountService.getUserUserConsumePage(userId, pageInfo);
    return Result.ok(pageInfo);
}

接口:

/**
 * 分页获取用户消费记录"
 *
 * @return
 */
void getUserUserConsumePage(Long userId, Page<UserAccountDetail> pageInfo);

实现类:

/**
 * 分页获取用户消费记录
 *
 * @return
 */
@Override
public void getUserUserConsumePage(Long userId, Page<UserAccountDetail> pageInfo) {
    userAccountDetailMapper.getUserRechargePage(pageInfo, userId, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS);
}

测试:充值一百元之后,查看余额与

充值记录: