微信登录接口对接

微信开发文档
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=24feab7ab13f183bd9fb6d4c62eba48d9e95abd0&lang=zh_CN

函数:根据Code值获取UnionId

/// 
        /// 调用微信接口 获取unionId
        /// 
        /// 
        /// 
        public string GetWeChatUnionnId(string code)
        {
            #region 调用微信接口

            //根据Code 获取refresh_token
            var accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + _WebWXAppId + "&secret=" + _WebWXAppSecrect + "&code=" + code
                + "&grant_type=authorization_code";
            WebRequest accessRequest = WebRequest.Create(accessUrl);
            StreamReader accessStream = new StreamReader(accessRequest.GetResponse().GetResponseStream());
            var accessObjerct = Newtonsoft.Json.JsonConvert.DeserializeObject(accessStream.ReadToEnd());
            var refreshToken = ((dynamic)accessObjerct).refresh_token;
            var unionId = ((dynamic)accessObjerct).unionid;
            if (refreshToken == null) return null;

            //根据refresh_token重置access_token刷新时间 获取open_id
            var accessRefreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
                + _WebWXAppId + "&grant_type=refresh_token&refresh_token=" + (string)refreshToken;
            WebRequest accessRefreshRequest = WebRequest.Create(accessRefreshUrl);
            StreamReader accessRefershStream = new StreamReader(accessRefreshRequest.GetResponse().GetResponseStream());
            var accessRefreshObjerct = Newtonsoft.Json.JsonConvert.DeserializeObject(accessRefershStream.ReadToEnd());
            var accessToken = ((dynamic)accessRefreshObjerct).access_token;
            if (accessToken == null || unionId == null) return null;
            return unionId;

            #endregion
        }

你可能感兴趣的:(工具类)