<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="Newtonsoft.Json.Linq" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["code"]) && !string.IsNullOrEmpty(Request.QueryString["state"]))
{
app config = new app();
string appid = config.key("AppId");
string secret = config.key("AppSecret");
string redirect_uri = config.key("redURL");
string code = Request.QueryString["code"];
WebClient webClient = new WebClient();
//用户授权获取到access_token
Byte[] bytes = webClient.DownloadData(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code));
//设置字码格式
string result = System.Text.Encoding.GetEncoding("utf-8").GetString(bytes);
//将json转换成JObject
JObject jObj = JObject.Parse(result);
if (result.IndexOf("access_token") > 0)
{
//拉去用户信息
string userInfo = "https://api.weixin.qq.com/sns/userinfo";
//下载页面数据
byte[] byuser = webClient.DownloadData(string.Format("{0}?access_token={1}&openid={2}&lang=zh_CN", userInfo, jObj["access_token"].ToString(), code));
//编码
string userdata = System.Text.Encoding.GetEncoding("utf-8").GetString(byuser);
//state 页面值
string state = Request.QueryString["state"];
//判断是否有openid
if (userdata.IndexOf("openid") > 0)
{
//转json
JObject juse = JObject.Parse(userdata);
Session["openid"] = juse["openid"].ToString();
//插入到数据库 ,,不管是什么操作先添加到数据 有就更新
WxUser wx = new WxUser();
string[] data ={ juse["openid"].ToString(), juse["nickname"].ToString(), juse["sex"].ToString(), juse["province"].ToString(), juse["city"].ToString(), juse["country"].ToString(), juse["headimgurl"].ToString(), juse["privilege"].ToString() };
wx.Insert(data);
Server.Transfer(state);
}
else {
Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=" + Request.QueryString["state"] + "#wechat_redirect", appid, Server.UrlEncode(redirect_uri)));
}
}
if (result.IndexOf("errcode") > 0)
{
Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=" + Request.QueryString["state"] + "#wechat_redirect", appid, Server.UrlEncode(redirect_uri)));
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no" />
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>