这篇文章主要为大家详细介绍了.net微信公众号获取openid和用户信息的方法,用户openid对于微信公众平台开发尤为重要,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了微信公众平台实现获取用户openid的方法,供大家参考,具体内容如下
index.aspx.cs代码:
public partial class index : system.web.ui.page
{
//用户id
public string openid = "";
//公众号信息部分
public string appid = configurationmanager.appsettings["appid"];
public string appsecret = configurationmanager.appsettings["appsecret"];
public string redirect_uri =httputility.urlencode("http://www.jb51.net");
public string scope = "【删除这个并填入请求类型,例如:snsapi_userinfo】";
#region 显示页面
public string accesstoken;
public string nickname;
public string sex;
public string headimgurl;
public string province;
public string country;
public string language;
public string city;
public string privilege = "";
#endregion
protected void page_load(object sender, eventargs e)
{
/*
*微信认证获取openid部分:
*临时认证code
*/
//微信认证部分:第二步 获得code
string code = request["code"];
if (string.isnullorempty(code))
{
//如果code没获取成功,重新拉取一遍
openaccess();
}
//微信认证部分:第三步 获得openid
string url = string.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appsecret, code);
string result = httpclienthelper.getresponse(url);
loghelper.writefile(result);
jobject outputobj = jobject.parse(result);
//微信认证部分:第四步 获得更多信息
accesstoken = outputobj["access_token"].tostring();
openid = outputobj["openid"].tostring();
url = string.format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_cn",accesstoken,openid);
string result1 = httpclienthelper.getresponse(url);
loghelper.writefile(result1);
jobject outputobj1 = jobject.parse(result1);//将json转为数组
//以下是第四步获得的信息:
nickname = outputobj1["nickname"].tostring(); //昵称
sex = outputobj1["sex"].tostring(); //性别什么的
headimgurl = outputobj1["headimgurl"].tostring(); //头像url
province = outputobj1["province"].tostring(); ;
country = outputobj1["country"].tostring(); ;
language = outputobj1["language"].tostring(); ;
city = outputobj1["city"].tostring(); ;
//将获得的用户信息填入到session中
session["openid"] = outputobj1["openid"];
//转向回入口
//openaccess();
}
/*
* 接入入口
* 开放到微信菜单中调用
* @param $dir_url 来源url
* @since 1.0
* @return void
*/
public void openaccess()
{
//判断session不存在
if (session["openid"] == null)
{
//认证第一步:重定向跳转至认证网址
string url = string.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&&response_type=code&scope=snsapi_userinfo&m=oauth2#wechat_redirect", appid, redirect_uri);
response.redirect(url);
}
//判断session存在
else
{
//跳转到前端页面.aspx
response.redirect(request.url.tostring());
}
}
}
index.aspx内容:
<%@ page language="c#" autoeventwireup="true" codebehind="index.aspx.cs" inherits="test.index" %>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
td
{
word-wrap: break-word;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<p id="wu" runat="server">
<table style="width: 100%;">
<tr>
<td style="width: 150px;">
<p>
openid:<%=openid%></p>
</td>
<td>
<p>
nickname:<%=nickname%></p>
</td>
<td>
<p>
sex:<%=sex%></p>
</td>
</tr>
<tr>
<td>
<p>
language:<%=language%></p>
</td>
<td>
<p>
city:<%=city%></p>
</td>
<td>
<p>
country:<%=country%></p>
</td>
</tr>
<tr>
<td>
<p>
headimgurl:<img width="50px;" src="<%=headimgurl %>" alt=""></p>
</td>
<td>
<p>
privilege:<%=privilege%></p>
</td>
<td>
</td>
</tr>
</table>
</p>
</form>
</body>
</html>
httpclienthelper.cs代码:
public class httpclienthelper
{
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string getresponse(string url)
{
if (url.startswith("https"))
{
servicepointmanager.securityprotocol = securityprotocoltype.tls;
}
var httpclient = new httpclient();
httpclient.defaultrequestheaders.accept.add( new mediatypewithqualityheadervalue("application/json"));
httpresponsemessage response = httpclient.getasync(url).result;
if (response.issuccessstatuscode)
{
string result = response.content.readasstringasync().result;
return result;
}
return null;
}
public static t getresponse<t>(string url)
where t : class, new()
{
if (url.startswith("https"))
servicepointmanager.securityprotocol = securityprotocoltype.tls;
var httpclient = new httpclient();
httpclient.defaultrequestheaders.accept.add(
new mediatypewithqualityheadervalue("application/json"));
httpresponsemessage response = httpclient.getasync(url).result;
t result = default(t);
if (response.issuccessstatuscode)
{
task<string> t = response.content.readasstringasync();
string s = t.result;
result = jsonconvert.deserializeobject<t>(s);
}
return result;
}
/// <summary>
/// post请求
/// </summary>
/// <param name="url"></param>
/// <param name="postdata">post数据</param>
/// <returns></returns>
public static string postresponse(string url, string postdata)
{
if (url.startswith("https"))
servicepointmanager.securityprotocol = securityprotocoltype.tls;
httpcontent httpcontent = new stringcontent(postdata);
httpcontent.headers.contenttype = new mediatypeheadervalue("application/json");
var httpclient = new httpclient();
httpresponsemessage response = httpclient.postasync(url, httpcontent).result;
if (response.issuccessstatuscode)
{
string result = response.content.readasstringasync().result;
return result;
}
return null;
}
/// <summary>
/// 发起post请求
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="url">url</param>
/// <param name="postdata">post数据</param>
/// <returns></returns>
public static t postresponse<t>(string url, string postdata)
where t : class, new()
{
if (url.startswith("https"))
servicepointmanager.securityprotocol = securityprotocoltype.tls;
httpcontent httpcontent = new stringcontent(postdata);
httpcontent.headers.contenttype = new mediatypeheadervalue("application/json");
var httpclient = new httpclient();
t result = default(t);
httpresponsemessage response = httpclient.postasync(url, httpcontent).result;
if (response.issuccessstatuscode)
{
task<string> t = response.content.readasstringasync();
string s = t.result;
result = jsonconvert.deserializeobject<t>(s);
}
return result;
}
/// <summary>
/// v3接口全部为xml形式,故有此方法
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="url"></param>
/// <param name="xmlstring"></param>
/// <returns></returns>
public static t postxmlresponse<t>(string url, string xmlstring)
where t : class, new()
{
if (url.startswith("https"))
servicepointmanager.securityprotocol = securityprotocoltype.tls;
httpcontent httpcontent = new stringcontent(xmlstring);
httpcontent.headers.contenttype = new mediatypeheadervalue("application/json");
var httpclient = new httpclient();
t result = default(t);
httpresponsemessage response = httpclient.postasync(url, httpcontent).result;
if (response.issuccessstatuscode)
{
task<string> t = response.content.readasstringasync();
string s = t.result;
result = xmldeserialize<t>(s);
}
return result;
}
/// <summary>
/// 反序列化xml
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="xmlstring"></param>
/// <returns></returns>
public static t xmldeserialize<t>(string xmlstring)
where t : class, new()
{
try
{
var ser = new xmlserializer(typeof (t));
using (var reader = new stringreader(xmlstring))
{
return (t) ser.deserialize(reader);
}
}
catch (exception ex)
{
throw new exception("xmldeserialize发生异常:xmlstring:" + xmlstring + "异常信息:" + ex.message);
}
}
}
结果如图:
以上就是.net微信公众号获取openid和用户信息实例解析的详细内容。
