微信

using System;
using System.Text.RegularExpressions;
using System.Web;
using Wisdom.JPClient.WeiXin.Utility;

namespace Wisdom.JPClient.WeiXin.Lib
{
    public sealed class WxHelper
    {
        //我的测试号
        //public const string APPID = "wx6596bfb9388cc63c";
        //public const string APPSECRET = "eb0c0d643d4e7bd3a43b61fd1031a2f2";
        //慧视通 公众号
        public static string APPID = ThisSession.WxConfig.APPID;
        public static string APPSECRET = ThisSession.WxConfig.APPSECRET;

        public static string GetCodeUrl(string redirect_url)
        {
            string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect", APPID, redirect_url);
            return url;
        }

        public static WxWebToken GetWebToken(string code)
        {
            if (string.IsNullOrEmpty(code)) { return null; }
            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 responseText = HttpClientHelper.HttpGet(new Uri(url));
            if (string.IsNullOrEmpty(responseText)) { throw new Exception("GetWebToken()错误"); }
            WxWebToken token = JsonHelper.DeserializeObject<WxWebToken>(responseText);
            return token;
        }

        public static WxWebToken RefreshWebToken(string refresh_token)
        {
            if (string.IsNullOrEmpty(refresh_token)) { return null; }
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", APPID, refresh_token);
            string responseText = HttpClientHelper.HttpGet(new Uri(url));
            if (string.IsNullOrEmpty(responseText)) { throw new Exception("RefreshWebToken()错误"); }
            WxWebToken token = JsonHelper.DeserializeObject<WxWebToken>(responseText);
            return token;
        }

        public static WxWebUser GetWebUserInfo(string access_token, string openid)
        {
            if (string.IsNullOrEmpty(access_token) || string.IsNullOrEmpty(openid)) { return null; }
            string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
            string responseText = HttpClientHelper.HttpGet(new Uri(url));
            if (string.IsNullOrEmpty(responseText)) { throw new Exception("GetWebUserInfo()错误"); }
            WxWebUser user = JsonHelper.DeserializeObject<WxWebUser>(responseText);
            return user;
        }



        public static WxBaseToken GetWxBaseToken()
        {
            string cacheKey = "WxBaseToken.config";
            System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
            object obj = cache.Get(cacheKey);
            if (obj == null)
            {
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", APPID, APPSECRET);
                string responseText = HttpClientHelper.HttpGet(new Uri(url));
                if (string.IsNullOrEmpty(responseText)) { throw new Exception("GetWxBaseToken()错误"); }
                WxBaseToken token = JsonHelper.DeserializeObject<WxBaseToken>(responseText);
                if (!string.IsNullOrEmpty(token.access_token))
                {
                    cache.Insert(cacheKey, token, null, DateTime.Now.AddSeconds(token.expires_in - 200), System.Web.Caching.Cache.NoSlidingExpiration);
                }
                return token;
            }
            return (WxBaseToken)obj;
        }

        public static WxJsApiTicket GetWxJsApiTicket(string access_token)
        {
            string cacheKey = "WxJsApiTicket.config";
            System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
            object obj = cache.Get(cacheKey);
            if (obj == null)
            {
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
                string responseText = HttpClientHelper.HttpGet(new Uri(url));
                if (string.IsNullOrEmpty(responseText)) { throw new Exception("GetWxJsApiTicket()错误"); }
                WxJsApiTicket jsApi = JsonHelper.DeserializeObject<WxJsApiTicket>(responseText);
                if (!string.IsNullOrEmpty(jsApi.ticket))
                {
                    cache.Insert(cacheKey, jsApi, null, DateTime.Now.AddSeconds(jsApi.expires_in - 200), System.Web.Caching.Cache.NoSlidingExpiration);
                }
                return jsApi;
            }
            return (WxJsApiTicket)obj;
        }


        public static bool IsWxBrowser(HttpRequest request)
        {
            string userAgent = request.Headers["User-Agent"];
            if (string.IsNullOrEmpty(userAgent)) { return true; }
            Regex regex = new Regex(@"micromessenger");
            return regex.IsMatch(userAgent.ToLower());
        }
    }

    public class WxWebToken
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
        public string openid { get; set; }
        public string scope { get; set; }
        public string unionid { get; set; }
    }

    public class WxWebUser
    {
        public string openid { get; set; }
        public string nickname { get; set; }
        public int sex { get; set; }
        public string province { get; set; }
        public string city { get; set; }
        public string country { get; set; }
        public string headimgurl { get; set; }
        public string unionid { get; set; }
    }

    public class WxBaseToken
    {
        private int _expires_in = 7200;
        public string access_token { get; set; }
        public int expires_in { get { return _expires_in; } set { _expires_in = value; } }
    }

    public class WxJsApiTicket
    {
        private int _expires_in = 7200;
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public int expires_in { get { return _expires_in; } set { _expires_in = value; } }
    }
}
<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <configSections>
    <section name="LogText" type=" " />
  </configSections>
  <appSettings>
    <add key="DbHelperProvider" value="System.Data.SqlClient" />
    <add key="DbHelperConnectionString" value="Data Source=172.16.0.251;Initial Catalog=DB_JP_BaseInfo00;User ID=sa;Password=weisheng;" />
      <add key="Wisdom_DTMIS_New_ServiceUser" value="Admin"/>
      <add key="Wisdom_DTMIS_New_ServicePwd" value="919616"/>

      <!--用于调用短信接口-->
      <add key="Wisdom_Host_Interface_Url" value="http://api.elianche.com/v1.1/"/>
      <!--E连车接口调用用户名-->
      <add key="Wisdom_Host_Interface_UserName" value="txc"/>
      <!--E连车接口调用密码-->
      <add key="Wisdom_Host_Interface_PassWord" value="txc"/>
      <!--E连车接口来源类型-->
      <add key="Wisdom_Host_Interface_SourceType" value="2"/>
      <!--E连车接口短信模板ID-->
      <add key="Wisdom_Host_Interface_MsgTmpId" value="3704"/>
    <add key="WxPay_NoticUrl" value="http://hstwx.wisdom-gps.com:52539/Order/ResultNotify.aspx"/>
