0005_基于SpringBoot的乐活商城的设计与实现 (C2C)(源码+部署文档+讲解等)

🍅联系方式QQ------------------------------:380223251----------------------------------------------🍅
博主介绍:✌10年以上互联网大厂项目经理、高校兼职讲师、创业导师、csdn特邀作者✌
👇🏻 精彩专栏推荐订阅👇🏻 不然下次找不到哟
2022-2024年最全的计算机软件毕业设计选题大全:1000个热门选题推荐✅
Java项目精品实战案例《100套》
Java微信小程序项目实战《100套》
感兴趣的可以先收藏起来,还有大家在毕设选题,项目以及论文编写等相关问题都可以给我留言咨询,希望帮助更多的人

1.系统运行环境

开发系统:Windows10

架构模式:MVC/前后端分离

JDK版本:Java JDK1.8

开发工具:IDEA

数据库版本: mysql5.7

数据库可视化工具: navicat for mysql

服务器:SpringBoot自带 apache tomcat

2.使用技术

Springboot、Mybatis、支付宝沙箱支付、Redis、Mysql等

3.系统截图

3.1 系统首页

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.2 商品详情

在这里插入图片描述
在这里插入图片描述

3.3 登录

在这里插入图片描述

3.4 订单确认

在这里插入图片描述

3.5支付

在这里插入图片描述

3.6 管理后台首页

在这里插入图片描述

3.7 店铺列表

在这里插入图片描述

3.8 轮播图管理

在这里插入图片描述

3.9 品牌管理

在这里插入图片描述

4.部分代码

4.1 核心配置文件

spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/computer_shop?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver
  devtools:
    restart:
      exclude: /static/
mybatis:
  type-aliases-package: com.springboot.projcet.pojo
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
server:
  port: 8080

4.2 用户管

