- A+
所属分类:.NET技术
源码还需优化,不喜勿喷。
微信官方文档 : 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 } }