龙空技术网

35.spring boot 小程序不需要授权登录

海椰人 247

前言:

当前兄弟们对“weixinjavaminiapp”大致比较看重,同学们都需要了解一些“weixinjavaminiapp”的相关知识。那么小编在网络上网罗了一些对于“weixinjavaminiapp””的相关文章,希望我们能喜欢,兄弟们快快来学习一下吧!

不需要授权的登录,只能获取到openId,有openId便可从数据库中关联到平台中的用户。

引入包:

     <!--微信开源封装sdk-->        <dependency>            <groupId>com.github.binarywang</groupId>            <artifactId>weixin-java-miniapp</artifactId>            <version>3.6.0</version>        </dependency>

WxMaConfiguration:

package com.haiyeren.config;import cn.binarywang.wx.miniapp.api.WxMaService;import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;import me.chanjar.weixin.common.error.WxErrorException;import java.io.File;import java.util.Map;/** * @author <a href=";>Binary Wang</a> */public class WxMaConfiguration {    private static Map<String, WxMaMessageRouter> routers = Maps.newHashMap();    private static Map<String, WxMaService> maServices = Maps.newHashMap();    public static WxMaService getMaService(String appid, String secret) {        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();        config.setAppid(appid);        config.setSecret(secret);        config.setToken("");        config.setAesKey("");        config.setMsgDataFormat("JSON");        WxMaService service = new WxMaServiceImpl();        service.setWxMaConfig(config);        return service;    }    public static WxMaMessageRouter getRouter(String appid) {        return routers.get(appid);    }    private WxMaMessageRouter newRouter(WxMaService service) {        final WxMaMessageRouter router = new WxMaMessageRouter(service);        router            .rule().handler(logHandler).next()            .rule().async(false).content("模板").handler(templateMsgHandler).end()            .rule().async(false).content("文本").handler(textHandler).end()            .rule().async(false).content("图片").handler(picHandler).end()            .rule().async(false).content("二维码").handler(qrcodeHandler).end();        return router;    }    private final WxMaMessageHandler templateMsgHandler = (wxMessage, context, service, sessionManager) -> {        service.getMsgService().sendTemplateMsg(WxMaTemplateMessage.builder()            .templateId("此处更换为自己的模板id")            .formId("自己替换可用的formid")            .data(Lists.newArrayList(                new WxMaTemplateData("keyword1", "339208499", "#173177")))            .toUser(wxMessage.getFromUser())            .build());        return null;    };    private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {        System.out.println("收到消息:" + wxMessage.toString());        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())            .toUser(wxMessage.getFromUser()).build());        return null;    };    private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")            .toUser(wxMessage.getFromUser()).build());        return null;    };    private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {        try {            WxMediaUploadResult uploadResult = service.getMediaService()                .uploadMedia("image", "png",                    ClassLoader.getSystemResourceAsStream("tmp.png"));            service.getMsgService().sendKefuMsg(                WxMaKefuMessage                    .newImageBuilder()                    .mediaId(uploadResult.getMediaId())                    .toUser(wxMessage.getFromUser())                    .build());        } catch (WxErrorException e) {            e.printStackTrace();        }        return null;    };    private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {        try {            final File file = service.getQrcodeService().createQrcode("123", 430);            WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);            service.getMsgService().sendKefuMsg(                WxMaKefuMessage                    .newImageBuilder()                    .mediaId(uploadResult.getMediaId())                    .toUser(wxMessage.getFromUser())                    .build());        } catch (WxErrorException e) {            e.printStackTrace();        }        return null;    };}

后台代码(xcxAppId和xcxSecret需要自己填):

 @ApiOperation(value = "小程序登录,只获取openid")    @PostMapping("loginByWeixin")    public ResultVo<WeixinLoginVo> loginByWeixin(String code) throws Exception {        ResultVo<WeixinLoginVo> result = new ResultVo<>();        WeixinLoginVo weixinLoginVo = new WeixinLoginVo();        //获取openid        //通过自定义工具类组合出小程序需要的登录凭证 code        String xcxAppId = "xxxx";        String xcxSecret = "xxxx";        //其他商城的小程序        final WxMaService wxService = WxMaConfiguration.getMaService(xcxAppId, xcxSecret);        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);        String  openid = session.getOpenid();        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();        queryWrapper.lambda().eq(UserEntity::getOpenid,openid);        UserEntity user=userService.getOne(queryWrapper);        if(null==user)        {            user=new UserEntity();            user.setOpenid(openid);           userService.save(user);        }        String tokenId = tokenService.getTokenId(user.getId(), "");        weixinLoginVo.setOpenid(openid);        weixinLoginVo.setOpenid(tokenId);        result.setData(weixinLoginVo);        return result;    }

WeixinLoginVo:

package com.haiyeren.entity.vo;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;@ApiModel("小程序登录返回")@Datapublic class WeixinLoginVo {    @ApiModelProperty(value="登录令牌")    private String token;    @ApiModelProperty(value="openid")    private String openid;}

小程序端登录代码:

  login: function () {    var that = this;    wx.login({      success: res => {        // 发送 res.code 到后台换取 openId, sessionKey, unionId        console.log("res.code:", res.code)        if (res.code) {          //发起网络请求          wx.request({            url:  '',            data: {              code: res.code                   },            header: {              'content-type': 'application/x-www-form-urlencoded'            },            method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT            success: function (res) {              console.log('登陆回调', res);              if (res.data.status == 1) {                              that.globalData.token = res.data.data.token;                             that.globalData.openid = res.data.data.openid;                                       }              if (res.data.status != 1) {                // 登录错误             //   wx.hideLoading();                wx.showModal({                  title: '提示',                  content: '无法登录,请重试',                  showCancel: false                })                return;              }            },            fail: function (failRes) {              //用户未授权会调用失败,调用失败就进这里            //  wx.hideLoading();            }          })        } else {          console.log('获取用户登录态失败!' + res.errMsg)        }      }    })  }

标签: #weixinjavaminiapp