二:H5登錄頁面
<template> <view class="content"> <image class="img" src="../../static/images/logo.png" mode=""></image> <form> <view class="list" style="margin-top: 80rpx;"> <input class="uni-input maininput" v-model="name" placeholder="用戶名" /> <text class="bl_icon_yonghu"></text> </view> <view class="list texttop"> <input class="uni-input maininput" type="password" v-model="password" placeholder="密碼" /> <text class="bl_icon_mima"></text> </view> <view> <button type="primary" class="buttoncolor martop" @click="formSubmit">登陸</button> </view> <view class="bottom-side-otherLogin" @click="getWeChatCode"> <text>微信登錄</text> <image src="../../static/images/wx.png"></image> </view> </form> </view></template><script> export default { data() { return { } }, onLoad() { let wxCode = uni.getStorageSync('wxCode') if(wxCode==null) { this.getWeChatCode() } }, methods: { //請(qǐng)求微信接口,用來獲取code getWeChatCode() { let local = encodeURIComponent('http://' + window.location.host + '/#/pages/wxlogin/wxlogin'); //獲取當(dāng)前頁面地址作為回調(diào)地址 let appid = '' //公眾號(hào)appid //通過微信官方接口獲取code之后,會(huì)重新刷新設(shè)置的回調(diào)地址【redirect_uri】 let code = this.getUrlCode('code') //如果沒有code 去獲取code if (code == null) { uni.setStorageSync('isLogin', 1) window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + local + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; } else { //this.checkWeChatCode(code) //通過微信官方接口獲取code之后,會(huì)重新刷新設(shè)置的回調(diào)地址【redirect_uri】 } } } }</script>
二:H5用戶同意授權(quán),獲取code

<template> <view> 微信授權(quán)登錄中... </view></template><script>export default { data() { return { openid: '', isBind: '', } }, onLoad() { let isLogin = uni.getStorageSync('isLogin') if (isLogin == 1) { let code = this.getUrlCode('code') if (code != null) { this.checkWeChatCode(code) uni.setStorageSync('wxCode', code) } } }, methods: { getUrlCode(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, '' ])[1] .replace(/\+/g, '%20')) || null }, //檢查瀏覽器地址欄中微信接口返回的 checkWeChatCode(code) { if (code) { this.getOpenidAndUserinfo(code) } }, //把code傳遞給后臺(tái)接口,靜默登錄 getOpenidAndUserinfo(code) { let that = this; uni.request({ url: that.websiteUrl + '/api/Wx/WechatLogin', method: 'GET', data: { code: code }, header: { 'content-type': 'application/x-www-form-urlencoded' //自定義請(qǐng)求頭信息 }, success: function(res) { if (res.statusCode == 200) { if (res.data.errCode == 0) { that.openid = res.data.result.Openid; that.isBind = res.data.result.IsBind; uni.setStorageSync('openid', that.openid); uni.setStorageSync('headimgurl', res.data.result.Headimgurl); //綁定到系統(tǒng)用戶表 } } }, fail: function(data) { } }) } }}</script>
三:后端獲取微信用戶信息

?
/// <summary> /// 獲取微信用戶信息/// </summary> /// <returns></returns>[HttpGet]public ApiResponse WechatLogin(string code){ try { if (!string.IsNullOrEmpty(code)) { string openid = string.Empty; string headimgurl = string.Empty; if (CacheHelper.Get(code)!=null) { openid = CacheHelper.Get(code).ToString(); } else { //根據(jù)appid,secret,code取到用戶的全部信息 Dictionary<string, object> dic = GetUserInfoByCode(AppId, AppSecret, code.Trim()); if (dic.ContainsKey("errcode")) { return BaseApiResponse.ApiError(dic["errmsg"].ToString()); } openid = dic["openid"].ToString(); headimgurl = dic["headimgurl"].ToString(); CacheHelper.Insert(code, openid); } //根據(jù)微信唯一標(biāo)識(shí)openid 去數(shù)據(jù)庫判斷是否存在 UserDao userDao = new UserDao(); UserEntity userEntity = userDao.GetByOpenid(openid); Dictionary<string, string> userDic = new Dictionary<string, string>(); if (userEntity != null) { userDic.Add("UserName", userEntity.Code); userDic.Add("PassWord", EncryptCommon.DecryptStr(userEntity.Password)); userDic.Add("Openid", openid); userDic.Add("IsBind", "1"); userDic.Add("Headimgurl", headimgurl); } else { userDic.Add("UserName", ""); userDic.Add("PassWord", ""); userDic.Add("Openid", openid); userDic.Add("IsBind", "0"); userDic.Add("Headimgurl", headimgurl); } return BaseApiResponse.ApiSuccess(userDic); } return BaseApiResponse.ApiError("code不能為空!"); } catch(Exception ex){ return BaseApiResponse.ApiError(ex.ToString()); }}
/// <summary> ///用code換取獲取用戶信息(包括非關(guān)注用戶的)(此access_token是網(wǎng)頁授權(quán)的和普通無關(guān)) /// </summary> /// <param name="Appid"></param> /// <param name="Appsecret"></param> /// <param name="Code">回調(diào)頁面帶的code參數(shù)</param> /// <returns>獲取用戶信息(json格式)</returns> public static Dictionary<string, object> GetUserInfoByCode(string Appid, string Appsecret, string Code){ //通過code換取網(wǎng)頁授權(quán)access_token JavaScriptSerializer Jss = new JavaScriptSerializer(); string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Appsecret, Code); string ReText = Tools.WebRequestPostOrGet(url, "");//post/get方法獲取信息 Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText); if (!DicText.ContainsKey("openid")) { return DicText; } else { //拉取用戶信息(需scope為 snsapi_userinfo) Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(Tools.WebRequestPostOrGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + DicText["access_token"] + "&openid=" + DicText["openid"] + "&lang=zh_CN", "")); return respDic; }}
閱讀原文:原文鏈接
該文章在 2025/1/15 10:17:20 編輯過