一:用户下单需求分析和设计:
用户下单业务说明: 在电商系统中,用户是通过下单的方式通知商家,用户已经购买了商品,需要商家进行备货和发货。 用户下单后会产生订单相关数据,订单数据需要能够体现如下信息:
接口设计(分析):
请求方式:POST
请求路径:/user/order/submit
- 参数:
- 地址簿id
- 配送状态(立即送出、选择送出时间)
- 打包费
- 总金额
- 备注
- 餐具数量
返回数据:
- 下单时间
- 订单总金额
- 订单号
- 订单id
做这种接口设计的时候,我们需要对照页面的原型进行分析。
围绕两个方面:
- 后端需要接收那些数据?
- 前端需要展示后端的那些数据
数据库设计:
- 订单表 orders
- 订单明细表 order_detail
有两张表可以分析得出:一张订单表下可以有很多张订单明细表
所以这是一组一对多的关系。
二:用户下单具体代码实现:
Controller层:
@RestController("userOrderController")
@RequestMapping("/user/order")
@Api(tags = "用户支付相关接口")
@Slf4j
public class OrderController {
@Autowired
private OrderService orderService;
/**
* 用户下单接口
* @param ordersSubmitDTO
* @return
*/
@PostMapping("/submit")
@ApiOperation("用户下单接口")
public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO){
log.info("用户下单接口:{}",ordersSubmitDTO);
OrderSubmitVO orderSubmitVO = orderService.submit(ordersSubmitDTO);
return Result.success(orderSubmitVO);
}
}
Service层:
package com.sky.service.impl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderDetailMapper orderDetailMapper;
@Autowired
private AddressBookMapper addressBookMapper;
@Autowired
private ShoppingCartMapper shoppingCartMapper;
/**
* 用户下单接口
* @param ordersSubmitDTO
* @return
*/
@Override
@Transactional
public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
//处理各种业务异常(地址簿为空,购物车数据为空)
//判断地址簿是否为空
AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
if(addressBook==null){
throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
}
//判断购物车的数据是否为空
final Long userId = BaseContext.getCurrentId();
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.setUserId(userId);
List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
if(list.isEmpty()){
throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
}
//向订单插入1条数据
Orders orders = new Orders();
BeanUtils.copyProperties(ordersSubmitDTO,orders);
orders.setOrderTime(LocalDateTime.now());
orders.setPayStatus(Orders.UN_PAID);
orders.setStatus(Orders.PENDING_PAYMENT);
orders.setNumber(String.valueOf(System.currentTimeMillis()));
orders.setPhone(addressBook.getPhone());
orders.setConsignee(addressBook.getConsignee());
orders.setUserId(userId);
orderMapper.insert(orders);//需要返回主键值
//向订单明细表插入n条数据
List<OrderDetail> orderDetailList = new ArrayList<>();
for (ShoppingCart cart : list) {
OrderDetail orderDetail = new OrderDetail();
BeanUtils.copyProperties(cart,orderDetail);
orderDetail.setOrderId(orders.getId());
orderDetailList.add(orderDetail);
}
orderDetailMapper.insertBatch(orderDetailList);
//清空用户购物车
shoppingCartMapper.deleteAll(userId);
//封装VO返回结果
final OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
.id(orders.getId())
.orderTime(orders.getOrderTime())
.orderNumber(orders.getNumber())
.orderAmount(orders.getAmount())
.build();
return orderSubmitVO;
}
}
Service层的处理逻辑主要分为五步:
- 处理异常信息(这一步前端也会处理)
- 向订单表中插入一条数据
- 向订单细节表插入多条数据
- 清空购物车
- 封装VO数据返回
Mapper层及其注释:
@Mapper
public interface OrderMapper {
void insert(Orders orders);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sky.mapper.OrderMapper">
<insert id="insert" parameterType="Orders" useGeneratedKeys="true" keyProperty="id">
insert into sky_take_out.orders
(number, status, user_id, address_book_id, order_time, checkout_time, pay_method, pay_status, amount, remark,
phone, address, consignee, estimated_delivery_time, delivery_status, pack_amount, tableware_number,
tableware_status)
values (#{number}, #{status}, #{userId}, #{addressBookId}, #{orderTime}, #{checkoutTime}, #{payMethod},
#{payStatus}, #{amount}, #{remark}, #{phone}, #{address}, #{consignee},
#{estimatedDeliveryTime}, #{deliveryStatus}, #{packAmount}, #{tablewareNumber}, #{tablewareStatus})
</insert>
</mapper>
@Mapper
public interface OrderDetailMapper {
void insertBatch(List<OrderDetail> orderDetailList);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sky.mapper.OrderDetailMapper">
<insert id="insertBatch" parameterType="list">
insert into sky_take_out.order_detail
(name, order_id, dish_id, setmeal_id, dish_flavor, number, amount, image)
values
<foreach collection="orderDetails" item="od" separator=",">
(#{od.name},#{od.orderId},#{od.dishId},#{od.setmealId},#{od.dishFlavor},
#{od.number},#{od.amount},#{od.image})
</foreach>
</insert>
</mapper>
三:订单支付:
微信支付时序图:
我们需要重点关注的就是5,10,13这几步,这也是在我们后端需要处理的。
我们需要重点看下面两步。
- 5:调用微信下单接口:如何保证数据的安全?
微信支付涉及到数据的传输,为了保证数据的安全,所以需要对数据进行加密和解密,需要用到证书。
需要下面2个文件(要求小程序是企业认证,没有的话也没关系,对后面没太大影响):获取微信微信支付平台证书文件:apiclient_key.pem。商户私钥文件:wechatpay_166D96F876F45C7D07CE98952A96EC980368ACFC.pem
- 13:推送支付结果:微信后台如何知道我们的ip地址?或者说如何调用我们的后台系统?
5:调用微信下单接口:
13:推送支付结果:
要想微信后台给我们的系统发送http请求,因为我们的电脑的ip地址大多数都在局域网,这样是接收不到的。
所以就要用到下面的一个工具:cpolar:进行内网穿透
cpolar概念和使用场景:
cpolar是一种安全的内网穿透云服务,它将内网下的本地服务器通过安全隧道暴露至公网。使得公网用户可以正常访问内网服务,是一款内网穿透软件。只需一行命令,就可以将内网站点发布至公网,方便给客户演示。高效调试微信公众号、小程序、对接支付宝网关等云端服务,提高您的编程效率。
cpolar的使用步骤:
在Coplar这个目录下打开cmd 输入如下命令
再输入如下命令
通过以上操作,我们就可以通过cpolar所映射的域名:http://449e4a26.r22.cpolar.top/,访问我们内网服务器中8080端口启动的服务。
简单测试:
启动服务之后访问8080端口的接口文档
整个微信支付的处理逻辑:
- 点击确认支付之后调用OrderController的payment方法,并且获取订单号
- 具体的处理逻辑在OrderServiceImpl,
- 获取了用户的id
- 调用微信支付接口,生成预支付交易单(不过这一步个体户做不了,所以我们的做法是直接对订单的状态进行改变用了一个updateStatus方法修改订单的状态)
- 将这个预支付交易单进行处理之后,就返回给了前端小程序,然后前端就会出现一个类似于支付的界面(做不了这个支付功能,我直接重定向跳转到支付成功的界面)
- 支付成功之后,微信后台就给我们的后端服务器发送了一个这个回调(告诉我们支付成功了顺便说一下,微信后台如何知道,就是上面的cpolar的作用,将我们的服务器暴露在公网,这样微信后台才知道我们后端的ip
- 然后我们后端对这个微信后台给我们返回的这个信息进行解密,并且修改这个订单的状态。
虽然做不了支付效果,也放以下这个步骤把。
订单支付的配置:
wechat:
appid: ${sky.wechat.appid}
secret: ${sky.wechat.secret}
mchid: ${sky.wechat.mchid}
mchSerialNo: ${sky.wechat.mchid}
privateKeyFilePath: ${sky.wechat.privateKeyFilePath}
apiV3Key: ${sky.wechat.apiV3Key}
weChatPayCertFilePath: ${sky.wechat.weChatPayCertFilePath}
notifyUrl: ${sky.wechat.notifyUrl}
refundNotifyUrl: ${sky.wechat.refundNotifyUrl}
wechat:
appid: wx12795712460de79a
secret: d0cbbfa6cc3af7fcc8875752622a3b71
mchid: 1561414331
mchSerialNo: 4B3B3DC35414AD50B1B755BAF8DE9CC7CF407606
privateKeyFilePath: C:\software\apiclient_key.pem
apiV3Key: CZBK51236435wxpay435434323FFDuv3
weChatPayCertFilePath: C:\software\wechatpay_166D96F876F45C7D07CE98952A96EC980368ACFC.pem
notifyUrl: https://5dd70cf8.r24.cpolar.top/notify/paySuccess
refundNotifyUrl: https://5dd70cf8.r24.cpolar.top/notify/refundSuccess
要注意notifyUrl和refundNotifyUrl,这两个url的前半部分都是cpolar临时生成的公网ip,因为是临时域名,所以每次生成的都会变化,以后要注意修改)
OrderControll层:
/**
* 订单支付
*
* @param ordersPaymentDTO
* @return
*/
@PutMapping("/payment")
@ApiOperation("订单支付")
public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) throws Exception {
log.info("订单支付:{}", ordersPaymentDTO);
OrderPaymentVO orderPaymentVO = orderService.payment(ordersPaymentDTO);
log.info("生成预支付交易单:{}", orderPaymentVO);
return Result.success(orderPaymentVO);
}
OrderService层:
/**
* 订单支付
*
* @param ordersPaymentDTO
* @return
*/
public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
// 当前登录用户id
Long userId = BaseContext.getCurrentId();
User user = userMapper.getById(userId);
/*
//调用微信支付接口,生成预支付交易单
JSONObject jsonObject = weChatPayUtil.pay(
ordersPaymentDTO.getOrderNumber(), //商户订单号
new BigDecimal(0.01), //支付金额,单位 元
"苍穹外卖订单", //商品描述
user.getOpenid() //微信用户的openid
);
if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
throw new OrderBusinessException("该订单已支付");
}
*/
JSONObject jsonObject = new JSONObject();
jsonObject.put("code","ORDERPAID");
OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
vo.setPackageStr(jsonObject.getString("package"));
Integer OrderStatus = Orders.TO_BE_CONFIRMED;
Integer OrderPaidStatus = Orders.PAID;
LocalDateTime check_out_time = LocalDateTime.now();
orderMapper.updateStatus(OrderStatus,OrderPaidStatus,check_out_time,this.orders.getId());
return vo;
}
/**
* 支付成功,修改订单状态
*
* @param outTradeNo
*/
public void paySuccess(String outTradeNo) {
// 根据订单号查询订单
Orders ordersDB = orderMapper.getByNumber(outTradeNo);
// 根据订单id更新订单的状态、支付方式、支付状态、结账时间
Orders orders = Orders.builder()
.id(ordersDB.getId())
.status(Orders.TO_BE_CONFIRMED)
.payStatus(Orders.PAID)
.checkoutTime(LocalDateTime.now())
.build();
orderMapper.update(orders);
}
这里主要实现了两个接口:
- 调用微信支付接口
- 支付成功,修改订单状态接口
这里提一下,我们直接在调用微信支付接口直接重定向了地址,并且也修改了订单状态,相当于把两个接口合成一个了。
Mapper层及注解:
/**
* 修改订单信息
* @param orders
*/
void update(Orders orders);
/**
* 更新支付状态
* @param orderStatus
* @param orderPaidStatus
* @param check_out_time
* @param id
*/
@Update("update sky_take_out.orders set status = #{orderStatus},pay_status = #{orderPaidStatus} ,checkout_time = #{check_out_time} where id = #{id}")
void updateStatus(Integer orderStatus, Integer orderPaidStatus, LocalDateTime check_out_time, Long id);
<update id="update" parameterType="com.sky.entity.Orders">
update sky_take_out.orders
<set>
<if test="cancelReason != null and cancelReason!='' ">
cancel_reason=#{cancelReason},
</if>
<if test="rejectionReason != null and rejectionReason!='' ">
rejection_reason=#{rejectionReason},
</if>
<if test="cancelTime != null">
cancel_time=#{cancelTime},
</if>
<if test="payStatus != null">
pay_status=#{payStatus},
</if>
<if test="payMethod != null">
pay_method=#{payMethod},
</if>
<if test="checkoutTime != null">
checkout_time=#{checkoutTime},
</if>
<if test="status != null">
status = #{status},
</if>
<if test="deliveryTime != null">
delivery_time = #{deliveryTime}
</if>
</set>
where id = #{id}
</update>
PayNotifyControll层:
package com.sky.controller.notify;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.WeChatProperties;
import com.sky.service.OrderService;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
/**
* 支付回调相关接口
*/
@RestController("notifyPayNotifyController")
@RequestMapping("/notify")
@Slf4j
public class PayNotifyController {
@Autowired
private OrderService orderService;
@Autowired
private WeChatProperties weChatProperties;
/**
* 支付成功回调
*
* @param request
*/
@RequestMapping("/paySuccess")
public void paySuccessNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
//读取数据
String body = readData(request);
log.info("支付成功回调:{}", body);
//数据解密
String plainText = decryptData(body);
log.info("解密后的文本:{}", plainText);
JSONObject jsonObject = JSON.parseObject(plainText);
String outTradeNo = jsonObject.getString("out_trade_no");//商户平台订单号
String transactionId = jsonObject.getString("transaction_id");//微信支付交易号
log.info("商户平台订单号:{}", outTradeNo);
log.info("微信支付交易号:{}", transactionId);
//业务处理,修改订单状态、来单提醒
orderService.paySuccess(outTradeNo);
//给微信响应
responseToWeixin(response);
}
/**
* 读取数据
*
* @param request
* @return
* @throws Exception
*/
private String readData(HttpServletRequest request) throws Exception {
BufferedReader reader = request.getReader();
StringBuilder result = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (result.length() > 0) {
result.append("\n");
}
result.append(line);
}
return result.toString();
}
/**
* 数据解密
*
* @param body
* @return
* @throws Exception
*/
private String decryptData(String body) throws Exception {
JSONObject resultObject = JSON.parseObject(body);
JSONObject resource = resultObject.getJSONObject("resource");
String ciphertext = resource.getString("ciphertext");
String nonce = resource.getString("nonce");
String associatedData = resource.getString("associated_data");
AesUtil aesUtil = new AesUtil(weChatProperties.getApiV3Key().getBytes(StandardCharsets.UTF_8));
//密文解密
String plainText = aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8),
nonce.getBytes(StandardCharsets.UTF_8),
ciphertext);
return plainText;
}
/**
* 给微信响应
* @param response
*/
private void responseToWeixin(HttpServletResponse response) throws Exception{
response.setStatus(200);
HashMap<Object, Object> map = new HashMap<>();
map.put("code", "SUCCESS");
map.put("message", "SUCCESS");
response.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes(StandardCharsets.UTF_8));
response.flushBuffer();
}
}
这一层其实用来通知前端,不过经过修改,这一步就跳过了。