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

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

时间:2016-07-11 10:32:44      阅读:461      评论:0      收藏:0      [点我收藏+]

标签:

一、填写授权回调页面的域名

技术分享

 

二、引导用户到指定的授权页面

例如:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

redirect_uri 是一个 url

三、最后奉上完整实现的代码

下面是完整的代码,希望对大家有用。

 1 <%@ WebHandler Language="C#" Class="UserAuth" %>
 2 
 3 public class UserAuth : IHttpHandler
 4 {
 5     public void ProcessRequest(HttpContext context)
 6     {
 7  
 8         var appid = "wxf1c24c60e3ac13b7";
 9         var secret = "5902b9817acb7a290d4b7c2e6e97d4d3";
10 
11         var code = context.Request.QueryString["Code"];
12         if (string.IsNullOrEmpty(code))
13         {
14             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);
15             context.Response.Redirect(url);
16         }
17         else
18         {
19             var client = new System.Net.WebClient();
20             client.Encoding = System.Text.Encoding.UTF8;
21 
22             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);
23             var data = client.DownloadString(url);
24 
25             var serializer = new JavaScriptSerializer();
26             var obj = serializer.Deserialize<Dictionary<string, string>>(data);
27             string accessToken;
28             if (!obj.TryGetValue("access_token", out accessToken))
29                 return;
30 
31             var opentid = obj["openid"];
32             url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid);
33             data = client.DownloadString(url);
34             var userInfo = serializer.Deserialize<Dictionary<string, object>>(data);
35             foreach (var key in userInfo.Keys)
36             {
37                 context.Response.Write(string.Format("{0}: {1}", key, userInfo[key]) + "<br/>");
38             }
39         }
40     }
41 }

 

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

标签:

原文地址:http://www.cnblogs.com/soulmate/p/5659267.html

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