package com.springboot.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.springboot.project.pojo.Store;
import com.springboot.project.pojo.User;
import com.springboot.project.service.StoreService;
import com.springboot.project.service.UserService;
import com.springboot.project.tools.MD5Util;
import com.springboot.project.tools.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author 38022
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StoreService storeService;

    /*  @ResponseBody
      @RequestMapping("/getUsers")
      public List<User> getAllUser(){
          List<User> userList = userService.getAllUsers();
          for (User user : userList) {
              System.out.println(user);
          }
          return userList;
      }*/
    //用户登录
    @RequestMapping("/user_login")
    @ResponseBody
    public String login(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        String userName = user.getUserName();
        if (userName == null) {
            userName = user.getUserEmail();
            if (userName == null) {
                userName = user.getUserPhone();
            }
        }
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String ph = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$";
        if (userName.matches(ph)) {
            user.setUserName(null);
            user.setUserPhone(userName);
        } else if (userName.matches(em)) {
            user.setUserName(null);
            user.setUserEmail(userName);
        }
        System.out.println(user);
        user.setUserPwd(MD5Util.PwdMD5(user.getUserPwd()));
        User user_login = userService.userLogin(user);
        if (user_login != null) {
            if (user_login.getUserState() == 1) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user_login);
                session.setAttribute("userId", user_login.getUserId());
                return "ok";
            }
            if (user_login.getUserState() == 2) {
                return "not";
            } else {
                return "delete";
            }
        } else {
            return "fail";
        }
    }

    //注册
    @RequestMapping("/registerUser")
    @ResponseBody
    public String register(User user) {
        user.setUserPwd(MD5Util.PwdMD5(user.getUserPwd()));
        int rs = userService.addUser(user);
        if (rs > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    //修该个人信息
    @RequestMapping("/updateUser")
    @ResponseBody
    public String updateUser(User user, HttpServletRequest request) {
        int rs = userService.updateUser(user);
        user = userService.getById(user.getUserId());
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        if (rs > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    //管理员修该个人信息
    @RequestMapping("/adminUpdateUser")
    @ResponseBody
    public String adminUpdateUser(User user, HttpServletRequest request) {
        int rs = userService.updateUser(user);
        user = userService.getById(user.getUserId());
        if (rs > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    //按用户名查询
    @RequestMapping("/checkByName/{userName}")
    @ResponseBody
    public String checkByName(@PathVariable String userName) {
        String msg = "";
        User user = userService.getByName(userName);
        if (user == null) {
            msg = "ok";
        } else {
            msg = "fail";
        }
        return msg;
    }

    @RequestMapping("/checkByName2/{userName}/{userId}")
    @ResponseBody
    public String checkByName2(@PathVariable String userName, @PathVariable int userId) {
        String msg = "";
        User user = userService.getByName2(userName, userId);
        if (user == null) {
            msg = "ok";
        } else {
            msg = "fail";
        }
        return msg;
    }

    //按用户电话号码查询
    @RequestMapping("/checkByPhone/{userPhone}")
    @ResponseBody
    public String checkByPhone(@PathVariable String userPhone) {
        String msg = "";
        User user = userService.getByPhone(userPhone);
        if (user == null) {
            msg = "ok";
        } else {
            msg = "fail";
        }
        return msg;
    }

    @RequestMapping("/checkByPhone2/{userPhone}/{userId}")
    @ResponseBody
    public String checkByPhone2(@PathVariable String userPhone, @PathVariable int userId) {
        String msg = "";
        User user = userService.getByPhone2(userPhone, userId);
        if (user == null) {
            msg = "ok";
        } else {
            msg = "fail";
        }
        return msg;
    }

    //按用户邮箱查询
    @RequestMapping("/checkByEmail/{userEmail}")
    @ResponseBody
    public String checkByEmail(@PathVariable String userEmail) {
        String msg = "";
        User user = userService.getByEmail(userEmail);
        if (user == null) {
            msg = "ok";
        } else {
            msg = "fail";
        }
        return msg;
    }

    @RequestMapping("/checkByEmail2/{userEmail}/{userId}")
    @ResponseBody
    public String checkByEmail2(@PathVariable String userEmail, @PathVariable int userId) {
        String msg = "";
        User user = userService.getByEmail2(userEmail, userId);
        if (user == null) {
            msg = "ok";
        } else {
            msg = "fail";
        }
        return msg;
    }

    //按id查询用户,去修改页面
    @RequestMapping("/getById/{userId}")
    public String getById(@PathVariable int userId, Model model) {
        User user = userService.getById(userId);
        model.addAttribute("user", user);
        return "/user/user_update";
    }

    //验证密码
    @RequestMapping("/verifyPwd/{oldPwd}")
    @ResponseBody
    public String verifyPwd(@PathVariable String oldPwd, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println(MD5Util.PwdMD5(user.getUserPwd()));
        if (MD5Util.PwdMD5(oldPwd).equals(user.getUserPwd())) {
            return "success";
        } else {
            return "fail";
        }
    }

    /*去用户修改密码页面*/
    @RequestMapping("/toUpPwd")
    public String toUpUserPwd() {
        return "/user/user_upPwd";
    }

    //修改密码
    @RequestMapping("/updatePwd/{userPwd}")
    @ResponseBody
    public String upUserPwd(@PathVariable String userPwd, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println(userPwd);
        user.setUserPwd(MD5Util.PwdMD5(userPwd));
        int rs = userService.updatePwd(user);
        if (rs > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    //上传头像
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upUserImg(@RequestParam(value = "file") MultipartFile file) throws IOException {
        /*List<String> list = Arrays.asList("jpg","jpeg", "png", "bmp", "gif");
        ArrayList<String> imglist = new ArrayList<>();
        imglist.addAll(list);*/
        String name = file.getOriginalFilename();
      /*  String fileSuffix = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        System.out.println(fileSuffix);*/

       /* String path = ResourceUtils.getURL("classpath:").getPath()+"static/img/header/"+name;
        String path2 = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+"/img/header/"+name;*/
        String path = "D:/project/bishe/5_springboot/基于SpringBoot的乐活商城的设计与实现 (C2C)/template/src/main/resources/static/img/header/" + name;
        file.transferTo(new File(path));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userImg", name);
        return jsonObject;
    }

    //添加收货地址
    @RequestMapping("/toAddAddress")
    public String toUpAddress() {
        return "/user/user_address";
    }

    //注销 退出登录
    @RequestMapping("/user_logout")
    @ResponseBody
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "success";
    }

    /*查询用户全部信息 分页*/
    @RequestMapping("/getAllUser")
    @ResponseBody
    public JSONObject getAllUser(int page, int limit, String keyWord) {
        PageBean pageBean = new PageBean();
        pageBean.setPage(page);
        pageBean.setLimit(limit);
        PageBean<User> pBean = userService.getPageBean(pageBean.getPage(), pageBean.getLimit(), keyWord);
        JSONObject jsObj = new JSONObject();
        jsObj.put("msg", "");
        jsObj.put("code", 0);
        jsObj.put("count", pBean.getTotalRecs());
        jsObj.put("data", pBean.getJsArr());
        return jsObj;
    }

    /*删除用户*/
    @RequestMapping("/deleteUser/{userId}")
    @ResponseBody
    public String deleUser(@PathVariable int userId) {
        int rs = userService.deleteUser(userId);
        if (rs > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /*批量删除用户*/
    @RequestMapping("/batchDeleteUser")
    @ResponseBody
    public String batchDelete(String batchId) {
        String[] list = batchId.split(",");
        boolean flag = true;
        for (String id : list) {
            int userId = Integer.valueOf(id);
            int rs = userService.deleteUser(userId);
            if (rs < 0) {
                flag = false;
            }
        }
        if (flag) {
            return "success";
        } else {
            return "fail";
        }
    }

    /*改变用户状态*/
    @RequestMapping("/changeUserState/{userState}/{userId}")
    @ResponseBody
    public String changeUserState(@PathVariable int userState, @PathVariable int userId) {
        int rs = userService.changeUserState(userState, userId);
        if (rs > 0) {
            return "success";
        } else {
            return "fail";
        }
    }
}

4.3 支付管理

package com.springboot.project.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.springboot.project.config.AlipayConfig;
import com.springboot.project.pojo.*;
import com.springboot.project.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 38022
 */
@Controller
@RequestMapping("/payment")
public class PayController {

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private EvaluateService evaluateService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private StoreService storeService;

    /*待付款*/
    @RequestMapping("/getOrderIdByIdBuy/{OrderId}")
    public void  getOrderIdByIdBuy(@PathVariable Long OrderId, Model model, HttpServletResponse response,HttpSession session,HttpServletRequest request)  {

        request.getSession().removeAttribute("orderId3");
        String type = "info"; // 类型
        OrderDetail orderDetail = orderService.selectGoodsIdByOrderId(OrderId);
        Goods goods = goodsService.getGoodsById(orderDetail.getDetailGoods());

        BigDecimal price = goods.getGoodsPrice();
        int price2 = price.intValue() * orderDetail.getDetailNum();

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getOpenApiDomain(),
                    alipayConfig.getAppId(),
                    alipayConfig.getMerchantPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()); //获得初始化的AlipayClient

            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
            alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());//在公共参数中设置回跳和通知地址

            if (type.equals("info")){
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+OrderId+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":\""+price2+"\"," +
                        "    \"subject\":\""+goods.getGoodsName()+"\"," +
                        "    \"body\":\""+goods.getGoodsName()+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
            }else if (type.equals("cart")){
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+OrderId+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":\""+goods.getGoodsPrice()+"\"," +
                        "    \"subject\":\""+goods.getGoodsName()+"\"," +
                        "    \"body\":\""+goods.getGoodsName()+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
            }

            String form="";
            try {
                form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            session.setAttribute("type",type);
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("exception", "支付出错了!");
        }
    }

    /*单样商品购买生成订单*/
    @RequestMapping("/payById/{goodsId}/{num}")
    public void  payById(@PathVariable int goodsId, @PathVariable int num, Model model, HttpServletResponse response, HttpServletRequest request)  {
        request.getSession().removeAttribute("orderId3");
        String orderId = "";
        String orderDetailsId = "";
        String type = "info";
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");
        Goods goods = goodsService.getGoodsById(goodsId);
        List<Address> address = addressService.getAddrByUserId(userId);
        Address address1 = addressService.getAddrByUserIdByDefault(userId);
        BigDecimal price = goods.getGoodsPrice();
        int price2 = price.intValue() * num;
        BigDecimal price3 = new BigDecimal(price2);

        goods.setGoodsPrice(price3);
        model.addAttribute("address1",address1);
        model.addAttribute("goods",goods);
        model.addAttribute("num",num);

        Long orderId2 = Long.valueOf(getOrderIdByTime());
        Goods goods1 = goodsService.selectStoreByGoodsId(goods.getGoodsId());
        Orderinfo order = new Orderinfo();
        order.setOrderId(orderId2);
        order.setOrderUser(userId);
        order.setOrderDate(new Date());
        order.setOrderPrice(price3);
        /*待付款*/
        order.setOrderState(1);
        order.setOrderReceiver(address1.getAddrReceiver());
        order.setOrderPhone(address1.getAddrPhone());
        order.setOrderAddress(address1.getAddrProvince()+address1.getAddrCity()+address1.getAddrArea()+address1.getAddrStreet()+address1.getAddrDetail());
        order.setCreateTime(new Timestamp(new Date().getTime()));
        order.setUpdateTime(new Timestamp(new Date().getTime()));
        order.setOrderStore(goods1.getGoodsStore());
        orderService.insertOrder(order);

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setDetailOrder(orderId2);
        orderDetail.setDetailGoods(goods.getGoodsId());
        orderDetail.setDetailPrice(price3.doubleValue());
        orderDetail.setDetailNum(num);
        orderService.insertDetail(orderDetail);

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getOpenApiDomain(),
                    alipayConfig.getAppId(),
                    alipayConfig.getMerchantPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()); //获得初始化的AlipayClient

            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
            alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());//在公共参数中设置回跳和通知地址

            if (type.equals("info")){
               /* Order order = orderService.selectByOrderIdAndOrderDetailsId(orderId,orderDetailsId);*/
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+orderId2+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":\""+price2+"\"," +
                        "    \"subject\":\""+goods.getGoodsName()+"\"," +
                        "    \"body\":\""+goods.getGoodsName()+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
            }else if (type.equals("cart")){
              /*  OrderDetails orderDetails = detailsService.selectByPrimaryKey(orderId);*/
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+orderId2+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":\""+price2+"\"," +
                        "    \"subject\":\""+goods.getGoodsName()+"\"," +
                        "    \"body\":\""+goods.getGoodsName()+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
            }
            String form="";
            try {
                form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            session.setAttribute("type",type);
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("exception", "支付出错了!");
        }
    }

    /*结算*/
    @RequestMapping("/pay")
    public void  pay( Model model, HttpServletResponse response, HttpServletRequest request)  {
        String orderId = "";
        String orderDetailsId = "";
        String type = "info";
        HttpSession session = request.getSession();
        // CartId集合
        List Classifys = (List) session.getAttribute("Classifys");
        // 商品数量集合
        List num = (List) session.getAttribute("num");
        int userId = (int) session.getAttribute("userId");
        List<Integer> goodsId = new ArrayList();
        BigDecimal Allprice = new BigDecimal("0");
        /*通过cartId拿到goodsId*/
        for(int i =0;i<Classifys.size();i++){
            String  a = (String) Classifys.get(i);
            Integer b = Integer.parseInt(a);
            Cart cart = goodsService.getGoodsIdByCartId(b);
            goodsId.add(cart.getCartGoods());
        }
        List<Goods> goodsList = new ArrayList<>();
        /*通过goodsId拿到goods*/
        for(int i =0;i<goodsId.size();i++) {
            Integer b = goodsId.get(i);
            Goods goods = goodsService.getGoodsById(b);
            goodsList.add(goods);
        }
        // 根据商品集合,获取总价
        for(int j=0;j<goodsList.size();j++) {
            BigDecimal price = goodsList.get(j).getGoodsPrice();
            String num2 = (String) num.get(j);
            Integer num3 = Integer.parseInt(num2);
            int price2 = price.intValue() * num3;
            BigDecimal price3 = new BigDecimal(price2);
            goodsList.get(j).setGoodsPrice(price3);
            Allprice = Allprice.add(price3);
        }
        // 数量
        for (int c =0;c<num.size();c++){
            String  a = (String) num.get(c);
            Integer b = Integer.parseInt(a);
            goodsList.get(c).setGoodsNums(b);
        }
        // 定义订单id
        Long orderId2 = null;
        String goodsName = "";
        List<Long> orderId3 = new ArrayList<>();
        //循环遍历生成订单
        for(int c=0;c < goodsList.size();c++){
            Goods goods = goodsService.getGoodsById(goodsList.get(c).getGoodsId());
            goodsName = goodsName + goods.getGoodsName() + " ";
            List<Address> address = addressService.getAddrByUserId(userId);
            Address address1 = addressService.getAddrByUserIdByDefault(userId);
            goods.setGoodsPrice(goodsList.get(c).getGoodsPrice());
            model.addAttribute("address1",address1);
            model.addAttribute("goods",goods);
            model.addAttribute("num",num);
            orderId2 = Long.valueOf(getOrderIdByTime());
            Goods goods1 = goodsService.selectStoreByGoodsId(goods.getGoodsId());
            Orderinfo order = new Orderinfo();
            order.setOrderId(orderId2);
            order.setOrderUser(userId);
            order.setOrderDate(new Date());
            order.setOrderPrice(goodsList.get(c).getGoodsPrice());
            order.setOrderState(1);
            order.setOrderReceiver(address1.getAddrReceiver());
            order.setOrderPhone(address1.getAddrPhone());
            order.setOrderAddress(address1.getAddrProvince()+address1.getAddrCity()+address1.getAddrArea()+address1.getAddrStreet()+address1.getAddrDetail());
            order.setCreateTime(new Timestamp(new Date().getTime()));
            order.setUpdateTime(new Timestamp(new Date().getTime()));
            order.setOrderStore(goods1.getGoodsStore());
            orderService.insertOrder(order);
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setDetailOrder(orderId2);
            orderDetail.setDetailGoods(goods.getGoodsId());
            BigDecimal bigDecimal = goodsList.get(c).getGoodsPrice();
            orderDetail.setDetailPrice(bigDecimal.doubleValue());
            orderDetail.setDetailNum(goodsList.get(c).getGoodsNums());
            orderService.insertDetail(orderDetail);

            orderId3.add(orderId2);
        }
        session.setAttribute("orderId3",orderId3);
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getOpenApiDomain(),
                    alipayConfig.getAppId(),
                    alipayConfig.getMerchantPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()); //获得初始化的AlipayClient

            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
            alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());//在公共参数中设置回跳和通知地址

            if (type.equals("info")){
                /* Order order = orderService.selectByOrderIdAndOrderDetailsId(orderId,orderDetailsId);*/
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+orderId2+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":\""+Allprice+"\"," +
                        "    \"subject\":\""+goodsName+"\"," +
                        "    \"body\":\""+goodsName+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
            }else if (type.equals("cart")){
                /*  OrderDetails orderDetails = detailsService.selectByPrimaryKey(orderId);*/
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+orderId2+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":\""+Allprice+"\"," +
                        "    \"subject\":\""+goodsName+"\"," +
                        "    \"body\":\""+goodsName+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
            }

            String form="";
            try {
                form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            session.setAttribute("type",type);
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("exception", "支付出错了!");
        }
    }
    /**/
    @RequestMapping("/return")
    public String returnUrl(Long out_trade_no,String total_amount,String body,
                            Model model,HttpSession session) throws ParseException {

        List<Long> orderId3 = (List<Long>) session.getAttribute("orderId3");
        if(orderId3 != null){
            for (Long orderId : orderId3){
                Orderinfo orderinfo = new Orderinfo();
                orderinfo.setOrderId(orderId);
                orderinfo.setOrderState(2);/*已支付*/
                orderService.updataByno(orderinfo);
                OrderDetail orderDetail = goodsService.selectGoodIdByOrderId(orderId);
                goodsService.updataGoodsNumsAndSales(orderDetail.getDetailGoods(),orderDetail.getDetailNum());
            }
        }else{
            Orderinfo orderinfo = new Orderinfo();
            orderinfo.setOrderId(out_trade_no);
            orderinfo.setOrderState(2);
            orderService.updataByno(orderinfo);
            OrderDetail orderDetail = goodsService.selectGoodIdByOrderId(out_trade_no);
            goodsService.updataGoodsNumsAndSales(orderDetail.getDetailGoods(),orderDetail.getDetailNum());
        }
        /*返回到用户订单*/
        int userId = (int) session.getAttribute("userId");
        List<Orderinfo> orderinfoList = orderService.selectOrderByUserId(userId);
        List<Integer> orderDetails2 = new ArrayList<>();
        for (Orderinfo orderinfo1 : orderinfoList ) {
            Long id = orderinfo1.getOrderId();
            OrderDetail orderDetail3 = orderService.selectGoodsIdByOrderId(id);
            orderDetails2.add(orderDetail3.getDetailGoods());
        }

        List<Goods> goods = new ArrayList<>();
        for (Integer integer : orderDetails2) {
            Goods goods1 = goodsService.getGoodsById(integer);
            goods.add(goods1);
        }
        List<orderGoods3> orderGoodsList = new ArrayList<>();

        for (int i = 0;i < orderinfoList.size();i++) {
            Store store = storeService.selectByOrderId(orderinfoList.get(i).getOrderStore());
            orderGoods3 orderGoods = new orderGoods3();
            orderGoods.setOrderId(orderinfoList.get(i).getOrderId());
            orderGoods.setOrderUser(orderinfoList.get(i).getOrderUser());
            orderGoods.setOrderDate(orderinfoList.get(i).getOrderDate());
            orderGoods.setOrderPrice(orderinfoList.get(i).getOrderPrice());
            orderGoods.setOrderState(orderinfoList.get(i).getOrderState());
            orderGoods.setOrderReceiver(orderinfoList.get(i).getOrderReceiver());
            orderGoods.setOrderPhone(orderinfoList.get(i).getOrderPhone());
            orderGoods.setOrderAddress(orderinfoList.get(i).getOrderAddress());
            orderGoods.setCreateTimeOrder(orderinfoList.get(i).getCreateTime());
            orderGoods.setUpdateTimeOrder(orderinfoList.get(i).getUpdateTime());

            orderGoods.setGoodsStore(store.getStoreName());

            orderGoods.setGoodsId(goods.get(i).getGoodsId());
            orderGoods.setGoodsName(goods.get(i).getGoodsName());
            orderGoods.setGoodsNums(goods.get(i).getGoodsNums());
            orderGoods.setGoodsBrand(goods.get(i).getGoodsBrand());
            orderGoods.setGoodsType(goods.get(i).getGoodsType());
            orderGoods.setGoodsPrice(goods.get(i).getGoodsPrice());
            orderGoods.setGoodsDesc(goods.get(i).getGoodsDesc());
            orderGoods.setGoodsSales(goods.get(i).getGoodsSales());
            orderGoods.setGoodsState(goods.get(i).getGoodsState());
            orderGoods.setGoodsImg(goods.get(i).getGoodsImg());
            orderGoods.setCreateTimeGoods(goods.get(i).getCreateTime());

            Timestamp ts = new Timestamp(System.currentTimeMillis());
            DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

            SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            orderGoods.setUpdateTimeGoods(sf2.format(orderinfoList.get(i).getCreateTime()));

            orderGoodsList.add(orderGoods);
        }

        model.addAttribute("orderinfoList",orderinfoList);
        model.addAttribute("orderGoodsList",orderGoodsList);
        return "/orderUserList";
    }

    @RequestMapping("/notify")
    public void notifyUrl(){
        System.out.println("notify--------------------------");
    }

    public static String getOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
         return newDate+result;
    }

}

  • 37
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值