<!--客户端上传的教练图片地址(客户端对应api地址) -->
 <add key="CoachPicUrl" value="http://172.16.0.251:1232/UploadFiles/Coach/"/>
  </appSettings>
  <LogText Path="lg" DebugEnabled="true" InfoEnabled="true" WarnEnabled="true" ErrorEnabled="true" FatalEnabled="true" />
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
        <defaultDocument>
            <files>
                <clear/>
                <add value="index.aspx"/>
            </files>
        </defaultDocument>
        <modules>
            <add name="WebAppAuthModule" type="Wisdom.JPClient.WeiXin.Web.WebAppAuthModule, Wisdom.JPClient.WeiXin.Web"/>
        </modules>
    </system.webServer>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="WebServiceSoap" />
            </basicHttpBinding>
            <customBinding>
                <binding name="WebServiceSoap12">
                    <textMessageEncoding messageVersion="Soap12" />
                    <httpTransport />
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="http://172.16.0.251:1233/WebService/WebService.asmx" binding="basicHttpBinding"
                bindingConfiguration="WebServiceSoap" contract="JP_Service.WebServiceSoap"
                name="WebServiceSoap" />
        </client>
    </system.serviceModel>
</configuration>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Wisdom.JPClient.WeiXin.Lib;
using Wisdom.JPClient.WeiXin.Utility;

namespace Wisdom.JPClient.WeiXin.Web
{
    public class WebAppAuthModule : IHttpModule
    {
        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Application_BeginRequest);
            context.AcquireRequestState += new EventHandler(Application_AcquireRequestState);
            context.Error += new EventHandler(Application_Error);
        }

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            //UrlParamsModule.Execute(sender, e);
            //SWFUploadModule.Execute(sender, e);
        }

        public void Application_AcquireRequestState(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            if (context.Session == null) { return; }
            //if (string.isnullorempty(thissession.wxopenid))
            //{
            //    string path = context.request.apprelativecurrentexecutionfilepath.tolower();
            //    list<string> pathlist = new list<string>();
            //    pathlist.add("~/index.aspx");
            //    pathlist.add("~/order/resultnotify.aspx");
            //    if (!pathlist.any(x => path.contains(x)))
            //    {
            //        //context.response.redirect("~/frame/notfound.html");
            //        wxmodule.execute(context);
            //    }
            //}
            GZipModule.Execute(sender, e);
        }

        public void Application_Error(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            Exception ex = context.Server.GetLastError().GetBaseException();
            if (ex == null || ex.TargetSite.Name == "GetFileInfo") { return; }
            context.Response.Redirect("~/frame/error.html");


            //Logger.WriteExceptionLog(ex);
            //int result = 0; string message = string.Empty;
            //if (WebAppContext.IsAjaxRequest())
            //{
            //    if (ex is EBaseException)
            //    {
            //        result = DataTypeParse.ToInt(ex.Message);
            //        switch ((EBaseExceptionType)result)
            //        {
            //            case EBaseExceptionType.ParameterError: { message = "参数错误"; } break;
            //            case EBaseExceptionType.ActivitySiteNotExist: { message = "站点活动不存在"; } break;
            //            case EBaseExceptionType.ActivitySiteFinalQuantityBuZu: { message = "数量不足"; } break;
            //        }
            //    }
            //    else
            //    {
            //        message = ex.Message;
            //    }
            //    StringBuilder responseBuilder = new StringBuilder();
            //    responseBuilder.AppendFormat("\"result\":{0},", result);
            //    responseBuilder.AppendFormat("\"message\":\"{0}\"", JsonHelper.CheckJsonSafechar(message));
            //    string responseText = WebContext.AddJson(responseBuilder.ToString());
            //    context.Response.Clear();
            //    context.Response.StatusCode = 400;
            //    context.Response.Write(responseText);
            //    context.Response.Flush();
            //    context.Server.ClearError();
            //}
            //else
            //{
            //    message = "~/error.html";
            //    if (ex is EBaseException)
            //    {
            //        switch ((EBaseExceptionType)DataTypeParse.ToInt(ex.Message))
            //        {
            //            case EBaseExceptionType.WxBrowserError: { message = "~/browser.html"; } break;
            //            case EBaseExceptionType.ActivityNotExist:
            //            case EBaseExceptionType.ConsigneeNotExist:
            //            case EBaseExceptionType.OrderNotExist: { message = "~/notfound.html"; } break;
            //        }
            //    }
            //    context.Response.Redirect(message);
            //}
        }
    }
}

 

posted on 2016-06-17 10:21  雪原日暮  阅读(302)  评论(0编辑  收藏  举报