微信小程序通过openid或unionid自动登录

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




环境:java springboot2 hibernate5

实现效果:登录时候绑定微信openid或unionid,之后加载页面自动登录,不用再输账号密码

其他文档参考:

1.https://www.idaobin.com/archives/2294.html

2.https://www.idaobin.com/archives/2263.html

3.https://www.idaobin.com/archives/2302.html

4.https://www.idaobin.com/archives/2246.html

数据库设计:

app.js

  globalData: {
    userInfo: null,
    url: "http://localhost:8080/"
  }

request.js

var app = getApp();
var host = app.globalData.url;

function sendPost(url, postData, doSuccess, doFail) {
  wx.request({
    url: host + url,
    header: {
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    data: postData,
    method: 'POST',
    success: function (res) {
      //参数值为res.data,直接将返回的数据传入
      doSuccess(res.data);
    },
    fail: function () {
      doFail();
    },
  })
}

function sendJsonPost(url, para, op, doSuccess, doFail) {
  wx.request({
    url: host + url,
    header: {
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    data: {
      op: op,
      para
    },
    method: 'POST',
    success: function (res) {
      //参数值为res.data,直接将返回的数据传入
      doSuccess(res.data);
    },
    fail: function () {
      doFail();
    },
  })
}

function sendGet(url, doSuccess, doFail) {
  wx.request({
    url: host + url,
    header: {
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    method: 'GET',
    success: function (res) {
      doSuccess(res.data);
    },
    fail: function () {
      doFail();
    },
  })
}

module.exports.sendPost = sendPost;
module.exports.sendJsonPost = sendJsonPost;
module.exports.sendGet = sendGet;

login.wxml

 <input placeholder="请输入账号" bindinput ="userNameInput" class="input" placeholder-class="placeholder-class" name="txtname" value="" focus='true' maxlength='16' />
    </view>
    <view class='test'>
      <input placeholder="请输入密码" bindinput ="passWdInput" class="input" placeholder-class="placeholder-class" name="txtpwd" password='true' />
    </view>
    <button bindtap="showMsg" class="button">登录</button>

login.js

var call = require("../../utils/request.js");
// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:"",
    pwd:""
  },

  userNameInput: function (e) {
    this.data.id = e.detail.value;
  },
  passWdInput: function (e) {
    this.data.pwd = e.detail.value;
  },

  login:function(e){
    call.sendPost('login.do', this.data, this.loginsuccess, this.loginfail);
  },
  loginsuccess: function (data) {
    if (data) {
      wx.switchTab({
        url: '../index/index'
      })
    }
    else {
      wx.showToast({
        title: '账号或密码错误',
        icon: 'none',
        duration: 2000
      })
    }
  },
  loginfail: function () {
    wx.showToast({
      title: '请求失败',
      icon: 'none',
      duration: 2000
    })
  },

  loginbind: function (e) {
    var that=this;
    wx.login({
      success: function (r) {
        var code = r.code;
        if (code) {
          wx.getUserInfo({
            success: function (res) {
              that.data = { encryptedData: res.encryptedData, iv: res.iv, code: code, id: that.data.id, pwd: that.data.pwd };
              call.sendPost('loginbind.do', that.data, that.loginbindsuccess, that.loginbindfail);
            },
            fail: function () {
              wx.showModal({
                title: '警告',
                content: '尚未进行授权,请点击确定跳转到授权页面进行授权。',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: 'author',
                    })
                  }
                  else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }
              })
            }
          });
        }
      },
      fail: function () {
        console.log("错误");
      }
    })
  },
  loginbindsuccess: function (data) {
    if (data) {
      wx.switchTab({
        url: '../index/index'
      })
    }
    else {
      wx.showToast({
        title: '账号或密码错误',
        icon: 'none',
        duration: 2000
      })
    }
  },
  loginbindfail: function () {
    wx.showToast({
      title: '请求失败',
      icon: 'none',
      duration: 2000
    })
  },

  showMsg:function(e){
    var that=this;
    wx.showModal({
      title: '授权',
      content: '是否绑定当前微信。',
      success: function (res) {
        if (res.confirm) {
          that.loginbind(e);
        }
        else {
          that.login(e);
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.login({
      success: function (r) {
        var code = r.code;
        if (code) {
          wx.getUserInfo({
            success: function (res) {
              that.data = { encryptedData: res.encryptedData, iv: res.iv, code: code };
              call.sendPost('getOpenid.do', that.data, that.loadsuccess, that.loadfail);
            },
            fail: function () {
              wx.showModal({
                title: '警告',
                content: '尚未进行授权,请点击确定跳转到授权页面进行授权。',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: 'author',
                    })
                  }
                  else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }
              })
            }
          });
        }
      },
      fail: function () {
        console.log("错误");
      }
    })
  },
  loadsuccess: function (data) {
    if (data) {
      wx.switchTab({ //跳转到底部导航栏tabbar
        url: '../index/index'
      })
    }
    else {
      wx.showToast({
        title: '未绑定',
        icon: 'none',
        duration: 2000
      })
    }
  },
  loadfail: function () {
    wx.showToast({
      title: '请求失败',
      icon: 'none',
      duration: 2000
    })
  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

author.wxml

<!--pages/login/author.wxml-->
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权</button>

author.js

// pages/login/author.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  bindGetUserInfo: function (e) {
    var that = this;
    var userinfo = e.detail.userInfo;
    if (userinfo == null) {
      wx.showToast({
        title: '授权失败',
        icon: 'none',
        duration: 2000
      })
    }
    else {
      //返回刚才的页面
      wx.navigateTo({
        url:"login"
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

java 后台

dal:

public class Login {
    HibernateUtils hib=new HibernateUtils();

    //判断userid
    public boolean getUserIdPwd(String id,String pwd){
        String sql="select count(*) from T_User where id=?0 and pwd=?1";
        Object[] para = {id,pwd};
        int row=Integer.parseInt(hib.selectCount(sql,para).toString());
        if(row>0){
            return true;
        }
        return false;
    }

    //写入openid
    public boolean setOpenid(String openid,String id){
        String sql="update T_User set openid=? where id=?";
        Object[] para = {openid,id};
        boolean bl=hib.update(sql,para);
        return bl;
    }

    //判断openid
    public boolean getOpenid(String openid){
        String sql="select count(*) from T_User where openid=?0";
        Object[] para = {openid};
        int row=Integer.parseInt(hib.selectCount(sql,para).toString());
        if(row>0){
            return true;
        }
        return false;
    }
}

controller:

@RestController
public class ActionController implements HttpSessionListener {
    Login login=new Login();
    WeChat weChat=new WeChat();

    //登录
    @RequestMapping("/login.do")
    public boolean getUserIdPwd(String id, String pwd, HttpServletRequest request){
        boolean bl=login.getUserIdPwd(id,pwd);
        if(bl){
            HttpSession session=request.getSession();
            session.setAttribute("id", id);
        }
        return bl;
    }

    @RequestMapping("/loginbind.do")
    public boolean getUserIdPwdBind(String id, String pwd,String encryptedData, String iv, String code, HttpServletRequest request){
        boolean bl=login.getUserIdPwd(id,pwd);
        if(bl){
            HttpSession session=request.getSession();
            session.setAttribute("id", id);
            String openid=getUnionId(encryptedData,iv,code);
            boolean bl2 = login.setOpenid(openid,id);
            bl=bl2;
        }
        return bl;
    }

    @RequestMapping("/getOpenid.do")
    public boolean getOpenid(String encryptedData, String iv, String code){
        String openid=getUnionId(encryptedData,iv,code);
        return login.getOpenid(openid);
    }

    // 微信小程序ID
    String appid = "xxxx";
    // 微信小程序秘钥
    String secret = "xxxxxxxx";
    public String getUnionId(String encryptedData, String iv, String code)  {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        try{
            String str = WeChatUtil.httpRequest(url, "POST", null);
            String session_key= JacksonUtil.getFileValue(str,"session_key").toString();
            String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            String openid= JacksonUtil.getFileValue(result,"openId").toString();
            return openid;
        }
        catch (Exception ex){
            return null;
        }
    }

}

原文链接:https://www.idaobin.com/archives/2304.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

59 ÷ = 59