第一个类:封装好微信配置文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using Newtonsoft.Json;
///
/// 微信公众号配置文件
///
///
public class Config : System.Web.SessionState.IRequiresSessionState
{
///
/// 开发者ID
///
public static string AppId { get; set; }
///
/// 开发者密码
///
public static string AppSecret { get; set; }
///
/// APP access_token 7200秒更新一次
///
public static string access_token
{
get
{
try
{
if (HttpContext.Current.Session["$access_token"] == null)
{
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
string ret = wc.DownloadString(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", Config.AppId, Config.AppSecret));
Dictionary
if (o.ContainsKey("errmsg")) return o["errmsg"].ToString();
HttpContext.Current.Session.Add("$access_token", o["access_token"].ToString());
HttpContext.Current.Session.Timeout = 7200;
return o["access_token"].ToString();
}
}
return HttpContext.Current.Session["$access_token"].ToString();
}
catch
{
throw;
}
}
}
}
第二个类:封装好HTTP请求类
using System;
using System.Collections.Specialized;
using System.Net;
///
/// 封装好HTTP请求方便调用
///
public class HttpService
{
public static string Get(string url)
{
using (WebClient c = new WebClient())
{
try
{
c.Encoding = System.Text.Encoding.UTF8;
return c.DownloadString(url);
}
catch (Exception)
{
throw;
}
}
}
public static string GetPost(string url, string parameters)
{
string ret = "";
using (WebClient c = new WebClient())
{
try
{
c.Encoding = System.Text.Encoding.UTF8;
byte[] data = System.Text.Encoding.UTF8.GetBytes(parameters);
c.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
c.Headers.Add("ContentLength", parameters.Length.ToString());
ret = System.Text.Encoding.UTF8.GetString(c.UploadData(url, "POST", data));
return ret;
}
catch (Exception)
{
throw;
}
}
}
public static string GetPost(string url, NameValueCollection nv)
{
using (WebClient c = new WebClient())
{
try
{
c.Encoding = System.Text.Encoding.UTF8;
return System.Text.Encoding.UTF8.GetString(c.UploadValues(url, "POST", nv));
}
catch (Exception)
{
throw;
}
}
}
}
第三个类:封装好微信基础页,方便其他页面继承调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
///
/// WeiXin 的摘要说明
///
public abstract class WeiXinPage : System.Web.UI.Page, System.Web.SessionState.IRequiresSessionState
{
protected sealed override void OnPreInit(EventArgs e)
{
if (isGuest)
{
getWxUser();
}
base.OnPreInit(e);
}
///
/// 是否访客身份 true:是 false:否
///
public static bool isGuest
{
get
{
return HttpContext.Current.Session[_user] == null ? true : false;
}
}
private static string _user { get { return "$wxuser"; } }
private static string _code { get { return "$wxcode"; } }
private static string _AbsoluteUri { get { return HttpContext.Current.Request.Url.AbsoluteUri; } }
///
/// 该路径剔除微信Query的URL用于页面重定向获取最新的用户信息
///
private static string _RawUrl
{
get
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
url = url.Replace(url.Substring(url.IndexOf("code"), url.IndexOf("STATE") + 5 - url.IndexOf("code")), "");
return url;
}
}
///
/// 获取微信用户信息
///
private static Dictionary
{
string code = HttpContext.Current.Request.QueryString.Get("code") ?? "",
url = "",
ret = "";
try
{
object user = HttpContext.Current.Session[_user];
if (code.Length == 0 && user == null)
{
/* 第一步: 用户同意授权,获取code*/
JumpUrl();
return null;
}
if (user != null) return JsonConvert.DeserializeObject
#region /*如果session中不存在user信息则对接微信接口获取用户信息*/
/* 第二步:通过code换取网页授权access_token */
url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code"
, Config.AppId
, Config.AppSecret
, code);
ret = HttpService.Get(url);
Dictionary
/* 第三步:根据access_token和openid拉取用户信息 */
url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN"
, o["access_token"]
, o["openid"]);
ret = HttpService.Get(url);
/*保存用户到Session*/
HttpContext.Current.Session[_user] = ret;
#endregion
return JsonConvert.DeserializeObject
}
catch
{
throw;
}
}
///
/// 跳转至微信授权登录页
///
private static void JumpUrl()
{
string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
, Config.AppId
, _AbsoluteUri);
HttpContext.Current.Response.Redirect(url, false);
}
///
/// 微信用户信息
///
public Dictionary
{
get
{
return getWxUser();
}
}
}
演示:
public partial class _Default : WeiXinPage
{
protected override void OnLoad(EventArgs e)
{
Response.Write(JsonConvert.SerializeObject(Data));
base.OnLoad(e);
}
}