using System.Web; /// <summary> /// 公共帮助类 /// </summary> public class Common { private HttpContext Context { get; set; } public static string OpenId = "Openid"; public static string access_token = "access_token"; #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="Context"></param> public Common(HttpContext context) { this.Context = context; } #endregion #region 通过code换取AccessToken /// <summary> /// 通过code换取AccessToken /// </summary> public void GetOpenidAndAccessToken() { if (!string.IsNullOrEmpty(Context.Request.QueryString["code"])) { //获取code码,以获取openid和access_token string code = Context.Request.QueryString["code"]; GetOpenidAndAccessTokenFromCode(code); } else { //构造网页授权获取code的URL string host = Context.Request.Url.Host; string path = Context.Request.Path; string redirect_uri = HttpUtility.UrlEncode("http://" + host + path); WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("redirect_uri", redirect_uri); data.SetValue("response_type", "code"); data.SetValue("scope", "snsapi_base"); data.SetValue("state", "STATE" + "#wechat_redirect"); string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl(); try { //触发微信返回code码 Context.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常 } catch (System.Threading.ThreadAbortException ex) { } } } #endregion #region 通过用户授权获取AccessToken和OpenId /// <summary> /// 通过用户授权获取AccessToken和OpenId /// </summary> /// <param name="code"></param> public void GetOpenidAndAccessTokenFromCode(string code) { try { //构造获取openid及access_token的url WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("secret", WxPayConfig.APPSECRET); data.SetValue("code", code); data.SetValue("grant_type", "authorization_code"); string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl(); //请求url以获取数据 string result = HttpService.Get(url); //保存access_token,用于收货地址获取 JsonData jd = JsonMapper.ToObject(result); access_token = (string)jd["access_token"]; //获取用户openid OpenId = (string)jd["openid"]; } catch (Exception ex) { throw new WxPayException(ex.ToString()); } } #endregion #region 获取OpenId /// <summary> /// 获取OpenId /// </summary> /// <param name="postStr"></param> /// <returns></returns> public string GetOpenId() { Common common = new Common(Context); common.GetOpenidAndAccessToken(); return OpenId; } #endregion }