/// <summary> /// 获取用户信息 /// </summary> /// <param>信息数据code凭证</param> /// <returns></returns> [HttpGet] public IHttpActionResult GetUserInfo(string code) { string AppSecret = "小程序秘钥"; string AppId = "应用程序标识"; try { //请求目标地址和参数(authorization_code授权类型,此处只需填写 authorization_code) string OauthUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";//序列化解析数据 var Result = HttpGet(OauthUrl); return Json(new { openid = Result.openid, errcode = Result.errcode, UnionID = Result.unionid, session_key = Result.session_key }); } catch (Exception ex) { return Json(new { errcode = 1, msg = "获取用户信息失败" + ex.Message }); } } /// <summary> /// 请求code2Session接口获取用户信息 /// </summary> /// <param>目标地址和参数</param> /// <returns></returns> public WxOauthModle HttpGet(string requestDataAndUrl) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestDataAndUrl); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return JsonConvert.DeserializeObject<WxOauthModle>(retString); } public class WxOauthModle { /// <summary> /// 用户唯一标识 /// </summary> public string openid { get; set; } /// <summary> /// 会话秘钥 /// </summary> public string session_key { get; set; } /// <summary> /// 联立编号 /// </summary> public string unionid { get; set; } /// <summary> /// 错误码 /// </summary> public int errcode { get; set; } /// <summary> /// 错误信息 /// </summary> public string errmsg { get; set; } }
关于微信网页开发通过UnionID机制解决用户在不同公众号,或在公众号、移动应用之间帐号统一问题: