Skip to content

Commit

Permalink
微信网页授权
Browse files Browse the repository at this point in the history
  • Loading branch information
seraphJ committed Nov 23, 2022
1 parent 047652b commit 40eb691
Show file tree
Hide file tree
Showing 14 changed files with 554 additions and 1 deletion.
12 changes: 12 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>2.7.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

<build>
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/com/gxj/config/WechatAccountConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.gxj.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {

private String mpAppId;
private String mpAppSecret;
}
33 changes: 33 additions & 0 deletions src/main/java/com/gxj/config/WechatMpConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.gxj.config;

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@Configuration
public class WechatMpConfig {

@Autowired
private WechatAccountConfig accountConfig;
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
return wxMpService;
}

@Bean
public WxMpConfigStorage wxMpConfigStorage() {
WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId(accountConfig.getMpAppId());
wxMpConfigStorage.setSecret(accountConfig.getMpAppSecret());
return wxMpConfigStorage;
}

}
18 changes: 18 additions & 0 deletions src/main/java/com/gxj/controller/BuyerOrderController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.gxj.enums.ResultEnum;
import com.gxj.exception.SellException;
import com.gxj.form.OrderForm;
import com.gxj.service.BuyerService;
import com.gxj.service.OrderService;
import com.gxj.utils.ResultVOUtil;
import com.mysql.cj.util.StringUtils;
Expand All @@ -30,6 +31,9 @@ public class BuyerOrderController {
@Autowired
private OrderService orderService;

@Autowired
private BuyerService buyerService;

@PostMapping("/create")
public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
Expand Down Expand Up @@ -61,4 +65,18 @@ public ResultVO<List<OrderDTO>> list(@RequestParam("openid") String openid,
Page<OrderDTO> orderDTOPage = orderService.findList(openid, request);
return ResultVOUtil.success(orderDTOPage.getContent());
}

@GetMapping("/detail")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId) {
OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
return ResultVOUtil.success(orderDTO);
}

@PostMapping("/cancel")
public ResultVO cancel (@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId) {
buyerService.cancelOrder(openid, orderId);
return ResultVOUtil.success();
}
}
49 changes: 49 additions & 0 deletions src/main/java/com/gxj/controller/WechatController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.gxj.controller;

import com.gxj.enums.ResultEnum;
import com.gxj.exception.SellException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

@Autowired
private WxMpService wxMpService;

@GetMapping("/authorize")
public String authorize(@RequestParam("returnUrl") String returnUrl) {
String url = "https://mytestsell.mynatapp.cc/sell/wechat/userInfo";
String redirectUrl =
wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(returnUrl));
log.info("【微信网页授权】获取code, result={}", redirectUrl);
return "redirect:" + redirectUrl;
}

@GetMapping("/userInfo")
public String userInfo(@RequestParam("code") String code,
@RequestParam("state") String returnUrl) {
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
try {
wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
} catch (WxErrorException e){
log.error("【微信网页授权】{}", e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
}
String openId = wxMpOAuth2AccessToken.getOpenId();

return "redirect:" + returnUrl + "?openid=" + openId;
}
}
25 changes: 25 additions & 0 deletions src/main/java/com/gxj/controller/WeixinController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.gxj.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {

@GetMapping("/auth")
public void auth(@RequestParam("code") String code) {
log.info("进入auth方法....");
log.info("code={}", code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx7aef45e7ab0a62e4&secret=4786ff747ab75b3e26ed59b28b72d3fb&code="
+ code + "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
log.info("response={}", response);
}
}
8 changes: 8 additions & 0 deletions src/main/java/com/gxj/dto/OrderDTO.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package com.gxj.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.gxj.dataobject.OrderDetail;
import com.gxj.utils.serializer.Date2LongSerializer;
import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Data
//@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDTO {
private String orderId;

Expand All @@ -33,9 +39,11 @@ public class OrderDTO {
private Integer payStatus;

/** 创建时间. */
@JsonSerialize(using = Date2LongSerializer.class)
private Date createTime;

/** 更新时间. */
@JsonSerialize(using = Date2LongSerializer.class)
private Date updateTime;

private List<OrderDetail> orderDetailList;
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/gxj/enums/ResultEnum.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ public enum ResultEnum {
ORDER_UPDATE_FAIL(15, "订单更新失败"),
ORDER_DETAIL_EMPTY(16, "订单详情为空"),
ORDER_PAY_STATUS_ERROR(17, "订单支付状态不正确"),
CART_EMPTY(18, "购物车为空")
CART_EMPTY(18, "购物车为空"),
ORDER_OWNER_ERROR(19, "该订单不属于当前用户"),
WECHAT_MP_ERROR(20, "微信公众账号方面错误")
;
private Integer code;
private String message;
Expand Down
9 changes: 9 additions & 0 deletions src/main/java/com/gxj/service/BuyerService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.gxj.service;

import com.gxj.dto.OrderDTO;

public interface BuyerService {

OrderDTO findOrderOne(String openid, String orderId);
OrderDTO cancelOrder(String openid, String orderId);
}
51 changes: 51 additions & 0 deletions src/main/java/com/gxj/service/impl/BuyerServiceImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.gxj.service.impl;

import com.gxj.dto.OrderDTO;
import com.gxj.enums.ResultEnum;
import com.gxj.exception.SellException;
import com.gxj.service.BuyerService;
import com.gxj.service.OrderService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

@Autowired
private OrderService orderService;

@Override
public OrderDTO findOrderOne(String openid, String orderId) {
return checkOrderOwner(openid, orderId);
}

@Override
public OrderDTO cancelOrder(String openid, String orderId) {
OrderDTO orderDTO = checkOrderOwner(openid, orderId);
if (orderDTO == null) {
log.error("【取消订单】查不到该订单, orderId={}", orderId);
throw new SellException(ResultEnum.ORDER_NOT_EXIST);
}
return orderService.cancel(orderDTO);
}

private OrderDTO checkOrderOwner(String openid, String orderId) {
if (StringUtils.isNullOrEmpty(openid)) {
log.error("【查询订单详情】openid为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
if (StringUtils.isNullOrEmpty(orderId)) {
log.error("【查询订单详情】orderId为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
OrderDTO orderDTO = orderService.findOne(orderId);
if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
log.error("【查询订单详情】订单的openid不一致, openid={}, orderDTO={}", openid, orderDTO);
throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
}
return orderDTO;
}
}
16 changes: 16 additions & 0 deletions src/main/java/com/gxj/utils/serializer/Date2LongSerializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.gxj.utils.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Date;

public class Date2LongSerializer extends JsonSerializer<Date> {

@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(date.getTime() / 1000);
}
}
10 changes: 10 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ spring:
url: jdbc:mysql://192.168.199.190/sell?characterEncoding=utf-8&useSSL=false
jpa:
show-sql: true
jackson:
default-property-inclusion: non_null

server:
servlet:
Expand All @@ -22,3 +24,11 @@ server:
include-message: always
include-binding-errors: always
include-exception: true

wechat:
mpAppId: wx7aef45e7ab0a62e4
mpAppSecret: 4786ff747ab75b3e26ed59b28b72d3fb




Loading

0 comments on commit 40eb691

Please sign in to comment.