源碼還需優化,不喜勿噴。 微信官方文檔 : https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html 前期準備: 1.微信開放平臺開發者資質認證 https://open.wei ...
源碼還需優化,不喜勿噴。
微信官方文檔 : https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
前期準備:
1.微信開放平臺開發者資質認證 https://open.weixin.qq.com/ 費用300 大概1-2天時間
2.創建網站應用,需要已備案功能變數名稱、logo等資料 大概1-2天
3.通過以後獲取AppID、AppSecret
winform 窗體 控制項 : webBrowser(載入微信介面,樣式太難調了,設置隱藏即可,用pictureBox蓋住就好) 、pictureBox(zhexiubu 載入二維碼圖片)
回調函數需格式化一下urlencode,微信要求的 地址: http://www.jsons.cn/urlencode/
以下是源碼:
//Form窗體載入
private void LoginForm_Load(object sender, EventArgs e) { webBrowser1.Navigate("https://open.weixin.qq.com/connect/qrconnect?appid=微信開放平臺申請的appid&redirect_uri=授權回調域&response_type=code&scope=snsapi_login&state=200"); }
//Form窗體
ArrayList addressList = new ArrayList(); string url = ""; private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (url != "") { string tempCode = ""; if (addressList.Count == 1) { foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("img")) { string str = he.GetAttribute("className"); if (str == "qrcode lightBorder") { pictureBox1.ImageLocation = he.GetAttribute("src"); //獲取微信生成的二維碼圖片,那個網頁中只有兩個圖片,且二維碼是第二張圖片. } } return; } else if (addressList.Count > 1) { tempCode = addressList[1].ToString(); addressList = new ArrayList(); } //微信最終獲得的code string code = ""; if (tempCode.Contains("code")) { int iStart = tempCode.IndexOf("="); int iEnd = tempCode.IndexOf('&', iStart); if (iEnd < 0) { iEnd = tempCode.Length - iStart; } else { iEnd -= iStart; } code = tempCode.Substring(iStart + 1, iEnd - 1); } else { return; } if (string.IsNullOrEmpty(code)) return; OAuth_Token token = new OAuth_Token(); OAuth_Token Model = token.Get_token(code); //獲取access_token OAuthUser OAuthUser_Model = token.Get_UserInfo(Model.access_token, Model.openid);//獲取用戶信息 if (OAuthUser_Model.openid != null) {
//通過openID 查詢用戶表 新增 修改 (openID是用戶微信唯一ID 可做關聯) Dao dao = new Dao(); string res = dao.AddWeChatUser(OAuthUser_Model); if (res == "1") { //跳轉主頁 } else if (res == "2") { //跳轉註冊頁面完善信息 } } } }
//Form窗體
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { url = e.Url.ToString(); //微信每次跳轉的頁面放到list中,第一個是包含code的網址 addressList.Add(url); }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; namespace XXXX { public class JsonHelper { public static T ParseFromJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } } }
using System.Net; using System.Text; namespace XXXXX { public class OAuth_Token { public OAuth_Token() { // //TODO: 在此處添加構造函數邏輯 // } //access_token 網頁授權介面調用憑證,註意:此access_token與基礎支持的access_token不同 //expires_in access_token介面調用憑證超時時間,單位(秒) //refresh_token 用戶刷新access_token //openid 用戶唯一標識,請註意,在未關註公眾號時,用戶訪問公眾號的網頁,也會產生一個用戶和公眾號唯一的OpenID //scope 用戶授權的作用域,使用逗號(,)分隔 public string _access_token; public string _expires_in; public string _refresh_token; public string _openid; public string _scope; public string access_token { set { _access_token = value; } get { return _access_token; } } public string expires_in { set { _expires_in = value; } get { return _expires_in; } } public string refresh_token { set { _refresh_token = value; } get { return _refresh_token; } } public string openid { set { _openid = value; } get { return _openid; } } public string scope { set { _scope = value; } get { return _scope; } } /// <summary> /// 生成Json格式 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public string GetJson(string url) { WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; wc.Encoding = Encoding.UTF8; string returnText = wc.DownloadString(url); if (returnText.Contains("errcode")) { //可能發生錯誤 } return returnText; } /// <summary> /// json轉實體 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="szJson"></param> /// <returns></returns> public OAuth_Token Get_token(string Code) { string appid = "申請的appid"; string appsecret = "申請的appsecret"; //獲取微信回傳的openid、access token string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + Code + "&grant_type=authorization_code"); //微信回傳的數據為Json格式,將Json格式轉化成對象 OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str); return Oauth_Token_Model; } /// <summary> /// 通過access_token和openid獲取用戶信息 /// </summary> /// <returns></returns> public OAuthUser Get_UserInfo(string access_token, string openid) { //獲取微信回傳的openid、access token string Str = GetJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN"); //微信回傳的數據為Json格式,將Json格式轉化成對象 OAuthUser userinfo = JsonHelper.ParseFromJson<OAuthUser>(Str); return userinfo; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XXXXX { /// <summary> /// 微信用戶信息類 /// </summary> public class OAuthUser { public OAuthUser() { } #region 資料庫欄位 private string _openID; private string _searchText; private string _nickname; private string _sex; private string _province; private string _city; private string _country; private string _headimgUrl; private string _privilege; private string _unionid; private DateTime _CreateDateTime; #endregion #region 欄位屬性 /// <summary> /// 用戶的唯一標識 /// </summary> public string openid { set { _openID = value; } get { return _openID; } } /// <summary> /// /// </summary> public string SearchText { set { _searchText = value; } get { return _searchText; } } /// <summary> /// 用戶昵稱 /// </summary> public string nickname { set { _nickname = value; } get { return _nickname; } } /// <summary> /// 用戶的性別,值為1時是男性,值為2時是女性,值為0時是未知 /// </summary> public string sex { set { _sex = value; } get { return _sex; } } /// <summary> /// 用戶個人資料填寫的省份 /// </summary> public string province { set { _province = value; } get { return _province; } } /// <summary> /// 普通用戶個人資料填寫的城市 /// </summary> public string city { set { _city = value; } get { return _city; } } /// <summary> /// 國家,如中國為CN /// </summary> public string country { set { _country = value; } get { return _country; } } /// <summary> /// 用戶頭像,最後一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),用戶沒有頭像時該項為空 /// </summary> public string headimgurl { set { _headimgUrl = value; } get { return _headimgUrl; } } /// <summary> /// 用戶特權信息,json 數組,如微信沃卡用戶為(chinaunicom)其實這個格式稱不上JSON,只是個單純數組 /// </summary> public string privilege { set { _privilege = value; } get { return _privilege; } } public string unionid { set { _unionid = value; } get { return _unionid; } } public DateTime CreateDateTime { set { _CreateDateTime = value; } get { return _CreateDateTime; } } #endregion } }