微信公众号获取access_token,code,openID,用户基本信息等

微信公众号获取用户基本信息

  1. 拿到appid
  2. 拿到secret
  3. 获取access_token

这个方法CallbackCode很重要,需要在页面初始化时加载

        private void CallbackCode ()
        {
          //获取当前页面url当页面第一次加载这个方法时,将redirect_url以参数的形式传入微信的链接
            Wxinterface.wxapp.redirect_url = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
           //当前清空下code,为null,第二次执行时会得到code
            Wxinterface.wxapp.code = HttpContext.Current.Request["code"];
            //这个就是获取用户信息的方法了, Wxinterface下getUserJson
            var json = Wxinterface.getUserJson();//用户信息
            Session["json"] = json;
        }

Wxinterface这个类你可以获取用户基本信息等

    public static class Wxinterface
    {
        /// <summary>
        /// 获取wx的凭证
        /// </summary>
        public class wxapp
        {
            public static string grant_type = "client_credential";
            public static string appid = "*******";//配置自己公众号的appid
            public static string secret = "*******";//配置自己公众号的secret 
            public static string code = "";
            public static string redirect_url = "";
            public static string access_token = "";

        }

        public static string access_token_url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", wxapp.appid, wxapp.secret);//获取access_token

        /// <summary>
        /// 返回json数据,请求接口
        /// </summary>
        /// <param name="url">URL</param>
        public static string HttpInfceJson(string url, string method, string json)
        {
            //    的接口地址
            string Url = url;
            //存储接口返回的数据
            string result = "";
            //Web请求
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);

            if (method == "get" || method == "GET")
            {
                req.Method = "GET";//请求方式
            }
            else
            {
                req.Method = "POST";
            }

            req.ContentLength = 0;//一定要添加这句
            //获取接口返回值
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            //以流的方式读取返回的数据
            Stream stream = null;
            stream = resp.GetResponseStream();
            //获取内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();//如果接口返回的是json字符串,那么这里就是对应的json字符串
                resp.Close();
                req = null;
            }
            if (result != "")
            {
                return result;
            }
            else
            {
                return "NULL";
            }
        }

        /// <summary>
        /// 获取key的值
        /// </summary>
        /// <param name="jsonStr">json数据</param>
        /// <param name="key">key</param>
        /// <returns></returns>
        public static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim('"') + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号,若是最后一个,截“}”号,取最小值
                    int end = jsonStr.IndexOf(',', index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }

                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
                }
            }
            return result;
        }


        /// <summary>
        ///获取access_token
        /// </summary>
        /// <returns></returns>
        public static string getToken()
        {
            string access = HttpInfceJson(Wxinterface.access_token_url, "get", "");
            string token = GetJsonValue(access, "access_token");//获取access_token

            if (token != "" || token != null)
            {
                return token;
            }
            else
            {
                return "tokenNull";
            }

        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public static string getUserJson()
        {
            string Openid = "";
            string redirect_url = "";

            wxapp.access_token = getToken();
              //当code是null的时候执行这个
            if (string.IsNullOrEmpty(wxapp.code))
            {
                redirect_url = HttpUtility.UrlEncode(wxapp.redirect_url);//一定要将wxapp.redirect_url进行UrlEncode
            // *下面这个东西重定向到腾讯的服器,我们的 redirect_url 参数会被腾讯回调,回调后就会执行我们当前的页面,就是执行开头CallbackCode方法,再次执行的时候就会进入我们就会获取到code,腾讯将code这个参数加到它回调的页面了所以我们第二次就能获取到,所以wxapp.code就不为null,就会执行下面的else了*
               HttpContext.Current.Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", wxapp.appid, redirect_url, new Random().Next(1000, 200000).ToString()));
            }
            else
            {
            //然后就是调接口穿参很简单,
                string id = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", wxapp.appid, wxapp.secret, wxapp.code);
                //这个HttpInfceJson方方法是请求接口的方法,会返回一个json
                Openid = HttpInfceJson(id, "POST", "");
            }
            获取openID,这个GetJsonValue方法就是获取接送key对应的,val
            string openid = Wxinterface.GetJsonValue(Openid, "openid");//获取openid

            string user = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", wxapp.access_token, openid);
            //得到用户信息了..
            string userJson = HttpInfceJson(user, "GET", "");

            return userJson;
        }

        /// <summary>
        /// 这个方法,可以设置响应体
        /// </summary>
        /// <param name="posturl">URL</param>
        /// <param name="postData">JSON</param>
        /// <returns></returns>
        public static string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页(html)代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }


    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值