微信小程序登录+后台获取oppenId+微信的授权

微信小程序登录+后台获取oppenId+微信的授权


微信小程序登录

 wx.login({
        success(res) {
          wx.request({
            url: '',  //填入你自己的请求url
            method:"",
            data:{
              code:res.code,  //调用wx.login()获取的临时登录凭证code
            },
            success(res) {  //返回成功后输出
              console.log(res);
            }
         })

后台获取oppenId

  1. 需要准备的POM

       <!-- JSONObject对象依赖的jar包 -->
            <dependency>
                <groupId>commons-beanutils</groupId>
                <artifactId>commons-beanutils</artifactId>
                <version>1.9.3</version>
            </dependency>
            <dependency>
                <groupId>commons-collections</groupId>
                <artifactId>commons-collections</artifactId>
                <version>3.2.1</version>
            </dependency>
            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>2.6</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.1.1</version>
            </dependency>
            <dependency>
                <groupId>net.sf.ezmorph</groupId>
                <artifactId>ezmorph</artifactId>
                <version>1.0.6</version>
            </dependency>
            <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.2.3</version>
                <classifier>jdk15</classifier><!-- 指定jdk版本 -->
            </dependency>
            <!-- Json依赖架包下载 -->
    
  2. 准备工具类

    /**
     * 微信工具类
     */
    public class WeChatUtil {
    
        //服务器请求微信接口
        public static String httpRequest(String requestUrl,String requestMethod,String output){
            try{
                URL url = new URL(requestUrl);
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                if(null != output){
                    OutputStream outputStream = connection.getOutputStream();
                    outputStream.write(output.getBytes("utf-8"));
                    outputStream.close();
                }
                // 从输入流读取返回内容
                InputStream inputStream = connection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuffer buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null){
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                inputStream = null;
                connection.disconnect();
                return buffer.toString();
            }catch(Exception e){
                e.printStackTrace();
            }
            return "";
        }
    }
    
  3. 进行数据的接收和获取oppid和session_key

    @RestController
    public class UserLoginController {
       private static String appid="";  //微信小程序oppenid
       private static String secret="";  //微信小程序appSecret
    
    
        @PostMapping("/wx/user/login")  
        private String userLogin(@RequestBody UserParam param){   
            
            //请求的url拼接
            String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+param.getCode()+"&grant_type=authorization_code";
            
            
            String str= WeChatUtil.httpRequest(url,"GET",null); //服务器请求微信接口
    
    
            // 转成Json对象 获取openid
            JSONObject jsonObject = JSONObject.fromObject(str);
    
            // 获取oppenid
            String openid = jsonObject.get("openid").toString();
            // 获取sessionkey
            String sessionKey = jsonObject.get("session_key").toString();
            System.out.println(openid);//在控制台打印oppenid
            System.out.println(sessionKey);//在控制台打印sessionkey
            return "0";
        }
    }
    

微信授权

 <button class='authBtn' type='primary' open-type='getUserInfo' bindgetuserinfo='bindGetUserInfo'>授权登录</button>
bindGetUserInfo:function(res){
    console.log(res)
    var platUserInfoMap=res.detail.userInfo;//获取用户信息
    if(res.detail.userInfo){
      var that=this;
      wx.showModal({  //授权成功后进行跳转
        title: '',
        content: '欢迎使用!',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.reLaunch({
              url: '../home/home'
            })
          }
        }
      })
    }else{
      wx.showModal({  //授权失败后进行跳转
        title: '警告',
        content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功,不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
    wx.setStorageSync("userinfo", platUserInfoMap)  //将用户的信息存入本地存储
  },

微信授权展示

  • 点击授权登录后的效果,这个效果是微信自带的

在这里插入图片描述

  • 点击拒绝按钮后的效果

在这里插入图片描述

  • 点击成功按钮后的效果

在这里插入图片描述

工欲善其事,必先利其器

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值