一 表结构

image-20190711211421327


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-- 类目
create table `product_category` (
`category_id` int not null auto_increment,
`category_name` varchar(64) not null comment '类目名字',
`category_type` int not null comment '类目编号',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key (`category_id`)
);

-- 商品
create table `product_info` (
`product_id` varchar(32) not null,
`product_name` varchar(64) not null comment '商品名称',
`product_price` decimal(8,2) not null comment '单价',
`product_stock` int not null comment '库存',
`product_description` varchar(64) comment '描述',
`product_icon` varchar(512) comment '小图',
`product_status` tinyint(3) DEFAULT '0' COMMENT '商品状态,0正常1下架',
`category_type` int not null comment '类目编号',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key (`product_id`)
);

-- 订单
create table `order_master` (
`order_id` varchar(32) not null,
`buyer_name` varchar(32) not null comment '买家名字',
`buyer_phone` varchar(32) not null comment '买家电话',
`buyer_address` varchar(128) not null comment '买家地址',
`buyer_openid` varchar(64) not null comment '买家微信openid',
`order_amount` decimal(8,2) not null comment '订单总金额',
`order_status` tinyint(3) not null default '0' comment '订单状态, 默认为新下单',
`pay_status` tinyint(3) not null default '0' comment '支付状态, 默认未支付',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key (`order_id`),
key `idx_buyer_openid` (`buyer_openid`)
);

-- 订单商品
create table `order_detail` (
`detail_id` varchar(32) not null,
`order_id` varchar(32) not null,
`product_id` varchar(32) not null,
`product_name` varchar(64) not null comment '商品名称',
`product_price` decimal(8,2) not null comment '当前价格,单位分',
`product_quantity` int not null comment '数量',
`product_icon` varchar(512) comment '小图',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key (`detail_id`),
key `idx_order_id` (`order_id`)
);

-- 卖家(登录后台使用, 卖家登录之后可能直接采用微信扫码登录,不使用账号密码)
create table `seller_info` (
`id` varchar(32) not null,
`username` varchar(32) not null,
`password` varchar(32) not null,
`openid` varchar(64) not null comment '微信openid',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key (`id`)
) comment '卖家信息表';

二 VM

MyPassword centos7 +VirtualBox导入

三 日志

1
2
3
4
5
6
7
8
9
10
11
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private Logger logger = new LoggerFactory.getlogger(DemoApplicationTests.class);
@Test
public void contextLoads() {
logger.info("info");
logger.debug("debug");
logger.error("error");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//使用  slf4J 简化方法
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class DemoApplicationTests {
@Test
public void contextLoads() {
String name = "imooc";
String password = "123456";
log.info("info");
log.debug("debug");
log.error("error");
log.info("name: {},password: {}", name, password);
//log.error("n:{},a:{}", n, a);
}
}

1
2
3
4
5
6
7
# application.yml. 不常用
logging:
pattern:
console: "%d -%msg%n" # 设置日志格式
path: /var/log/tomcat/ #设置日期存储地址
file: /var/log/tomcat/sell.log
level: debug #默认info

logback-spring.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="UTF-8" ?>

<configuration>

<appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
%d - %msg%n
</pattern>
</layout>
</appender>

<appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>
%msg%n
</pattern>
</encoder>
<!--ن؛šمŠ�ه­–ه•�-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--و��م�„-->
<fileNamePattern>/var/log/tomcat/sell/info.%d.log</fileNamePattern>
</rollingPolicy>
</appender>


<appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%msg%n
</pattern>
</encoder>
<!--ن؛šمŠ�ه­–ه•�-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--و��م�„-->
<fileNamePattern>/var/log/tomcat/sell/error.%d.log</fileNamePattern>
</rollingPolicy>
</appender>

<root level="info">
<appender-ref ref="consoleLog" />
<appender-ref ref="fileInfoLog" />
<appender-ref ref="fileErrorLog" />
</root>

</configuration>

#第4章 买家端类目

买家端类目模块的开发,按照dao->service->api的顺序开发。贯穿单元测试。

1
2
3
4
5
6
7
8
9
10
11
@Entity
@DynamicUpdate
@Data
public class ProductCategory {

/** ه�؛ه›�id. */
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer categoryId;
......
}
  • @DynamicUpdate 动态的更新时间

  • Springboot-jpa Table ‘sell.hibernate_sequence’ doesn’t exist

1
@GeneratedValue(strategy = GenerationType.IDENTITY)
1
2
3
4
5
6
7
8
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://192.168.1.105/sell?characterEncoding=utf-8&useSSL=false
jpa:
show-sql: true
1
2
3
4
1 mysql地址 写VM虚拟机里面的。密码也要是Linux的
2 com.mysql.cj.jdbc.Driver CJ
3 lombok
mysql数据库驱动不要
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    @Test
public void testDao() {
Optional<ProductCategory> one = productCategoryRepository.findById(1);
if (one.isPresent()) {
ProductCategory productCategor = one.get();
System.out.println("======~~~====+~~~~=---===--==");
System.out.println(productCategor.toString());
System.out.println("======~~~====+~~~~=---===--==");
}
}

//保存Test 不要设置主键 主键自增长啦
@Test
public void saveTest() {
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryName("biaze");
productCategory.setCategoryType(2);
productCategoryRepository.save(productCategory);
}

//更新的话要设置主键 根据主键设置更新
@Test
public void saveUpdateTest() {
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryId(3);
productCategory.setCategoryName("biaze2");
productCategory.setCategoryType(2);
productCategoryRepository.save(productCategory);
}
}

