MYBLOG

欢迎来到小马哥的个人博客~

[微信开发].net微信开发之获取用户openid

2020-03-08学海无涯

说道微信开发,感觉好久之前的事情了,大概一年前做到过,现在突然有个朋友问到我如何获取用户的openid?好吧,我找了下代码,找到了,现在在这里大概讲一下,很简单,一共分三步

1、首先去获取到接口(如下,当然你必须知道appid、secret还有code)


https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code


2、去接口get一下


helper.HttpGet(string.Format(GetVisitUserUnionidUrl, Config.GetWX_AppID(), Config.GetWX_AppSecret(), code))


在这里,我把HttpGet方法贴出来

 public string HttpGet(string Url)
        {
            var request = WebRequest.Create(Url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            return HttpRequest(request);
        }
3、接口返回给你的是json串,你知道获取到其中的openid就可以了


 COE.Components.Json.JsonHelper.GetJsonValue(helper.HttpGet(string.Format(GetVisitUserUnionidUrl, Config.GetWX_AppID(), Config.GetWX_AppSecret(), code)), "openid");
同样我还是把GetJsonValue方法粘贴出来


 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;
        }


Sorry,忘记了一个方法


private static string HttpRequest(HttpWebRequest request)
        {
            HttpWebResponse response = null;
            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            if (response == null)
            {
                return null;
            }
            string result = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
                reader.Close();
            }
            response.Close();
            return result;

        }