网站微信第三方登录里面,用的是 微信开放平台 中申请的 APPID 和 APPSECRET。回调地址下的代码如下:
public partial class WeiXinLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { WeiXinLoginAPI(); } public const string APPID = ""; public const string APPSECRET = ""; public void WeiXinLoginAPI() { string errorCode = "微信登录过期,请重新登录!"; var code = Request.QueryString["Code"]; try { if (!string.IsNullOrEmpty(code)) { var client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.UTF8; var 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); var data = Tools.GetPage(url); Log.Debug("第一个接口", data); var serializer = new JavaScriptSerializer(); var obj = serializer.Deserialize<Dictionary<string, string>>(data); string accessToken; if (!obj.TryGetValue("access_token", out accessToken)) return; var opentid = obj["openid"]; url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid); data = Tools.GetPage(url); Log.Debug("第二个接口", data); var userInfo = serializer.Deserialize<Dictionary<string, object>>(data); #region 同步数据到您的平台操作 Begin if (opentid != null && userInfo["nickname"] != null) { try { Users _MTUsers = GetModel( openid); //获取用户信息 if (_MTUsers == null) { Insert(_MTUsers); //如果不存在,创建 } else { _MTUsers.LastLogin = DateTime.Now; _MTUsers.LastUpdated = DateTime.Now; Instance.MTUsers.Business.Update(_MTUsers); //存在则修改 } Session["CurrentUser"] = _MTUsers; //将当前登录的用户放入session中 } catch (Exception ex) { Response.Write("异常信息:" + ex.ToString()); } } else { errorCode = "微信登录身份过期"; } #endregion } } catch (Exception ex) { Log.Debug("【异常】", errorCode + ";异常信息:" + ex.Message.ToString()); } } }
时间: 2024-11-05 14:42:02