Browse Source

'开发永天综合智慧云(获取code码/获取openid/跳转首页权限/登录)接口'

james 11 months ago
parent
commit
d565a4dc8a

+ 5 - 0
service-iot/service-iot-biz/pom.xml

@@ -66,6 +66,11 @@
             <version>0.0.1</version>
             <scope>compile</scope>
         </dependency>
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-mp</artifactId>
+            <version>4.3.0</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 17 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/RuoYiSystemApplication.java

@@ -2,7 +2,12 @@ package com.usky.iot;
 
 
 
+import com.usky.iot.constant.constant;
 import io.swagger.annotations.SwaggerDefinition;
+import lombok.val;
+import me.chanjar.weixin.mp.api.WxMpService;
+import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
+import me.chanjar.weixin.mp.config.impl.WxMpMapConfigImpl;
 import org.mybatis.spring.annotation.MapperScan;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -10,6 +15,7 @@ import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cloud.openfeign.EnableFeignClients;
 import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.core.env.Environment;
 
@@ -31,6 +37,17 @@ public class RuoYiSystemApplication
 {
     private static final Logger LOGGER = LoggerFactory.getLogger(RuoYiSystemApplication.class);
 
+    @Bean
+    public WxMpService wxMpService(){
+        WxMpMapConfigImpl wxMpMapConfig = new WxMpMapConfigImpl();
+        wxMpMapConfig.setAppId(constant.WE_CHAT_APP_ID);
+        wxMpMapConfig.setSecret(constant.WE_CHAT_SECRET);
+        val wxMpService = new WxMpServiceImpl();
+        wxMpService.setWxMpConfigStorage(wxMpMapConfig);
+
+        return wxMpService;
+    }
+
     public static void main(String[] args) throws UnknownHostException {
         ConfigurableApplicationContext application = SpringApplication.run(RuoYiSystemApplication.class, args);
         Environment env = application.getEnvironment();

+ 27 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/constant/constant.java

@@ -0,0 +1,27 @@
+package com.usky.iot.constant;
+
+public class constant {
+    // 微信公众号的 app_id
+    public static final String WE_CHAT_APP_ID = "wx24286e0c45f8da1c";
+    // 微信公众号的 secret
+    public static final String WE_CHAT_SECRET = "d605d3efaaad559a8e6a327870b48ce8";
+    // 微信公众号的 access_token
+    public static final String WE_CHAT_ACCESS_TOKEN = "**********";
+    // 微信公众号code获取地址
+    public static final String WE_CHAT_CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect";
+    // 回调地址,获取open_id
+    public static final String WE_CHAT_CALL_BACK_DOMAIN_URL = "http://localhost:9887/weChat/getWeChatOpenId";
+    // 微信公众号的token获取地址
+    public static final String WE_CHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
+    // 微信公众号消息推送地址
+    public static final String WE_CHAT_REQUEST_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
+    // 微信公众号推送消息模板id
+    public static final String WE_CHAT_TEMPLATE_ID = "**********";
+    // 微信公众号的消息回调地址(这儿可根据业务需求自定义动作,可选)
+    public static final String WE_CHAT_CUSTOMER_CALL_URL = "https://***.***.***.***/***/***/accountInfo?keyword=%s";
+    // 微信公众号的主题颜色
+    public static final String WE_CHAT_TOP_COLOR = "#A349A4";
+    // 微信公众号微信用户授权地址
+    public static final String WE_CHAT_AUTHORIZATION_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
+
+}

+ 21 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/controller/web/SysWxOpuserController.java

@@ -0,0 +1,21 @@
+package com.usky.iot.controller.web;
+
+
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import org.springframework.stereotype.Controller;
+
+/**
+ * <p>
+ * 微信用户openid信息表 前端控制器
+ * </p>
+ *
+ * @author han
+ * @since 2024-04-03
+ */
+@Controller
+@RequestMapping("/sysWxOpuser")
+public class SysWxOpuserController {
+
+}
+

+ 301 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/controller/web/WeChatController.java

@@ -0,0 +1,301 @@
+package com.usky.iot.controller.web;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.usky.common.core.bean.ApiResult;
+import com.usky.common.core.exception.BusinessException;
+import com.usky.common.redis.core.RedisHelper;
+import com.usky.iot.constant.constant;
+import com.usky.iot.domain.SysWxOpuser;
+import com.usky.iot.service.SysWxOpuserService;
+import com.usky.iot.service.vo.SignUpRequestVO;
+import ma.glasnost.orika.impl.util.StringUtil;
+import me.chanjar.weixin.common.api.WxConsts;
+import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
+import me.chanjar.weixin.mp.api.WxMpService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.ExitCodeEvent;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.view.RedirectView;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.time.LocalDateTime;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+@RestController
+@RequestMapping("weChat")
+public class WeChatController {
+    @Autowired
+    private WxMpService wxMpService;
+    @Resource
+    private HttpServletRequest request;
+    @Resource
+    private HttpServletResponse response;
+    @Autowired
+    private SysWxOpuserService sysWxOpuserService;
+    @Autowired
+    private RedisHelper redisHelper;
+
+    /**
+     * 调用的第一个接口,获取微信公众号CODE,获取openid
+     */
+    @GetMapping("/getFirst1")
+    public void getFirst1(){
+        String http = "https://";
+        String code = request.getParameter("code");
+        String userAgent = request.getHeader("User-Agent");
+
+        if(userAgent.contains("MicroMessenger")){ //wx
+            request.getSession().setAttribute("type","wx");
+            if(StringUtils.isBlank(code)){
+                String url = URLDecoder.decode(http+request.getServerName()+request.getRequestURI());
+                String sendUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+constant.WE_CHAT_APP_ID+"&redirect_uri="+url+"&response_type=code&scope=snsapi_base&state=abc123#wechat_redirect";
+                try{
+                    System.out.println("sendUrl: "+sendUrl);
+                    response.sendRedirect(sendUrl);
+                }catch (IOException e){
+                    throw new BusinessException(e.getMessage());
+                }
+            }else{
+                System.out.println("code:  "+code);
+                try {
+                    WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
+
+                    String openid = wxOAuth2AccessToken.getOpenId();
+                    String access_token = wxOAuth2AccessToken.getAccessToken();
+                    System.out.println("openid:  "+openid);
+                    request.getSession().setAttribute("openid",openid);
+                    LambdaQueryWrapper<SysWxOpuser> queryWrapper = Wrappers.lambdaQuery();
+                    queryWrapper.select(SysWxOpuser::getPhone)
+                            .eq(SysWxOpuser::getStatus,1)
+                            .eq(SysWxOpuser::getOpenid,openid);
+                    SysWxOpuser one = sysWxOpuserService.getOne(queryWrapper);
+                    if(one != null){
+                        request.getSession().setAttribute("phone",one.getPhone());
+                    }
+//
+//                    response.sendRedirect("https://qhome.usky.cn/work/index.html#/pages/login/login?flag=true");
+                } catch (Exception e) {
+                    throw new BusinessException(e.getMessage());
+                }
+            }
+
+        }else{ //app
+            request.getSession().setAttribute("type","app");
+            request.getSession().setAttribute("app_token","");
+            try{
+                response.sendRedirect("");
+            }catch (IOException e){
+                throw new BusinessException(e.getMessage());
+            }
+
+        }
+    }
+
+    /**
+     * 跳转首页权限
+     */
+    @GetMapping("getPageAuthorization")
+    public void getPageAuthorization(){
+        String http = "https://";
+        String code = request.getParameter("code");
+        String userAgent = request.getHeader("User-Agent");
+        if(null != request.getSession().getAttribute("app_token") && (null != request.getSession().getAttribute("phone"))){
+            LambdaQueryWrapper<SysWxOpuser> queryWrapper = Wrappers.lambdaQuery();
+            queryWrapper.eq(SysWxOpuser::getPhone,request.getSession().getAttribute("phone"))
+                    .eq(SysWxOpuser::getStatus,1)
+                    .eq(SysWxOpuser::getType,"app");
+            SysWxOpuser one = sysWxOpuserService.getOne(queryWrapper);
+            if(one != null){
+                String sendUrl = "https://iot.usky.cn/work/#/?op="+one.getOpenid();
+                try{
+                    System.out.println("sendUrl: "+sendUrl);
+                    response.sendRedirect(sendUrl);
+                }catch (IOException e){
+                    throw new BusinessException(e.getMessage());
+                }
+            }
+
+        }else{
+            if(!userAgent.contains("MicroMessenger")){
+                try{
+                    response.sendRedirect("https://iot.usky.cn/work/index.html#/pages/login/login");
+                }catch (IOException e){
+                    throw new BusinessException(e.getMessage());
+                }
+
+            }else{
+                if((null == request.getSession().getAttribute("openid")) && (StringUtils.isBlank(request.getSession().getAttribute("openid").toString()))){
+                    if(StringUtils.isBlank(code)){
+                        String url = URLDecoder.decode(http+request.getServerName()+request.getRequestURI());
+                        String sendUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+constant.WE_CHAT_APP_ID+"&redirect_uri="+url+"&response_type=code&scope=snsapi_base&state=abc123#wechat_redirect";
+                        try{
+                            System.out.println("sendUrl: "+sendUrl);
+                            response.sendRedirect(sendUrl);
+                        }catch (IOException e){
+                            throw new BusinessException(e.getMessage());
+                        }
+                    }else{
+                        System.out.println("code:  "+code);
+                        try {
+                            WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
+
+                            String openid = wxOAuth2AccessToken.getOpenId();
+                            String access_token = wxOAuth2AccessToken.getAccessToken();
+                            System.out.println("openid:  "+openid);
+                            request.getSession().setAttribute("openid",openid);
+                            LambdaQueryWrapper<SysWxOpuser> queryWrapper = Wrappers.lambdaQuery();
+                            queryWrapper.eq(SysWxOpuser::getType,"wx")
+                                    .eq(SysWxOpuser::getStatus,1)
+                                    .eq(SysWxOpuser::getOpenid,openid);
+                            SysWxOpuser one = sysWxOpuserService.getOne(queryWrapper);
+                            if(one != null){
+                                request.getSession().setAttribute("phone",one.getPhone());
+
+                                String sendUrl = "https://iot.usky.cn/work/#/?op="+one.getOpenid();
+                                response.sendRedirect(sendUrl);
+                            }else{
+                                request.getSession().removeAttribute("openid");
+                                request.getSession().removeAttribute("phone");
+
+                                response.sendRedirect("https://iot.usky.cn/work/index.html#/pages/login/login");
+                            }
+
+
+                        } catch (Exception e) {
+                            throw new BusinessException(e.getMessage());
+                        }
+                    }
+                }else{
+                    try{
+                        LambdaQueryWrapper<SysWxOpuser> queryWrapper = Wrappers.lambdaQuery();
+                        queryWrapper.eq(SysWxOpuser::getType,"wx")
+                                .eq(SysWxOpuser::getStatus,1)
+                                .eq(SysWxOpuser::getOpenid,request.getSession().getAttribute("openid"));
+                        SysWxOpuser one = sysWxOpuserService.getOne(queryWrapper);
+                        if(one != null){
+                            request.getSession().setAttribute("phone",one.getPhone());
+                            String sendUrl = "https://iot.usky.cn/work/#/?op="+one.getOpenid();
+                            response.sendRedirect(sendUrl);
+                        }else{
+                            request.getSession().removeAttribute("openid");
+                            request.getSession().removeAttribute("phone");
+
+                            response.sendRedirect("https://iot.usky.cn/work/index.html#/pages/login/login");
+                        }
+                    }catch (IOException e){
+                        throw new BusinessException(e.getMessage());
+                    }
+
+                }
+            }
+        }
+
+    }
+
+
+    /**
+     * 登录并注册
+     */
+    @PostMapping("signUp")
+    public Map<String,Object> signUp(@RequestBody SignUpRequestVO requestVO){
+        String phone = requestVO.getPhone();
+        String verify = requestVO.getVerify();
+        Map<String,Object> map = new HashMap<>();
+
+        //手机验证码登录
+        if (StringUtils.isBlank(phone)) {
+            throw new BusinessException("手机号不能为空");
+        }
+        if (StringUtils.isBlank(verify)) {
+            throw new BusinessException("验证码不能为空");
+        }
+        if (!verify.equals(redisHelper.get(phone))) {
+            throw new BusinessException("验证码错误");
+        }
+
+        LambdaQueryWrapper<SysWxOpuser> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.eq(SysWxOpuser::getPhone,phone)
+                .eq(SysWxOpuser::getType,request.getSession().getAttribute("type"));
+        List<SysWxOpuser> list = sysWxOpuserService.list(queryWrapper);
+        if(CollectionUtils.isEmpty(list)){
+            SysWxOpuser one = new SysWxOpuser();
+            one.setPhone(phone);
+            if(request.getSession().getAttribute("type") == "app"){
+                one.setOpenid(request.getSession().getAttribute("app_token").toString());
+            }else{
+                one.setOpenid(request.getSession().getAttribute("openid").toString());
+            }
+            one.setType(request.getSession().getAttribute("type").toString());
+            one.setCreatedTime(LocalDateTime.now());
+            one.setStatus(1);
+
+            if(sysWxOpuserService.save(one)){
+
+            }else{
+                map.put("msg","注册失败,请重新注册");
+                map.put("flag",true);
+                return map;
+            }
+        }else {
+            request.getSession().setAttribute("openid",list.get(0).getOpenid());
+        }
+
+        request.getSession().setAttribute("phone",phone);
+
+        map.put("msg","验证成功,正在登录");
+        map.put("flag",true);
+        return map;
+    }
+
+
+
+    /**
+     * Description:[获取微信公众号的Access_Token]
+     *
+     * @return JSONResult
+     * @date 2019-05-19
+     * @author huazai
+     */
+    @GetMapping("/getWeChatAccessToken")
+    public String getWeChatAccessToken() {
+        try {
+            // 微信公众号官方获取AccessToken
+            String accessToken = wxMpService.getAccessToken();
+
+            return accessToken;
+        } catch (Exception e) {
+
+        }
+        return null;
+    }
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 63 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/domain/SysWxOpuser.java

@@ -0,0 +1,63 @@
+package com.usky.iot.domain;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import java.time.LocalDateTime;
+import java.io.Serializable;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * <p>
+ * 微信用户openid信息表
+ * </p>
+ *
+ * @author han
+ * @since 2024-04-03
+ */
+@Data
+@EqualsAndHashCode(callSuper = false)
+public class SysWxOpuser implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    /**
+     * 电话号码
+     */
+    private String phone;
+
+    /**
+     * 微信用户id
+     */
+    private String openid;
+
+    /**
+     * 类型: wx 微信,app 手机
+     */
+    private String type;
+
+    /**
+     * 注册时间
+     */
+    private LocalDateTime createdTime;
+
+    /**
+     * 状态:0.不启用 1.启用
+     */
+    private Integer status;
+
+    /**
+     * 组织机构ID
+     */
+    private Integer deptId;
+
+    /**
+     * 租户ID
+     */
+    private Integer tenantId;
+
+
+}

+ 16 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/mapper/SysWxOpuserMapper.java

@@ -0,0 +1,16 @@
+package com.usky.iot.mapper;
+
+import com.usky.iot.domain.SysWxOpuser;
+import com.usky.common.mybatis.core.CrudMapper;
+
+/**
+ * <p>
+ * 微信用户openid信息表 Mapper 接口
+ * </p>
+ *
+ * @author han
+ * @since 2024-04-03
+ */
+public interface SysWxOpuserMapper extends CrudMapper<SysWxOpuser> {
+
+}

+ 16 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/service/SysWxOpuserService.java

@@ -0,0 +1,16 @@
+package com.usky.iot.service;
+
+import com.usky.iot.domain.SysWxOpuser;
+import com.usky.common.mybatis.core.CrudService;
+
+/**
+ * <p>
+ * 微信用户openid信息表 服务类
+ * </p>
+ *
+ * @author han
+ * @since 2024-04-03
+ */
+public interface SysWxOpuserService extends CrudService<SysWxOpuser> {
+
+}

+ 20 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/service/impl/SysWxOpuserServiceImpl.java

@@ -0,0 +1,20 @@
+package com.usky.iot.service.impl;
+
+import com.usky.iot.domain.SysWxOpuser;
+import com.usky.iot.mapper.SysWxOpuserMapper;
+import com.usky.iot.service.SysWxOpuserService;
+import com.usky.common.mybatis.core.AbstractCrudService;
+import org.springframework.stereotype.Service;
+
+/**
+ * <p>
+ * 微信用户openid信息表 服务实现类
+ * </p>
+ *
+ * @author han
+ * @since 2024-04-03
+ */
+@Service
+public class SysWxOpuserServiceImpl extends AbstractCrudService<SysWxOpuserMapper, SysWxOpuser> implements SysWxOpuserService {
+
+}

+ 17 - 0
service-iot/service-iot-biz/src/main/java/com/usky/iot/service/vo/SignUpRequestVO.java

@@ -0,0 +1,17 @@
+package com.usky.iot.service.vo;
+
+import lombok.Data;
+
+@Data
+public class SignUpRequestVO {
+
+    /**
+     * 验证码
+     */
+    private String verify;
+
+    /**
+     * 手机号
+     */
+    private String phone;
+}

+ 17 - 0
service-iot/service-iot-biz/src/main/resources/mapper/iot/SysWxOpuserMapper.xml

@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.usky.iot.mapper.SysWxOpuserMapper">
+
+    <!-- 通用查询映射结果 -->
+    <resultMap id="BaseResultMap" type="com.usky.iot.domain.SysWxOpuser">
+        <id column="id" property="id" />
+        <result column="phone" property="phone" />
+        <result column="openid" property="openid" />
+        <result column="type" property="type" />
+        <result column="created_time" property="createdTime" />
+        <result column="status" property="status" />
+        <result column="dept_id" property="deptId" />
+        <result column="tenant_id" property="tenantId" />
+    </resultMap>
+
+</mapper>