微信公众号开发

小程序授权登陆

本文主要是介绍小程序授权登陆,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

小程序授权登陆

    • wxml:
    • js
    • 后端
    • 效果

wxml:

<view>
  <block wx:if="{{!hasUserInfo}}">
    <view style=" width: 98%;height: 640px;margin: 0 auto;">
      <view style="height: 350px;">
        <image src="/static/logo.png" style="width: 150px;height: 150px;margin: 150px 0 100px 29.8%"></image>
      </view>
      <view>
        <button style="background-color: #12BAF8;color: #ffffff;width: 98%;" bindtap="getUserProfile">微信授权/登录</button>
      </view>
    </view>
    <button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 申请获取以下权限</button>
  </block>
  <block wx:else>
   <view>登录成功了</view>
  </block>
</view>

js

getUserProfile(e) {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        app.globalData.userInfo = res.userInfo;
        this.login(res);
      },
    })
  },
  login: function (e) {
    var that = this;
    wx.login({
      success: function (res) {
        wx.request({
          url: app.path + 'wxapi/user/getcode',
          method: 'post',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            code: res.code,
            userInfo: JSON.stringify(e.userInfo)
          },
          success: function (res) {
            console.log("token:" + res.data)
            that.setData({
              hasUserInfo: true,
            })
            //给全局变量赋值
            app.globalData.token = res.data;
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        })
      }
    })
  }

后端

@RequestMapping("/user/getcode")
@ResponseBody
public String getcode(String code,String userInfo) throws JSONException {
    //String转map
    HashMap hashMap = JSON.parseObject(userInfo,HashMap.class);
    String Appid = "";
    String AppSecret = "";
    String getopenid_url = "https://api.weixin.qq.com/sns/jscode2session";
    String param = "appid=" + Appid + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
    //向微信服务器发送get请求获取openIdStr
    String openIdStr = this.sendGet(getopenid_url, param);
    JSONObject jsonObj = new JSONObject(openIdStr);
    //openid
    String openid = jsonObj.getString("openid");
    String session_key = jsonObj.getString("session_key");

    //通过openid查询用户,不存在添加一个
    User u = userService.getopenid(openid);
    Map<String, Object> mmap = new HashMap<>();
    if (u != null) {
        mmap.put("user", u);
    } else {
        User uu = new User();
        uu.setSessionkey(session_key);
        uu.setOpenid(openid);
        uu.setNickname(hashMap.get("nickName").toString());
        //创建一个为0的密码
        String salt = ShiroUtil.getRandomSalt();
        String encrypt = ShiroUtil.encrypt("0", salt);
        uu.setPassword(encrypt);
        uu.setSalt(salt);
        uu.setPicture(hashMap.get("avatarUrl").toString());
        uu.setSex(Byte.valueOf(hashMap.get("gender").toString()));
        uu.setCreateDate(new Date());
        uu.setSalt("1");
        userService.save(uu);
        mmap.put("user", uu);
    }
    String token = openid + "," + code + "," + session_key;
    mmap.put("token", token);
    System.out.println("点击登录返回的map:"+mmap);
    return token;
}

/**
 * 向指定URL发送GET方法的请求
 *
 * @param url   发送请求的URL
 * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 * @return URL 所代表远程资源的响应结果
 */

public static String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        // 打开和URL之间的连接
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> map = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : map.keySet()) {
            System.out.println(key + "--->" + map.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("发送GET请求出现异常!" + e);
        e.printStackTrace();
    }
    // 使用finally块来关闭输入流
    finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return result;
}

效果

在这里插入图片描述
在这里插入图片描述

大佬勿喷,欢迎提意见建议评论!!!!

这篇关于小程序授权登陆的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!