码迷,mamicode.com
首页 > 微信 > 详细

微信开发——通过授权获取用户的基本信息

时间:2016-03-03 16:20:02      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

<%@ WebHandler Language="C#" Class="UserAuth" %>

public class UserAuth : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
 
        var appid = "wxf1c24c60e3ac13b7";
        var secret = "5902b9817acb7a290d4b7c2e6e97d4d3";

        var code = context.Request.QueryString["Code"];
        if (string.IsNullOrEmpty(code))
        {
            var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri=http%3a%2f%2fwx.alinq.org%2fTest%2fUserAuth.ashx&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appid);
            context.Response.Redirect(url);
        }
        else
        {
            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, secret, code);
            var data = client.DownloadString(url);

            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 = client.DownloadString(url);
            var userInfo = serializer.Deserialize<Dictionary<string, object>>(data);
            foreach (var key in userInfo.Keys)
            {
                context.Response.Write(string.Format("{0}: {1}", key, userInfo[key]) + "<br/>");
            }
        }
    }
}

 

微信开发——通过授权获取用户的基本信息

标签:

原文地址:http://www.cnblogs.com/demoC/p/5239026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!