目录
实现思路
1.购物车页面实现结算功能,主要是拿到传入后台的gids 2.跳转订单页后台,主要是拿到订单页展示数据 3.订单页前台数据展示
购物车页面实现结算功能
注:使用jquery动态实现结算功能,必须勾选购物车中的商品进行结算,没有勾选无法完成结算功能!!!
cart.js进行整改:关于结算按钮的绑定事件
- //计算总共几件商品
- function zg(){
- let gids="";
- var zsl = 0;
- var index = $(".th input[type='checkbox']:checked").parents(".th").find(".num span");
- var len =index.length;
- if(len==0){
- $("#sl").text(0);
- }else{
- let gidarr=new Array();
- index.each(function(){
- zsl+=parseInt($(this).text());
- $("#sl").text(zsl);
- //TODO 获取当前行的索引
- let idx = $(this).parents(".th").index()-1;
- console.log(idx);
- gidarr.push($(".th").eq(index).find('div:eq(0) input[type=hidden]').val());
- });
- gids=gidarr.join(",");
- }
- if($("#sl").text()>0){
- $(".count").css("background","#c10000");
- $(".count").bind("click",function () {
- // 拿到gids
- location.href='/order/toOrder?gids='+gids
- });
- }else{
- $(".count").css("background","#8e8e8e");
- $(".count").unbind("click");
- }
- }
测试结果,当点击结算,会跳转访问地址http://localhost:8080/order/toOrder?gids=2,22;
说明gids的值是已经拿到了;
然后再次去生成订单、订单项的代码:
记得在Order类修改时间的类型:
1.从session中获取购物车对象
2.筛选出要结算的订单项列表集合
OrderController .java:
- package com.ycx.spbootpro.controller;
-
-
- import com.ycx.spbootpro.model.Goods;
- import com.ycx.spbootpro.model.User;
- import com.ycx.spbootpro.model.vo.ShopCar;
- import com.ycx.spbootpro.model.vo.ShopCarItem;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
-
- /**
- *
- * 订单信息表 前端控制器
- *
- *
- * @author yangzong
- * @since 2022-11-08
- */
- @Controller
- @RequestMapping("/order")
- public class OrderController {
-
- @RequestMapping("/toOrder")
- public ModelAndView toOrder(User user,
- String gids,
- HttpServletRequest request){
- ModelAndView mv=new ModelAndView();
- // 拿到购物车中的所有商品
- ShopCar shopCar = getShopCar(user, request);
- // 通过gids从购物车中筛选出指定的商品
- List<ShopCarItem> list=getGoods(shopCar,gids);
- mv.addObject("goods",list);
- mv.setViewName("order.html");
- return mv;
- }
-
- //通过gids从购物车中筛选出指定的商品
- private List<ShopCarItem> getGoods(ShopCar shopCar, String gids) {
- List<String> gidList = Arrays.asList(gids.split(","));
- List<ShopCarItem> items=shopCar.getItems();//购物车里的商品
- List<ShopCarItem> itemsNew=new ArrayList<>();//购物车中要结算的商品
- for (ShopCarItem item:items){
- if(gidList.contains(item.getGid()+"")){
- itemsNew.add(item);
- }
- }
- return itemsNew;
- }
-
- // 从session中获取购物车对象
- private ShopCar getShopCar(User user,
- HttpServletRequest request) {
- HttpSession session = request.getSession();
- ShopCar shopCar = (ShopCar) session.getAttribute(user.getId() + "_shopCar");
- if (shopCar == null) {
- shopCar = new ShopCar();
- session.setAttribute(user.getId() + "_shopCar", shopCar);
- }
- return shopCar;
- }
- }
3.订单页前台展示
order.html:
- html>
- <html>
- <head lang="en">
- <#include "common/head.html">
- <link rel="stylesheet" type="text/css" href="css/public.css"/>
- <link rel="stylesheet" type="text/css" href="css/proList.css" />
- <link rel="stylesheet" type="text/css" href="css/mygxin.css" />
- head>
- <body>
-
- <div class="head ding">
- <div class="wrapper clearfix">
- <div class="clearfix" id="top">
- <h1 class="fl"><a href="${ctx}/"><img src="img/logo.png"/>a>h1>
- <div class="fr clearfix" id="top1">
- <form action="#" method="get" class="fl">
- <input type="text" placeholder="搜索" />
- <input type="button" />
- form>
- div>
- div>
- div>
- div>
-
- <div class="order cart mt">
- <div class="site">
- <p class="wrapper clearfix">
- <span class="fl">订单确认span>
- <img class="top" src="img/temp/cartTop02.png">
- p>
- div>
-
- <div class="orderCon wrapper clearfix">
- <div class="orderL fl">
-
- <h3>收件信息<a href="#" class="fr">新增地址a>h3>
-
- <div class="addres clearfix">
- <div class="addre fl on">
- <div class="tit clearfix">
- <p class="fl">张三1p>
- <span class="default">[默认地址]span>
- <p class="fr">
- <a href="#">删除a>
- <span>|span>
- <a href="#" class="edit">编辑a>
- p>
- div>
- <div class="addCon">
- <p>河北省 唐山市 路北区 大学生公寓村p>
- <p>15732570937p>
- div>
- div>
- <div class="addre fl">
- <div class="tit clearfix">
- <p class="fl">张三2
- p>
- <p class="fr">
- <a href="#" class="setDefault">设为默认a>
- <span>|span>
- <a href="#">删除a>
- <span>|span>
- <a href="#" class="edit">编辑a>
- p>
- div>
- <div class="addCon">
- <p>河北省 唐山市 路北区 大学生公寓村p>
- <p>15732570937p>
- div>
- div>
- <div class="addre fl">
- <div class="tit clearfix">
- <p class="fl">张三3
- p>
- <p class="fr">
- <a href="#" class="setDefault">设为默认a>
- <span>|span>
- <a href="#">删除a>
- <span>|span>
- <a href="#" class="edit">编辑a>
- p>
- div>
- <div class="addCon">
- <p>河北省 唐山市 路北区 大学生公寓村p>
- <p>15732570937p>
- div>
- div>
- div>
- <h3>支付方式h3>
-
- <div class="way clearfix">
- <img class="on" value="0" src="img/temp/way01.jpg">
- <img value="1" src="img/temp/way02.jpg">
- <img value="2" src="img/temp/way03.jpg">
- <img value="3" src="img/temp/way04.jpg">
- div>
- <h3>选择快递h3>
-
- <div class="dis clearfix">
- <span class="on">顺风快递span>
- <span>百世汇通span>
- <span>圆通快递span>
- <span>中通快递span>
- div>
- div>
- <div class="orderR fr">
- <div class="msg">
- <h3>订单内容<a href="${ctx}/shopCar/queryShopCar" class="fr">返回购物车a>h3>
- <#if goods??>
- <#list goods as g>
- <ul class="clearfix">
- <li class="fl">
- <img style="height: 87px; width: 87px;" src="${g.goodsImg}">
- li>
- <li class="fl">
- <p>${g.goodsName}p>
- <p>颜色分类:烟灰色玻璃瓶p>
- <p>数量:${g.quantity}p>
- li>
- <li class="fr">¥ ${g.goodsPrice}li>
- ul>
- #list>
- #if>
- div>
-
- <div class="tips">
- <p><span class="fl">商品金额:span><span class="fr">¥139.8span>p>
- <p><span class="fl">优惠金额:span><span class="fr">¥0.00span>p>
- <p><span class="fl">运费:span><span class="fr">免运费span>p>
- div>
-
- <div class="count tips">
- <p><span class="fl">合计:span><span class="fr">¥139.8span>p>
-
- div>
-
- <a href="javascript:void(0);" class="pay">去支付a>
- div>
- div>
- div>
-
-
- <div class="mask">div>
- <div class="adddz editAddre">
- <form action="#" method="get">
- <input type="text" placeholder="姓名" class="on" />
- <input type="text" placeholder="手机号" />
- <div class="city">
- <select name="">
- <option value="省份/自治区">省份/自治区option>
- select>
- <select>
- <option value="城市/地区">城市/地区option>
- select>
- <select>
- <option value="区/县">区/县option>
- select>
- <select>
- <option value="配送区域">配送区域option>
- select>
- div>
- <textarea name="" rows="" cols="" placeholder="详细地址">textarea>
- <input type="text" placeholder="邮政编码" />
- <div class="bc">
- <input type="button" value="保存" />
- <input type="button" value="取消" />
- div>
- form>
- div>
-
- <input type="hidden" id="gids" value="${RequestParameters['gids']!}"/>
- <#include "common/footer.html">
- <script src="js/others/order.js" type="text/javascript" charset="utf-8">script>
- <script src="js/public.js" type="text/javascript" charset="utf-8">script>
- <script src="js/pro.js" type="text/javascript" charset="utf-8">script>
- <script src="js/user.js" type="text/javascript" charset="utf-8">script>
- body>
- html>
展示结果如下:
实现思路
1.前台订单相关数据获取
2.后台进行下单操作
1)获取收货地址、收货人以及联系电话
2)获取支付方式
3)获取快递方式
在Order.html添加order.js,
order.js代码如下
- $(function(){
- $('.pay').click(function(){
- //获取收货地址、联系人、联系电话
- let name=$('.addres').find('div.on div:eq(0)>p:eq(0)').text().trim();
- let address=$('.addres').find('div.on div:eq(1)>p:eq(0)').text();
- let phone=$('.addres').find('div.on div:eq(1)>p:eq(1)').text();
- console.log("name=%s,address=%s,phone=%s",name,address,phone);
- //获取支付方式
- let pay=$('.way').find('img.on').attr('value');
- console.log(pay);
- //获取快递方式
- let dis=$('.dis').find('span.on').text();
- console.log(dis);
- //获取勾选结算的商品ID
- let gids=$('#gids').val();
- //拼接请求参数
- let params={
- gids:gids,
- address:address,
- person:name,
- telephone:phone,
- pay:pay,
- mail:dis
- };
- console.log(params);
-
- $.post('/order/addOrder',params,function(rs){
- if(rs.code==200){
- location.href='/page/ok.html';
- }else{
- alert(rs.msg);
- }
- },'json');
- });
- });
OrderDto :
- package com.ycx.spbootpro.model.dto;
-
- import com.ycx.spbootpro.model.Order;
- import lombok.Data;
-
- /**
- * @author 杨总
- * @create 2022-11-08 21:36
- */
- @Data
- public class OrderDto extends Order{
- private String gids;
- }
OrderController.java:
- package com.ycx.spbootpro.controller;
-
-
- import com.ycx.spbootpro.model.Goods;
- import com.ycx.spbootpro.model.User;
- import com.ycx.spbootpro.model.dto.OrderDto;
- import com.ycx.spbootpro.model.vo.ShopCar;
- import com.ycx.spbootpro.model.vo.ShopCarItem;
- import com.ycx.spbootpro.service.IOrderService;
- import com.ycx.spbootpro.utils.JsonResponseBody;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
-
- /**
- *
- * 订单信息表 前端控制器
- *
- *
- * @author yangzong
- * @since 2022-11-08
- */
- @Controller
- @RequestMapping("/order")
- public class OrderController {
-
- @RequestMapping("/toOrder")
- public ModelAndView toOrder(User user,
- String gids,
- HttpServletRequest request){
- ModelAndView mv=new ModelAndView();
- // 拿到购物车中的所有商品
- ShopCar shopCar = getShopCar(user, request);
- // 通过gids从购物车中筛选出指定的商品
- List<ShopCarItem> list=getGoods(shopCar,gids);
- mv.addObject("goods",list);
- mv.setViewName("order.html");
- return mv;
- }
-
- //通过gids从购物车中筛选出指定的商品
- private List<ShopCarItem> getGoods(ShopCar shopCar, String gids) {
- List<String> gidList = Arrays.asList(gids.split(","));
- List<ShopCarItem> items=shopCar.getItems();//购物车里的商品
- List<ShopCarItem> itemsNew=new ArrayList<>();//购物车中要结算的商品
- for (ShopCarItem item:items){
- if(gidList.contains(item.getGid()+"")){
- itemsNew.add(item);
- }
- }
- return itemsNew;
- }
-
- // 从session中获取购物车对象
- private ShopCar getShopCar(User user,
- HttpServletRequest request) {
- HttpSession session = request.getSession();
- ShopCar shopCar = (ShopCar) session.getAttribute(user.getId() + "_shopCar");
- if (shopCar == null) {
- shopCar = new ShopCar();
- session.setAttribute(user.getId() + "_shopCar", shopCar);
- }
- return shopCar;
- }
-
- @Autowired
- private IOrderService orderService;
-
- @RequestMapping("/addOrder")
- @ResponseBody
- public JsonResponseBody addOrder(User user,
- HttpServletRequest req,
- OrderDto orderDto){
- //获取购物车
- ShopCar shopCar = this.getShopCar(user, req);
- //获取结算商品集合
- List<ShopCarItem> shopCarItems = this.getGoods(shopCar, orderDto.getGids());
- //生成订单及订单项
- orderDto.setUserId(user.getId());
- orderService.addOrder(orderDto,shopCarItems);
- //从购物车中删除已结算的商品
- shopCar.delete(orderDto.getGids());
- //跳转支付页面(下节课内容)
- return new JsonResponseBody();
- }
-
- }
OrderServiceImpl.java:
- package com.ycx.spbootpro.service.impl;
-
- import com.ycx.spbootpro.model.Order;
- import com.ycx.spbootpro.mapper.OrderMapper;
- import com.ycx.spbootpro.model.OrderItem;
- import com.ycx.spbootpro.model.dto.OrderDto;
- import com.ycx.spbootpro.model.vo.ShopCarItem;
- import com.ycx.spbootpro.service.IOrderItemService;
- import com.ycx.spbootpro.service.IOrderService;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.ycx.spbootpro.utils.SnowFlake;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
-
- import java.math.BigDecimal;
- import java.util.ArrayList;
- import java.util.List;
-
- /**
- *
- * 订单信息表 服务实现类
- *
- *
- * @author yangzong
- * @since 2022-11-08
- */
- @Service
- public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
- @Autowired
- private OrderMapper orderMapper;
-
- @Autowired
- private IOrderItemService orderItemService;
-
- @Transactional
- @Override
- public void addOrder(OrderDto orderDto, List
shopCarItems ) { -
- //1) 生成订单ID (SnowFlake生成雪花ID,它的作用:生成一个随机的long类型的数字;相较于UUID的优点在于雪花ID可以排序)
- SnowFlake snowFlake = new SnowFlake(2, 3);
- Long orderId=snowFlake.nextId();
- orderDto.setOid(orderId);
- //2) 循环勾选的商品集合计算商品总价、获取商品详情集合
- //总价
- BigDecimal total=BigDecimal.valueOf(0);
- //定义商品详情集合
- List<OrderItem> orderItems=new ArrayList<>();
- OrderItem it=null;
- for (ShopCarItem shopCarItem : shopCarItems) {
- //累加小计等于总价
- total=total.add(shopCarItem.smalltotal());
- //初始化OrderItem商品详情对象
- it=new OrderItem();
- // 订单项表的ooid为自增,所以不需要设置
- it.setOid(orderId);
- it.setGid(shopCarItem.getGid());
- it.setGoodsName(shopCarItem.getGoodsName());
- it.setGoodsPrice(shopCarItem.getGoodsPrice());
- it.setQuantity(shopCarItem.getQuantity());
- orderItems.add(it);
- }
- orderDto.setTotal(total);
-
- //1.保存订单
- orderMapper.insert(orderDto);
- //2.保存订单对应的订单项
- orderItemService.saveBatch(orderItems);
- }
- }
SnowFlake :
(SnowFlake生成雪花ID,它的作用:生成一个随机的long类型的数字;相较于UUID的优点在于雪花ID可以排序)
- package com.ycx.spbootpro.utils;
-
- public class SnowFlake {
-
- /**
- * 起始的时间戳
- */
- private final static long START_STMP = 1480166465631L;
-
- /**
- * 每一部分占用的位数
- */
- private final static long SEQUENCE_BIT = 12; //序列号占用的位数
- private final static long MACHINE_BIT = 5; //机器标识占用的位数
- private final static long DATACENTER_BIT = 5;//数据中心占用的位数
-
- /**
- * 每一部分的最大值
- */
- private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
- private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
- private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
-
- /**
- * 每一部分向左的位移
- */
- private final static long MACHINE_LEFT = SEQUENCE_BIT;
- private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
- private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
-
- private long datacenterId; //数据中心
- private long machineId; //机器标识
- private long sequence = 0L; //序列号
- private long lastStmp = -1L;//上一次时间戳
-
- public SnowFlake(long datacenterId, long machineId) {
- if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
- throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
- }
- if (machineId > MAX_MACHINE_NUM || machineId < 0) {
- throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
- }
- this.datacenterId = datacenterId;
- this.machineId = machineId;
- }
-
- /**
- * 产生下一个ID
- *
- * @return
- */
- public synchronized long nextId() {
- long currStmp = getNewstmp();
- if (currStmp < lastStmp) {
- throw new RuntimeException("Clock moved backwards. Refusing to generate id");
- }
-
- if (currStmp == lastStmp) {
- //相同毫秒内,序列号自增
- sequence = (sequence + 1) & MAX_SEQUENCE;
- //同一毫秒的序列数已经达到最大
- if (sequence == 0L) {
- currStmp = getNextMill();
- }
- } else {
- //不同毫秒内,序列号置为0
- sequence = 0L;
- }
-
- lastStmp = currStmp;
-
- return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
- | datacenterId << DATACENTER_LEFT //数据中心部分
- | machineId << MACHINE_LEFT //机器标识部分
- | sequence; //序列号部分
- }
-
- private long getNextMill() {
- long mill = getNewstmp();
- while (mill <= lastStmp) {
- mill = getNewstmp();
- }
- return mill;
- }
-
- private long getNewstmp() {
- return System.currentTimeMillis();
- }
-
- public static void main(String[] args) {
- SnowFlake snowFlake = new SnowFlake(2, 3);
-
- long start = System.currentTimeMillis();
- for (int i = 0; i < 1000000; i++) {
- System.out.println(snowFlake.nextId());
- }
-
- System.out.println(System.currentTimeMillis() - start);
-
-
- }
- }
IOrderService :
- package com.ycx.spbootpro.service;
-
- import com.ycx.spbootpro.model.Order;
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.ycx.spbootpro.model.dto.OrderDto;
- import com.ycx.spbootpro.model.vo.ShopCarItem;
-
- import java.util.List;
-
- /**
- *
- * 订单信息表 服务类
- *
- *
- * @author yangzong
- * @since 2022-11-08
- */
- public interface IOrderService extends IService<Order> {
-
- void addOrder(OrderDto orderDto, List<ShopCarItem> shopCarItems);
- }
OrderMapper :
- package com.ycx.spbootpro.mapper;
-
- import com.ycx.spbootpro.model.Order;
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import org.springframework.stereotype.Repository;
-
- /**
- *
- * 订单信息表 Mapper 接口
- *
- *
- * @author yangzong
- * @since 2022-11-08
- */
- @Repository
- public interface OrderMapper extends BaseMapper<Order> {
-
- }
OrderItemMapper :
- package com.ycx.spbootpro.mapper;
-
- import com.ycx.spbootpro.model.OrderItem;
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import org.springframework.stereotype.Repository;
-
- /**
- *
- * Mapper 接口
- *
- *
- * @author yangzong
- * @since 2022-11-08
- */
- @Repository
- public interface OrderItemMapper extends BaseMapper<OrderItem> {
-
- }
数据插入了表中即可。
第一步: 1)登陆支付宝:https://open.alipay.com/ 打开自己的支付宝扫一扫: 2)首页找到进入管理中心 -> 开发工具推荐选择【沙箱】 3)下载安装支付宝开放平台开发助手: https://opendocs.alipay.com/common/02kipk 4)打开本地支付宝开放平台助手 -> 密钥工具 -> 生成密钥 -> 以默认方式(RSA2和PKCS8)生成应用私钥和应用公钥 5)在沙箱应用的开发信息中选择自定义密钥生成支付宝公钥(基于应用公钥生成支付宝公钥) 第二步:配置沙箱账号(买家)并完成手动充值 https://open.alipay.com/develop/sandbox/account 第三步:下载沙箱支付宝(只支持安卓) https://open.alipay.com/develop/sandbox/tool/alipayclint 沙箱工具 -> 支付宝客户端沙箱版 -> 请使用浏览器中的扫码功能扫描下载 注:请使用Android手机扫码下载支付宝客户端沙箱版;如需登录,请访问沙箱账号,在商家信息中获取帐密
实现思路
1.完成支付宝沙箱支付功能接入 2.支付成功后变更订单状态
完成支付宝沙箱支付功能接入
https://opendocs.alipay.com/common/02kg69
AlipayConfig.java
- package com.ycx.spbootpro.config;
-
- import com.ycx.spbootpro.model.dto.OrderDto;
-
- /**
- * 支付宝沙箱支付
- */
- public class AlipayConfig {
-
- public String goAlipay(OrderDto orderDto){
- try {
- // 1. 设置参数(全局只需设置一次)
- Factory.setOptions(aliconfig());
- // 2. 发起API调用(subject商品标题、outTradeNo订单编号、totalAmount总金额、returnUrl异步通知地址)
- AlipayTradePagePayResponse response = Factory.Payment.Page()
- .pay(orderDto.getOid()+"",
- orderDto.getOid()+"",
- orderDto.getTotal().toString(),
- "http://localhost:8081/page/ok.html"); //支付成功之后的异步通知(跳出到自己系统的哪个位置)
- System.out.println(response.body);
- return response.body;
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
-
- private Config aliconfig(){
- Config config=new Config();
- //沙箱支付宝地址
- config.gatewayHost="openapi.alipaydev.com";
- //协议https
- config.protocol="https";
- //应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
- config.appId="2016093000634935";
- //支付宝公钥
- config.alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy/NfwxWr2SfktLUekBR+3w/MUjz1mnW7/wzTOkN1WWIx4i4Ak2m7XDl+evV76FPCcj40HfqgLXxxSVW5a1cCwJ8Z9EgEd7dd1J0EW6slx0v1XMHoPQgOkEVijSWZLLjVhw9x88IWtPTr93YGHYWgR7T9S0M58ABrXPO5eoRxjDdkPCdzyDSmeVixzXZcrhCBHsUMJqipEr8NQA6Iz8QYRYBvQxtkv8j7NZcu+tFfWZ0EPswbsYp/ie+LFjFxTKsov27aduM466Q9ECOYRhCJvB0IbTyY/KYc/VT8TvZIyBA3JP1w2KYoUnKgc5sAGt7ifVXjH3jc8rrC4rWeUIGVFQIDAQAB";
- //签名方式
- config.signType="RSA2";
- //商户私钥(应用私钥),您的PKCS8格式RSA2私钥
- config.merchantPrivateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC06LM7m2P2svS9/2W6GwhP9WwcuwmA4ASjsIx6y1llPdrDfPU/79tnWpZXnaA+JcVhUv1iZ0JfEBCMCSPXISuIbvYWsRk+UJ5JqFhutuOSKgG2Xr5UFoHpsEZxehgOa7sPsy109XtQS0Nk/0FiyyoDYzgubPrvneEyqT4vnvMD3xDTILI8hqyTt+DD8HAKDR0D/5vMXi5JuSJfizIRkOQCT6zdx5QkOm40nk4xaJdlV2FmknYiJdy8TpEwTtmk6v8cSt9o6GcmydiqqmMfWZ1pFoeeoHw0zep6cdhhTVhnEWu4lTnUtS2W1kCtU1uDzAkDUygGVCNB2TaW9L1dme5TAgMBAAECggEAY6R7/AvVnm7pELFYVY5IIMpbtuNqE5rP010NsyDH51SPZvcvmfzBywaBIlcGiNSDB90PBSE81GFjy83I+NgjQy1izBLVhZYf6RAZTTnc1Ifgk5NRn70Z5x4ZXq1SDLdXvAkDs5T2S754q2tQl1qxlFYU/rU17b7259GCF/ajgXBwDGIeq+gaGvyWI7ZQAlIJttTisPJfEq9BujZ2NiKabTuyztqGTB2/3woX3pCDwRyYdjmw65obMwzh4CpXJ1ku5eTorwdI/wVX/FY2+4ZfeB632vTJcCWqJilwTwGhlLF0ZQfFgkBaABCLUOGVCIqL4V9JcZaTBYHbsRjfeDZ3WQKBgQDxjk8d4tFRqJWwyhxF9TddIbnR6LydUIOH9dvpoxGTSLQwFY/OYRA2aOfgch0Xturti/iGtu3MNQX1KTA5+WvHKPspYZrHkDpk6K9iXylIQo0+9L1bn73HAYuH/PqGoxewVstlegu5wk9u/BAh9bmGm1T0NOQZ7AafpplhxIGnNwKBgQC/ugUYbLIAI+Zt5rD7oaHUKSyYGPD2DFzP2tYUjKWQy5sh7fzNK0D/X49RI/ozbHctvl/CLUb6/vtbWTGe9LDstflY/v+q/WnLKW4alrgmztIwlq1x8wRkYSbG6QeMPYZsJ17SUY6JWfkVLxqS9oTqImmDRx13kM7CLdyepSxHxQKBgAoDqVoG1kC5aYNLzcJEuUfeJxMBwBgRh3Jyiex0uzzM7dN0gWK/+WkYDkzqzjP2fGTewa3sFY26wQV58KrmoUY/d7Iufrk5TIJ0dxjv8wkw4SQ0B0muJLMEaGF55nUAe/Hulz4cwjGwUZS7VHvj8Q4YkHwTWUWN2HRz9rXr7KgfAoGBALhHRISAXOozl1SEyhFh/phcZudd+aSUp1SFIwUnVi+A83++LiDJdTS/lZHIwcBRfY9zDrklKbcwA0p+xWniCHfMRHjcx8KCxf+mt5RIz4FFgtN+0ADZMpyEoG/JJR8PN7eWc9Y024p69yT8XE9rML+WCdJLNTBp98C9sfKuEYx9AoGBAN6RslNXhkGmAZEeZD9nUpfdJJz+55uXv6vlMSp9SHw0ZZH5Ndu0YfWLP3AhhrhP+u/2LVggAE50x12LVJjDWhr9eGUsCvuKLrekfZvUC7OGSmBcrLLkY0BbYGo9+S3FYxTe/rRd23jM4UEA0X/49gK0NMN1yrkhvYvQZBfn4PaJ";
- return config;
- }
- }
order.js变更如下:
支付会引发页面跳转,所以要将ajax请求换成页面跳转的方式
- $(function(){
- $('.pay').click(function(){
- //获取收货地址、联系人、联系电话
- let name=$('.addres').find('div.on div:eq(0)>p:eq(0)').text().trim();
- let address=$('.addres').find('div.on div:eq(1)>p:eq(0)').text();
- let phone=$('.addres').find('div.on div:eq(1)>p:eq(1)').text();
- console.log("name=%s,address=%s,phone=%s",name,address,phone);
- //获取支付方式
- let pay=$('.way').find('img.on').attr('value');
- console.log(pay);
- //获取快递方式
- let dis=$('.dis').find('span.on').text();
- console.log(dis);
- //获取勾选结算的商品ID
- let gids=$('#gids').val();
- //拼接请求参数
- let params={
- gids:gids,
- address:address,
- person:name,
- telephone:phone,
- pay:pay,
- mail:dis
- };
- console.log(params);
-
- // $.post('/order/addOrder',params,function(rs){
- // if(rs.code==200){
- // location.href='/page/ok.html';
- // }else{
- // alert(rs.msg);
- // }
- // },'json');
-
- location.href='/order/addOrder?'+parseParams(params);
-
- });
- });
-
- /**
- * JSON转URL参数
- * @param data
- * @returns {string}
- */
- function parseParams(data) {
- try {
- var tempArr = [];
- for (var i in data) {
- var key = encodeURIComponent(i);
- var value = encodeURIComponent(data[i]);
- tempArr.push(key + '=' + value);
- }
- var urlParamsStr = tempArr.join('&');
- return urlParamsStr;
- } catch (err) {
- return '';
- }
- }
OrderController.java代码变更如下:
- @Autowired
- private IOrderService orderService;
-
- @RequestMapping("/addOrder")
- @ResponseBody
- public String addOrder(User user,
- HttpServletRequest req,
- OrderDto orderDto){
- //获取购物车
- ShopCar shopCar = this.getShopCar(user, req);
- //获取结算商品集合
- List<ShopCarItem> shopCarItems = this.getGoods(shopCar, orderDto.getGids());
- //生成订单及订单项
- orderDto.setUserId(user.getId());
- orderService.addOrder(orderDto,shopCarItems);
- //从购物车中删除已结算的商品
- shopCar.delete(orderDto.getGids());
- //跳转支付页面(下节课内容)
- AlipayConfig alipayConfig = new AlipayConfig();
- return alipayConfig.goAlipay(orderDto);
- }
OrderController.java代码新增如下:
- /**
- * 支付成功后回调处理订单状态,完成整个下单流程的链路
- * @param param
- * @return
- */
- @RequestMapping("/orderFinish")
- public String orderFinish(@RequestParam Map<String, String> param){
- System.out.println("异步回调开始。。。。。。");
- Boolean signVerified=false;
-
- try {
- System.out.println(param);
- signVerified = Factory.Payment.Common().verifyNotify(param);
- System.out.println(signVerified);
- System.out.println("out_trade_no:"+param.get("out_trade_no"));
- System.out.println("total_amount:"+param.get("total_amount"));
- System.out.println("trade_no:"+param.get("trade_no"));
- if(signVerified){
- //支付成功
- //根据订单编号修改订单状态
- //update t_xxx set xx=?,tt=? where id=?
- orderService.update(new UpdateWrapper<Order>()
- .set("status",1)
- .setSql("pay_date=now()")
- .eq("oid",param.get("out_trade_no")));
- //跳转到支付成功页面
- }else{
- //支付失败
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "ok.html";
- }
AlipayConfig.java变更如下:
- package com.ycx.spbootpro.config;
-
- import com.alipay.easysdk.factory.Factory;
- import com.alipay.easysdk.kernel.Config;
- import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
- import com.ycx.spbootpro.model.dto.OrderDto;
-
- /**
- * 支付宝沙箱支付
- */
- public class AlipayConfig {
-
- public String goAlipay(OrderDto orderDto){
- try {
- // 1. 设置参数(全局只需设置一次)
- Factory.setOptions(aliconfig());
- // 2. 发起API调用(subject商品标题、outTradeNo订单编号、totalAmount总金额、returnUrl异步通知地址)
- AlipayTradePagePayResponse response = Factory.Payment.Page()
- .pay(orderDto.getOid()+"",
- orderDto.getOid()+"",
- orderDto.getTotal().toString(),
- // "http://localhost:8080/page/ok.html");
- "http://localhost:8080/order/orderFinish");
-
- //支付成功之后的异步通知(跳出到自己系统的哪个位置)
- System.out.println(response.body);
- return response.body;
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
-
- private Config aliconfig(){
- Config config=new Config();
- //沙箱支付宝地址
- config.gatewayHost="openapi.alipaydev.com";
- //协议https
- config.protocol="https";
- //应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
- config.appId="2021000120601533";
- //支付宝公钥
- config.alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6rbyoXBc0GLKuVQAAQsvimxWKKJr/0a93yqadDalqIfrWeXlg6tFoQT+DtRazaJSBb3DwQuq3GUpUHA5RaAkhpLId6fRFiufhIwiL1mt+urs82u2wpDRq0mw7eNdSSCN+SP03Gi15fuS94twPYCmHv9F/lecSs27vEIZkGUHN6ueeGm7I/9JeoxKXIu6D9agKZzMR2jY6ThVOmGnpkV95PxuI3XSG+nvkZoCSB2UJ7A7/P5xHiDw3sk8JEjpCDcwcUCq1Mbems3MrQLwS9rn2uqXFTwfS1Wl9aT3XCyMUKciSrO7mGm608S0swVFf52otLaEnd/44QVOD/vGdK05qwIDAQAB";
- //签名方式
- config.signType="RSA2";
- //商户私钥(应用私钥),您的PKCS8格式RSA2私钥
- config.merchantPrivateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDAlDU9aEj69WZluzXp912ACjjlrlJ+h9x5cr/bp/fq5CQapDIqgriW9dWAMS9VVUFsoiA7lU/5UGuvjgTTGlY/4+PRnlbxyk4LF8dM/4czAB7G8TTiZNmemijL8xdO/ifYXskZJ+epbbqZGGaf3GKIuvhAbfNRBoNJBG2pUxlPkpjuY1w4oox2h4fd9+ERknWpQClOArAKnmg9qsMjZMwHpUh561jyOSjWGeNUg+bpRVwfbhDp4Js/QC1vXBcR5lsADuyrC7He3apHF3uoTQBkC1NbL7RinpoSIom6ZUB3T9lmpJ2VBxvYTGIHM8GVebDc2c9UNj0tU0StHC/hIu/VAgMBAAECggEBAIs9XbU1prbVIiFiF9w/v3npajQfM4RLBU1Ge5P9QZKzO6uLlr4H4CE+RA05AslHKFO8cWPDVJyl2gaHv9NG0p/FTR5txt1x8bWxjqeMhhuI9bfQBPXAB1zWh7LW4754oySde/dVU/m73dP9wY3KUfAch4xGM0wdUmVD72ojLETMLOpiUweuVb+WNWX/mP5JtLEWI8M8usWMYN/0PaAfy0ayZrsLif3Tep21lf9wXAICgMWI/dtTgNAfmfU1WDdSC0ENKsV1/DYvqjlEmFDOQccRGjBWoGgXxamCukppTAtpWfqFHdsY9z/WGhB+XxVaKRklUuw51XwVGhlo0cKipCECgYEA/sEr8hxMl1m2X7VjsdD9PHXDsXrdEX+gyQCJHNlP8KEJQjEWV8znWGsNS3LvkA9/mC1JMDV/FVK/7CSPR0tHrr/Mv48DEUA+zukz4SBGqI+NlXg3CeoRrbJOj95zRp7na7jsw1UyxwIoXXWzthuqOZ7TPn4fQyZSNEsIQ/qL3v0CgYEAwYU5BxIwE+3dGLpKiBetKCg9LvE7KiYY4uzzlvR4aGC3jx4y9GYw31QEWyEbLHy8373nE2lIlCwhSdyWGQD+NWDLuebti9MCf9erRJ+ImdTPgg0Kwqui1P72qrjIP+QaMSNlZZBW2CsRIu7ST9HSdNTCkD6TkmmIYtxzlWXjZ7kCgYBt/uhDpHZpjyHQl1hRaaQ927dARYV4TbwVrbaGD0qV4mJGAz3bcSyen7Jg1mKbuCVmhn8oYqDZix41DuASb22nBUeZml0/sJat7kEpPi9kDn+afwp8rGUvs2J6ehkZ7/iKKZGJEZtYFBVrrSuIQM+yC2K4g+ppqv0peRA7kc2c3QKBgC2ai3nTG2lW4Id3PyEbEz8nXGO3jU29dJflZvHn4ogWYqtjXnahrlqyneQrxQ+SxZ+kTNQSN3xTefTB+s0hosZJbTj95nTQ4QHnfQDK55H4yH3JPQPrFpBDFTXeHbKQumth//8TKKQAYiVtSjptI79MdB0x4eza2b0SXlqSjChhAoGBAIl91/O6TiAX9SjUj0ItJtaPc3PyoAWh19ZlTHLlN6NQ8XevEHVUEtVkK2mKgXr7PUUNRw3meDGoB0fpYwiCW5s2R2x8xQAATo+SIQMyBwtAr610+vkhyjQSZ/u0JhIazDrI6RJZmvzeLMgLQwQKTXnKwHTUgxNUqRSE4F3eet46";
- return config;
- }
- }
测试:
随后便自动调回商品首页,下单已完成!
关于SpringBoot电商项目就到此告一段落啦~感谢收看。