image-20190712203056683

生成serviceTest的方法

  • Bug

    image-20190713082558460


image-20190713082617300

image-20190713082632357


image-20190713082649981


image-20190713082730063


第五章 买家商品

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.imooc.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.UTF8JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.imooc.demo.VO.ProductInfoVo;
import com.imooc.demo.VO.ProductVo;
import com.imooc.demo.VO.ResultVo;
import com.imooc.demo.dataobject.ProductCategory;
import com.imooc.demo.dataobject.ProductInfo;
import com.imooc.demo.repository.ProductInfoRepository;
import com.imooc.demo.service.CategoryServiceImpl;
import com.imooc.demo.service.ProductServiceImpl;
import com.imooc.demo.util.ResultVoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/buyer/product")
//http://localhost:8080/sell/buyer/product/list
public class BuyerProductController {
@Autowired
private CategoryServiceImpl categoryService;
@Autowired
private ProductServiceImpl productService;

@RequestMapping("/list")
public ResultVo list() {
List<ProductInfo> productInfoList = productService.findUpAll();
// categoryList存放商品的categoryType(product_info)
List<Integer> categoryList = new ArrayList<>();
for (ProductInfo productInfo : productInfoList) {
Integer categoryType = productInfo.getCategoryType();
categoryList.add(categoryType);
}
//根据categoryType查询商品种类(product_category)
List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryList);
/**
* 数据封装
* ResultVo.set(ProductVo).set(ProductInfoVo)
*/
List<ProductVo> productVoList = new ArrayList<>();
for (ProductCategory productCategory : productCategoryList) {
ProductVo productVo = new ProductVo();
productVo.setCategoryName(productCategory.getCategoryName());
productVo.setCategorytype(productCategory.getCategoryType());
//------------------------⭐️⭐️------⭐️⭐⭐️⭐-------------⭐️⭐⭐️⭐-------------------------------------------------
List<ProductInfoVo> productInfoList1 = new ArrayList<>();
for (ProductInfo newProductInfo : productInfoList) {
if (newProductInfo.getCategoryType().equals(productCategory.getCategoryType())) {
ProductInfoVo productInfoVo = new ProductInfoVo();
// BeanUtils.copyProperties(productInfoList, productInfoVo);
BeanUtils.copyProperties(newProductInfo, productInfoVo);
productInfoList1.add(productInfoVo);
}
}
//----------------------⭐️⭐---------⭐️⭐⭐️⭐----------⭐️⭐⭐️⭐---------------------------------------------------
productVo.setProductInfoVoList(productInfoList1);
productVoList.add(productVo);
}


//1 ResultVo result = new ResultVo();
// result.setMsg("成功");
// result.setCode(0);
// result.setData(productVoList);
//2 return new ResultVoUtil();
return ResultVoUtil.success(productVoList);
}
}

image-20190714115459817


  • 前端接口

    image-20190714115618966


