ruoyi管理系统+微信小程序登录解决

原料:

ruoyi管理系统项目模板(基于springboot)
微信小程序项目
阿里云服务器(有域名,有ssl证书(阿里云服务器的ssl证书可以买一个仅限一年免费的那个证书))

注意事项

1.微信小程序调用云服务器接口需要https://csdn.net这样的网页才可以,ip地址或http打头的都不行,这就需要我们购买域名和ssl证书
2.微信小程序调用登录接口时会有shiro拦截,需要用到 weixin-java-miniapp-demo基于Spring Boot构建,实现微信小程序后端开发功能,支持多个小程序。

  <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-miniapp</artifactId>
            <version>4.0.0</version>
        </dependency>

改造login方法

步骤

1.springboot项目添加ssl证书,打jar包上传到服务器运行

application.yml

http:
  port: 80
# 开发环境配置
server:
  # 服务器的HTTP端口,默认为80
  port: 443 # https默认端口号
  servlet:
    # 应用的访问路径
    context-path: /admin
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    max-threads: 800
    # Tomcat启动初始化的线程数,默认值25
    min-spare-threads: 30
  ssl:
    key-store: classpath:xxxx.pfx # 从阿里云服务器下载下来的ssl证书(tomcat版)直接放在resources文件夹下和yml在同一个文件夹下
    key-store-password: xxx # 下载证书附带的password.txt里的密码
    keyStoreType: PKCS12
wx:
  miniapp:
    configs:
      - appid: xxxx #微信小程序的appid
        secret: xxxx #微信小程序的Secret,在小程序公众平台的开发设置里找到
        token: leoisaking #微信小程序消息服务器配置的token
#        aesKey: #微信小程序消息服务器配置的EncodingAESKey
        msgDataFormat: JSON

注意80和443端口号要在阿里云服务器安全组中设置上,否则服务器会拦截拒绝访问

pom.xml

<packaging>jar</packaging>

端口号tomcat内部配置

  @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        return connector;
    }

2.微信小程序登录接口
要先把weixin-java-miniapp-demo中的相关代码复制下来



import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.framework.config.WxMaConfiguration;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;

import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ISysUserService userService;
    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public AjaxResult login(@PathVariable String appid, String code,String loginName,String password) throws WxErrorException {
        if (StringUtils.isBlank(code)) {
            return error("");
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
        this.logger.info(session.getSessionKey());
        this.logger.info(session.getOpenid());
        String openId = session.getOpenid();
        //这里将sys_user表中添加一个字符串类型openId的列
        SysUser sysUser = userService.selectUserByOpenId(openId);
        if (sysUser!=null) {
            UsernamePasswordToken token = new UsernamePasswordToken(loginName, password,true);
            Subject subject = SecurityUtils.getSubject();
            try
            {
                subject.login(token);
                return success();
            }
            catch (AuthenticationException e)
            {
                String msg = "用户或密码错误";
                if (com.ruoyi.common.utils.StringUtils.isNotEmpty(e.getMessage()))
                {
                    msg = e.getMessage();
                }
                return error(msg);
            }
        }
        return error(session.getOpenid());
    }
}

3.微信小程序登录

app = getApp();


// 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: "https://xxx.xx/wx/user/"+appId+"/login",
          data: {
            code: res.code,
            appid:app.globalData.appId,
            loginName:"xxxx",
            password:"xxxx",
          },
          success: function (res) {
            //console.log(res);
            let ret = res.data;
            console.log(res);
            app.globalData.header.cookie = res.cookies.toString();
            app.globalData.openid = ret.openid;
            that.getUser();
          },fail: function (res) {
            console.log(res);
          }
        })

      }
    })

//登录后调用接口
getUser:function(){
    
    wx.request({
      url: "https://xxxx.xx/system/user/getList",
      header:app.globalData.header,
      data: {
        loginName:"xxxx"
      },
      method:"get",
      success: function (res) {
        console.log(res);
        if (res.statusCode == 200) {
          var user = res.data[0];
          app.user = user;
        }
      },fail: function (res) {
        console.log(res);
      }
    })
  },

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值