查询ip地址的ip地址

image-20190714115709618

更改nginx.conf配置成本地ip地址

image-20190714115800928


设置域名

image-20190714120243104

image-20190714120346634


第六章 买家订单

DTO

image-20190714153806377

image-20190714153822552


image-20190714153841368


  • 异常处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Getter
    public enum ResultEnum {
    PRODUCT_NOT_EXIST(10, "商品不存在"),
    ;
    private Integer code;
    private String message;

    ResultEnum(Integer code, String message) {
    this.code = code;
    this.message = message;
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    public class SellException extends RuntimeException {
    private Integer code;

    public SellException(ResultEnum resultEnum) {
    super(resultEnum.getMessage());
    this.code = resultEnum.getCode();
    }
    }

    Navigate 操作数据库要保存 手动保存

    mysql AUTO_INCREMENT 设置主键自增

    detail_id int(32) NOT NULL AUTO_INCREMENT,

    注意在navicat中表已经建立了 就无法使用

    主键自增 Bug

    1
    The database returned no natively generated identity value; nested exception is org.hibernate.HibernateException: The database returned no natively generated identity value

    image-20190715074328283

image-20190715094458370


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Data
@Getter
@Setter
public class OrderDTO {
private String orderId;
//买家名字
private String buyerName;
//买家手机
private String buyerPhone;
//买家地址
private String buyerAddress;
//买家地址
private String buyerOpenid;
//订单总金额
private BigDecimal orderAmount;
//订单状态 默认为新下单
private Integer orderStatus = OrderStatusEnum.NEW.getCode();
/**
* 支付状态 默认为0 未支付
*/
private Integer payStatus = PayStatusEnum.WAIT.getCode();
private Date createTime;
private Date updateTime;
private List<OrderDetail> orderDetailList;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
@Autowired
OrderMasterRepostiory orderMasterRepostiory;
@Autowired
ProductServiceImpl productService;
@Autowired
OrderDetailRepository orderDetailRepository;
@Autowired
IdWorker idWorker;

@Override
@Transactional
public OrderDTO create(OrderDTO orderDTO) {
String orderId = idWorker.nextId() + "";
//1 拿到OrderDTO 存到ORDERmaster中
BigDecimal orderAmount = new BigDecimal(0);
//先拿到productId
List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
for (OrderDetail orderDetail : orderDetailList) {


//通过productID查询商品的信息 拷贝到orderDetail表中 存起来
ProductInfo productInfo = productService.findById(orderDetail.getProductId());
BeanUtils.copyProperties(productInfo, orderDetail);
orderDetail.setDetailId(idWorker.nextId() + "");
orderDetail.setOrderId(orderId);
orderDetailRepository.save(orderDetail);


//通过productID查询商品的的价格(从数据库中查)
BigDecimal productPrice = productInfo.getProductPrice();
//通过orderDTO查询商品的购买数量
Integer productQuantity = orderDetail.getProductQuantity();
//求出商品总价 存到orderMaster数据中
orderAmount = productPrice.multiply(new BigDecimal(productQuantity)).add(orderAmount);
OrderMaster orderMaster = new OrderMaster();
orderDTO.setOrderId(orderId);
//先拷贝在设置值要不然为空
BeanUtils.copyProperties(orderDTO, orderMaster);
//orderMaster.setOrderId("1314"); 不应该是ordermaster设置orderId 因为传来的orderDTO 需要一个id
orderMaster.setOrderAmount(orderAmount);
orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
orderMasterRepostiory.save(orderMaster);
}
//减库存product_stock =catrDTO 传递一个catrDTOS
List<CartDTO> cartDTOList = new ArrayList<>();
List<OrderDetail> orderDetailLists = orderDTO.getOrderDetailList();
for (OrderDetail orderDetail : orderDetailLists) {
String productId = orderDetail.getProductId();
Integer productQuantity = orderDetail.getProductQuantity();
CartDTO cartDTO = new CartDTO();
cartDTO.setProductQuantity(productQuantity);
cartDTO.setProductId(productId);
cartDTOList.add(cartDTO);
}
productService.decreaseStock(cartDTOList);
return orderDTO;
}

1
2
3
4
5
6
7
8
9
@Data
public class CartDTO {
//商品id
private String productId;
//商品数量
private Integer ProductQuantity;

public CartDTO() {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//减库存
@Override
@Transactional
public void decreaseStock(List<CartDTO> cartDTOS) {
if (cartDTOS == null) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
for (CartDTO cartDTO : cartDTOS) {
Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(cartDTO.getProductId());
if (productInfoOptional.isPresent()) {
ProductInfo productInfo = productInfoOptional.get();
Integer productStock = productInfo.getProductStock();
//新库存 newstock=数据库里面的库存-前端页面传来的商品数量
Integer newstock = productStock - cartDTO.getProductQuantity();
if (newstock == 0) {
throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
}
//更新库存 存到商品里面(不要新new了 直接放到原来的里面构造方法就是设置值)
// ProductInfo newproductInfo = new ProductInfo();
productInfo.setProductStock(newstock);
//更新了整条数据
// newproductInfo.setProductId(cartDTO.getProductId());
productInfoRepository.save(productInfo);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class OrderServiceImplTest {
@Autowired
OrderServiceImpl orderService;

@Test
public void create() throws Exception {

OrderDTO orderDTO = new OrderDTO();
orderDTO.setBuyerPhone("18868822111");
orderDTO.setBuyerName("张三");
orderDTO.setBuyerOpenid("ew3euwhd7sjw9diwkq");
orderDTO.setBuyerAddress("慕课网总部");
List<OrderDetail> orderDetails = new ArrayList<>();
OrderDetail orderDetail = new OrderDetail();
// java.lang.IllegalArgumentException: Source must not be null
orderDetail.setProductId("123457");
orderDetail.setProductQuantity(2); // 2 //购买数量
orderDetails.add(orderDetail);
orderDTO.setOrderDetailList(orderDetails);
//orderDTO.setOrderId("123"); orderDTO需要一个id
OrderDTO result = orderService.create(orderDTO);
log.info("result:{}", result);
}

查询订单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    @Override
public OrderDTO findOne(String orderId) {
Optional<OrderMaster> orderMasterOptional = orderMasterRepostiory.findById(orderId);
if (orderMasterOptional.isPresent()) {
OrderMaster orderMaster = orderMasterOptional.get();
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster, orderDTO);
// List<OrderDetail> orderDetailList = new ArrayList<>();
// OrderDetail orderDetail = new OrderDetail();
List<OrderDetail> byOrderId = orderDetailRepository.findByOrderId(orderDTO.getOrderId());
// orderDetailList.add(orderDetail);
orderDTO.setOrderDetailList(byOrderId);
return orderDTO;
} else {
throw new SellException(ResultEnum.ORDER_NOT_EXIST);
}
}

1
2
3
4
5
6
7
8
9
10
11
@Override
public List<OrderDTO> findList(Pageable pageable, String bunerOpenid) {
Page<OrderMaster> orderMasterPage = orderMasterRepostiory.findByBuyerOpenid(pageable, bunerOpenid);
List<OrderDTO> orderDTOList = new ArrayList<>();
for (OrderMaster orderMaster : orderMasterPage) {
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster, orderDTO);
orderDTOList.add(orderDTO);
}
return orderDTOList;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    //取消订单
@Override
public OrderDTO cancel(OrderDTO orderDTO) {
//判断订单状态 create的时候设置成 NEW (0,"新订单") FINSHED(1, "完结"), CEL(2, "取消")
if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
log.error("[取消订单] 订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//修改订单状态
OrderMaster orderMaster = new OrderMaster();
BeanUtils.copyProperties(orderDTO, orderMaster);
orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
OrderMaster updateResult = orderMasterRepostiory.save(orderMaster);
if (updateResult == null) {
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
//返回库存
if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
}
List<CartDTO> cartDTOList = new ArrayList<>();
CartDTO cartDTO = new CartDTO();
List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
for (OrderDetail orderDetail : orderDetailList) {
Integer productQuantity = orderDetail.getProductQuantity();
String productId = orderDetail.getProductId();
cartDTO.setProductId(productId);
cartDTO.setProductQuantity(productQuantity);
cartDTOList.add(cartDTO);
}
List<CartDTO> cartDTOList1 = cartDTOList;
productService.increaseStock(cartDTOList);
//如果已经支付 需要退款
// if (orderDTO.getPayStatus(PayStatusEnum.SUCCESS.getCode())) {
// //TODO
// }

return orderDTO;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//加库存
@Override
@Transactional
public void increaseStock(List<CartDTO> cartDTOS) {
for (CartDTO cartDTO : cartDTOS) {
String productId = cartDTO.getProductId();
Integer productQuantity = cartDTO.getProductQuantity();
ProductInfo productInfo = productInfoRepository.getOne(productId);
if (productInfo == null) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
Integer productStock = productInfo.getProductStock();
Integer newProductStock = productStock + productQuantity;
productInfo.setProductStock(newProductStock);
productInfoRepository.save(productInfo);

}

1
2
3
4
5
6
7
8
9
10
@Test
public void cancel() {
/**
* 分析 OrderDTO 里面有orderdetailList
* ordertailList里面有orderid productid 可以实现多表查询 不要用主外键盘 和多表查询
*/
OrderDTO orderDTO = orderService.findOne("1150598982927486976");
OrderDTO cancel = orderService.cancel(orderDTO);
System.out.println(cancel);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 @Override
@Transactional
public OrderDTO paid(OrderDTO orderDTO) {
//判断订单状态 create的时候设置成 NEW (0,"新订单") FINSHED(1, "完结"), CEL(2, "取消")
if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
log.error("[取消订单] 订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//判断支付状态 一开始create订单的时候设置的是WAIT 待支付
if (!orderDTO.getOrderStatus().equals(PayStatusEnum.WAIT.getCode())) {
throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
}

//修改支付状态
OrderDTO payorderDTO = new OrderDTO();
OrderMaster orderMaster = new OrderMaster();
BeanUtils.copyProperties(payorderDTO, orderMaster);
orderMaster.setPayStatus(PayStatusEnum.SUCCESS.getCode());
OrderMaster save = orderMasterRepostiory.save(orderMaster);
if (save == null) {
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
return orderDTO;
}
}

GSON

1
2
3
4
5
6
7
8
9
10
JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量。

1、JSON可以有两种格式

一种是对象格式的:

{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串
另一种是数组对象

[{"name":"JSON","address":"北京市西城区","age":25}]//数据对象格式
1
2
3
从上面的两种格式可以看出对象格式和数组对象格式唯一的不同则是在对象格式的基础上加上了[],再来看具体的结构,可以看出都是以键值对的形式出现的,中间以英文状态下的逗号(,)分隔。

在前端和后端进行数据传输的时候这种格式也是很受欢迎的,后端返回json格式的字符串,前台使用js中的JSON.parse()方法把JSON字符串解析为json对象,然后进行遍历,供前端使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class BuyerOrderController {

@Autowired
private OrderServiceImpl orderService;

@RequestMapping("/create")
public ResultVo<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
log.error("创建订单参数不正确" + defaultMessage);
throw new SellException(ResultEnum.FORM_ERROR);
}
OrderDTO orderDTO = new OrderDTO();
//属性的值不一样不能转啊(不可以用 BeanUtils.copyProperties)
//BeanUtils.copyProperties(orderForm, orderDTO);
String name = orderForm.getName();
String address = orderForm.getAddress();
String openid = orderForm.getOpenid();
String items = orderForm.getItems();
String phone = orderForm.getPhone();
orderDTO.setBuyerName(name);
orderDTO.setBuyerPhone(phone);
orderDTO.setBuyerOpenid(openid);
orderDTO.setBuyerAddress(address);
/**
* items: [{ cartDO
* productId: "1423113435324",
* productQuantity: 2 //购买数量
* }]
* OrderDetail:
* [{
productId: "1423113435324",
productQuantity: 2 //购买数量
}]
*/
//解析JSON 集合形式
//new Gson().fromJson(jsonArray, new TypeToken<List<Object>>(){}.getType());
/**
* List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType())
*/
Gson gson = new Gson();
String jsonString = items;
List<OrderDetail> orderDetails = null;
try {
orderDetails = gson.fromJson(jsonString, new TypeToken<List<OrderDetail>>() {
}.getType());
} catch (JsonSyntaxException e) {
log.error("购物车对象转换错误 items={}", orderForm.getItems());
e.printStackTrace();
} finally {
orderDTO.setOrderDetailList(orderDetails);
}
if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
log.error("[购物车为空】");
throw new SellException(ResultEnum.CART_EMPTY);
}
OrderDTO orderDTOcreate = orderService.create(orderDTO);
String orderId = orderDTOcreate.getOrderId();
log.error(orderId);
Map<String, String> map = new HashMap<>();
map.put("orderIds ", orderId);
ResultVo resultVo = ResultVoUtil.success(map);
return resultVo;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
public Page<OrderDTO> findList(Pageable pageable, String openId) {
Page<OrderMaster> orderMasterPage = orderMasterRepostiory.findByBuyerOpenid(pageable, openId);
//取出Page里面的内容
List<OrderMaster> content = orderMasterPage.getContent();
List<OrderDTO> orderDTOList = new ArrayList<>();
for (OrderMaster orderMaster : content) { //遍历的是Content而不是orderMasterPage
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster, orderDTO);
orderDTOList.add(orderDTO);
}
int totalPages = orderMasterPage.getTotalPages();
long totalElements = orderMasterPage.getTotalElements();
log.error("totalPages{},totalElements{}", totalPages, totalElements);
return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());

}
1
2
3
4
5
6
7
8
9
10
11
12
13
//查询订单列表
@RequestMapping("/list")
public ResultVo list(@RequestParam("openId") String openId, @RequestParam(value = "page", defaultValue = "2") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) {
//Pageable pageable, String bunerOpenid
if (StringUtils.isEmpty(openId)) {
log.error("openId----null");
}
PageRequest of = PageRequest.of(page - 1, size);
Page<OrderDTO> list = orderService.findList(of, openId);
List<OrderDTO> content = list.getContent();
return ResultVoUtil.success(content)

}
1
2
3
4
5
6
7
8
@RequestMapping("/detail")
public ResultVo detail(@RequestParam("openId") String openId, @RequestParam("orderId") String orderId) {


//TODO OpenID
OrderDTO orderDTO = orderService.findOne(orderId);
return ResultVoUtil.success(orderDTO);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   //查询订单详情
@RequestMapping("/detail")
public ResultVo detail(@RequestParam("openId") String openId, @RequestParam("orderId") String orderId) {

OrderDTO orderDTO = orderService.findOne(orderId);
if (orderDTO == null) {
return null;
}
if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openId)) {
log.error("查询订单失败openId={},orderDTO={}", openId, orderDTO);
throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
}
return ResultVoUtil.success(orderDTO);
}

//取消订单
@RequestMapping("/cancel")
public ResultVo cancel(@RequestParam("openId") String openId, @RequestParam("orderId") String orderId) {
OrderDTO orderDTO = orderService.findOne(orderId);
OrderDTO cancel = orderService.cancel(orderDTO);
if (cancel == null) {
return null;
}
if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openId)) {
log.error("取消订单失败查不到该订单openId={},orderDTO={}", openId, orderDTO);
throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
}
return ResultVoUtil.success();
}
}

第七章 微信

1 手工 方式(JSAPI)支付

image-20190717071920268

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_4


natapp

image-20190717082812135

image-20190717082842533

image-20190717082928962

该网址 http://ywy9n8.natappfree.cc 就是可以全球访问的网址,可以发给您的小伙伴试试 :)


image-20190717083944900

![image-20190717084011877](../../../../Library/Application Support/typora-user-images/image-20190717084011877.png)


1
2
3
4
5
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.4.0</version>
</dependency>

https://github.com/Wechat-Group/WxJava


image-20190717090809065

image-20190717113013573

image-20190717121945289



image-20190815144058520


image-20190815144126661


y1047629166@163.com. yhp836143 —–微信公众号小程序


操作步骤

https://blog.51cto.com/zero01/2117892. 五角星大佬博客


第三方 SDK

前端项目位置 centos7.3

image-20190815185938074

Vim index.JS


image-20190815190252417


image-20190815190349822


image-20190815191142994


Charles sde你用。使用。手机代理

image-20190815191443004

手机 连接WI-FI。 查看ip ran hou ping 一下。设置代理 手动ifconfigimage-20190815195230845

image-20190815195230845

image-20190815195340298

微信支付