protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //提供微信支付信息
            var weixinPay_PartnerId    = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"];
            var weixinPay_Key          = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_Key"];
            var weixinPay_AppId        = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppId"];
            var weixinPay_AppKey       = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppKey"];
            var weixinPay_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_TenpayNotify"];

            var tenPayV3_MchId        = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"];
            var tenPayV3_Key          = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"];
            var tenPayV3_AppId        = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"];
            var tenPayV3_AppSecret    = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppSecret"];
            var tenPayV3_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"];

            var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);

            TenPayInfoCollection.Register(weixinPayInfo);
            var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key,
                                                tenPayV3_TenpayNotify);

            TenPayV3InfoCollection.Register(tenPayV3Info);
        }
Beispiel #2
0
        /// <summary>
        /// 注册微信支付
        /// </summary>
        private void RegisterWeixinPay()
        {
            var senparcWeixinSetting = Senparc.Weixin.Config.DefaultSenparcWeixinSetting;

            //提供微信支付信息
            var weixinPay_PartnerId    = senparcWeixinSetting.WeixinPay_PartnerId;
            var weixinPay_Key          = senparcWeixinSetting.WeixinPay_Key;
            var weixinPay_AppId        = senparcWeixinSetting.WeixinPay_AppId;
            var weixinPay_AppKey       = senparcWeixinSetting.WeixinPay_AppKey;
            var weixinPay_TenpayNotify = senparcWeixinSetting.WeixinPay_TenpayNotify;

            var tenPayV3_MchId        = senparcWeixinSetting.TenPayV3_MchId;
            var tenPayV3_Key          = senparcWeixinSetting.TenPayV3_Key;
            var tenPayV3_AppId        = senparcWeixinSetting.TenPayV3_AppId;
            var tenPayV3_AppSecret    = senparcWeixinSetting.TenPayV3_AppSecret;
            var tenPayV3_TenpayNotify = senparcWeixinSetting.TenPayV3_TenpayNotify;

            var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);

            TenPayInfoCollection.Register(weixinPayInfo);//微信V2(旧版)

            var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify);

            TenPayV3InfoCollection.Register(tenPayV3Info);//微信V3(新版)
        }
Beispiel #3
0
        public static void Init(IPlugin plugin)
        {
            app        = plugin;
            PluginAttr = plugin.GetAttribute();
            initCfg(PluginAttr);
            InitWeixin(PluginAttr.Settings);

            //提供微信支付信息
            var weixinPay_PartnerId    = PluginAttr.Settings["WeixinPay_PartnerId"];
            var weixinPay_Key          = PluginAttr.Settings["WeixinPay_Key"];
            var weixinPay_AppId        = PluginAttr.Settings["WeixinPay_AppId"];
            var weixinPay_AppKey       = PluginAttr.Settings["WeixinPay_AppKey"];
            var weixinPay_TenpayNotify = PluginAttr.Settings["WeixinPay_TenpayNotify"];
            var tenPayV3_MchId         = PluginAttr.Settings["TenPayV3_MchId"];
            var tenPayV3_Key           = PluginAttr.Settings["TenPayV3_Key"];
            var tenPayV3_AppId         = PluginAttr.Settings["TenPayV3_AppId"];
            var tenPayV3_AppSecret     = PluginAttr.Settings["TenPayV3_AppSecret"];
            var tenPayV3_TenpayNotify  = PluginAttr.Settings["TenPayV3_TenpayNotify"];
            var weixinPayInfo          = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);

            TenPayInfoCollection.Register(weixinPayInfo);
            var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key,
                                                tenPayV3_TenpayNotify);

            TenPayV3InfoCollection.Register(tenPayV3Info);
        }
Beispiel #4
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //提供微信支付信息
            var weixinPay_PartnerId    = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"];
            var weixinPay_Key          = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_Key"];
            var weixinPay_AppId        = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppId"];
            var weixinPay_AppKey       = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppKey"];
            var weixinPay_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_TenpayNotify"];

            var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);

            TenPayInfoCollection.Register(weixinPayInfo);
        }
Beispiel #5
0
        /// <summary>
        /// 注册微信支付
        /// </summary>
        private void RegisterWeixinPay()
        {
            //提供微信支付信息
            var weixinPay_PartnerId    = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"];
            var weixinPay_Key          = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_Key"];
            var weixinPay_AppId        = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppId"];
            var weixinPay_AppKey       = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppKey"];
            var weixinPay_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_TenpayNotify"];

            var tenPayV3_MchId        = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"];
            var tenPayV3_Key          = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"];
            var tenPayV3_AppId        = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"];
            var tenPayV3_AppSecret    = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppSecret"];
            var tenPayV3_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"];

            var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);

            TenPayInfoCollection.Register(weixinPayInfo);
            var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key,
                                                tenPayV3_TenpayNotify);

            TenPayV3InfoCollection.Register(tenPayV3Info);
        }
Beispiel #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            //引入EnableRequestRewind中间件
            app.UseEnableRequestRewind();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            #region 提供网站根目录(当前 Sample 用到,和 SDK 无关)
            if (env.ContentRootPath != null)
            {
                Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath;
            }
            Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath;              // env.ContentRootPath;
            #endregion


            var isDebug = true;//当前是否是Debug状态
            IRegisterService register = RegisterService.Start(env, isDebug);

            #region 注册线程(必须) 在Start()中已经自动注册,此处也可以省略,仅作演示

            register.RegisterThreads();  //启动线程,RegisterThreads()也可以省略,在RegisterService.Start()中已经自动注册

            #endregion

            #region 缓存配置(按需)

            // 当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须)
            register.ChangeDefaultCacheNamespace("DefaultWeixinCache");

            //配置Redis缓存(按需,独立)
            var redisConfigurationStr = senparcWeixinSetting.Value.Cache_Redis_Configuration;
            var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置";
            if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的
            {
                CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);
                //如果不进行任何设置,则默认使用内存缓存
            }


            //配置Memcached缓存(按需,独立)
            //这里配置的是 CO2NET 的 Memcached 缓存(如果执行了下面的 app.UseSenparcWeixinCacheMemcached(),
            //会自动包含本步骤,这一步注册可以忽略)
            var useMemcached = false;
            app.UseWhen(h => useMemcached, a => a.UseEnyimMemcached());

            #endregion

            #region 注册日志(按需)

            register.RegisterTraceLog(ConfigTraceLog);//配置TraceLog

            #endregion

            #region 微信相关配置


            /* 微信配置开始
             *
             * 建议按照以下顺序进行注册,尤其须将缓存放在第一位!
             */

            //注册开始

            #region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前)

            // 微信的 Memcached 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useMemcached)
            {
                app.UseSenparcWeixinCacheMemcached();
            }
            //app.UseWhen(h => useMemcached, a => a.UseSenparcWeixinCacheMemcached());//如果连接而配置未生效,不能这么使用

            //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useRedis)
            {
                app.UseSenparcWeixinCacheRedis();
            }
            //app.UseWhen(h => useRedis, a => a.UseSenparcWeixinCacheRedis());//如果连接而配置未生效,不能这么使用

            #endregion

            //开始注册微信信息
            register.UseSenparcWeixin(senparcWeixinSetting.Value, isDebug /*此处为单独用于微信的调试状态*/, () => GetExContainerCacheStrategies(senparcWeixinSetting.Value)) //注意:这里没有 ; 下面可接着写

            #region 注册公众号或小程序(按需)

            //注册公众号
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WeixinAppId,
                senparcWeixinSetting.Value.WeixinAppSecret,
                "【盛派网络小助手】公众号")
            //注册多个公众号或小程序
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WxOpenAppId,
                senparcWeixinSetting.Value.WxOpenAppSecret,
                "【盛派互动】小程序")

            #endregion

            #region 注册企业号(按需)

            //注册企业号
            .RegisterWorkAccount(
                senparcWeixinSetting.Value.WeixinCorpId,
                senparcWeixinSetting.Value.WeixinCorpSecret,
                "【盛派网络】企业微信")
            //还可注册任意多个企业号

            #endregion

            #region 注册微信支付(按需)

            //注册旧微信支付版本(V2)
            .RegisterTenpayOld(() =>
            {
                //提供微信支付信息
                var weixinPay_PartnerId    = senparcWeixinSetting.Value.WeixinPay_PartnerId;
                var weixinPay_Key          = senparcWeixinSetting.Value.WeixinPay_Key;
                var weixinPay_AppId        = senparcWeixinSetting.Value.WeixinPay_AppId;
                var weixinPay_AppKey       = senparcWeixinSetting.Value.WeixinPay_AppKey;
                var weixinPay_TenpayNotify = senparcWeixinSetting.Value.WeixinPay_TenpayNotify;
                var weixinPayInfo          = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key,
                                                            weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);
                return(weixinPayInfo);
            })
            //注册最新微信支付版本(V3)
            .RegisterTenpayV3(() =>
            {
                //提供微信支付信息
                var tenPayV3_MchId        = senparcWeixinSetting.Value.TenPayV3_MchId;
                var tenPayV3_Key          = senparcWeixinSetting.Value.TenPayV3_Key;
                var tenPayV3_AppId        = senparcWeixinSetting.Value.TenPayV3_AppId;
                var tenPayV3_AppSecret    = senparcWeixinSetting.Value.TenPayV3_AppSecret;
                var tenPayV3_TenpayNotify = senparcWeixinSetting.Value.TenPayV3_TenpayNotify;
                var tenPayV3Info          = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret,
                                                             tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify);
                return(tenPayV3Info);
            })

            #endregion

            #region 注册微信第三方平台(按需)

            .RegisterOpenComponent(
                senparcWeixinSetting.Value.Component_Appid,
                senparcWeixinSetting.Value.Component_Secret,

                //getComponentVerifyTicketFunc
                componentAppId =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket"));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId));
                using (var fs = new FileStream(file, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        var ticket = sr.ReadToEnd();
                        return(ticket);
                    }
                }
            },

                //getAuthorizerRefreshTokenFunc
                (componentAppId, auhtorizerId) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                if (!File.Exists(file))
                {
                    return(null);
                }

                using (Stream fs = new FileStream(file, FileMode.Open))
                {
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var result    = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs);
                    return(result.authorizer_refresh_token);
                }
            },

                //authorizerTokenRefreshedFunc
                (componentAppId, auhtorizerId, refreshResult) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                using (Stream fs = new FileStream(file, FileMode.Create))
                {
                    //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    binFormat.Serialize(fs, refreshResult);
                    fs.Flush();
                }
            }, "【盛派网络】开放平台")

            #endregion

            ;

            /* 微信配置结束 */

            #endregion
        }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            //引入EnableRequestRewind中间件
            app.UseEnableRequestRewind();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            #region 提供网站根目录(当前 Sample 用到,和 SDK 无关)
            if (env.ContentRootPath != null)
            {
                Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath;
            }
            Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath;              // env.ContentRootPath;
            #endregion

            // 启动 CO2NET 全局注册,必须!
            IRegisterService register = RegisterService.Start(env, senparcSetting.Value)
                                        .UseSenparcGlobal(false, () => GetExCacheStrategies(senparcSetting.Value));

            //如果需要自动扫描自定义扩展缓存,可以这样使用:
            //register.UseSenparcWeixin(true);
            //如果需要指定自定义扩展缓存,可以这样用:
            //register.UseSenparcWeixin(false, GetExCacheStrategies);

            #region CO2NET 全局配置

            #region 注册线程,在 RegisterService.Start() 中已经自动注册,此处也可以省略,仅作演示

            register.RegisterThreads();  //启动线程,RegisterThreads()也可以省略,在RegisterService.Start()中已经自动注册

            #endregion

            #region 缓存配置(按需)

            // 当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须)
            register.ChangeDefaultCacheNamespace("DefaultCO2NETCache");

            //配置全局使用Redis缓存(按需,独立)
            var redisConfigurationStr = senparcSetting.Value.Cache_Redis_Configuration;
            var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置";
            if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的
            {
                //设置Redis链接信息,并在全局立即启用Redis缓存。
                register.RegisterCacheRedis(redisConfigurationStr, redisConfiguration => RedisObjectCacheStrategy.Instance);

                //此外还可以通过这种方式修改 Redis 链接信息(不立即启用):
                //RedisManager.ConfigurationOption = redisConfigurationStr;

                //以下会立即将全局缓存设置为Redis(不修改配置)。
                //如果要使用其他缓存,同样可以在任意地方使用这个方法,修改 RedisObjectCacheStrategy 为其他缓存策略
                //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);
            }
            //如果这里不进行Redis缓存启用,则目前还是默认使用内存缓存


            //配置Memcached缓存(按需,独立)
            //这里配置的是 CO2NET 的 Memcached 缓存(如果执行了下面的 app.UseSenparcWeixinCacheMemcached(),
            //会自动包含本步骤,这一步注册可以忽略)
            var useMemcached = false;
            app.UseWhen(h => useMemcached, a =>
            {
                a.UseEnyimMemcached();
                //确保Memcached连接可用后,启用下面的做法
                //var memcachedConnStr = senparcSetting.Value.Cache_Memcached_Configuration;
                //var memcachedConnDic = new Dictionary<string, int>() {/*进行配置 { "localhost", 9101 }*/ };//可以由 memcachedConnStr 分割得到,或直接填写
                //register.RegisterCacheMemcached(memcachedConnDic, memcachedConfig => MemcachedObjectCacheStrategy.Instance);
            });


            #endregion

            #region 注册日志(按需,建议)

            register.RegisterTraceLog(ConfigTraceLog);//配置TraceLog

            #endregion

            #endregion

            #region 微信相关配置


            /* 微信配置开始
             *
             * 建议按照以下顺序进行注册,尤其须将缓存放在第一位!
             */

            //注册开始

            #region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前)

            // 微信的 Memcached 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useMemcached)
            {
                app.UseSenparcWeixinCacheMemcached();
            }
            //app.UseWhen(h => useMemcached, a => a.UseSenparcWeixinCacheMemcached());//如果连接而配置未生效,不能这么使用

            //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useRedis)
            {
                app.UseSenparcWeixinCacheRedis();
            }
            //app.UseWhen(h => useRedis, a => a.UseSenparcWeixinCacheRedis());//如果连接而配置未生效,不能这么使用

            #endregion

            //开始注册微信信息,必须!
            register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value)
            //注意:上一行没有 ; 下面可接着写 .RegisterXX()

            #region 注册公众号或小程序(按需)

            //注册公众号
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WeixinAppId,
                senparcWeixinSetting.Value.WeixinAppSecret,
                "【盛派网络小助手】公众号")
            //注册多个公众号或小程序
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WxOpenAppId,
                senparcWeixinSetting.Value.WxOpenAppSecret,
                "【盛派网络小助手】小程序")    //注意:小程序和公众号的AppId/Secret属于并列关系,这里name需要区分开

            #endregion

            #region 注册企业号(按需)

            //注册企业号
            .RegisterWorkAccount(
                senparcWeixinSetting.Value.WeixinCorpId,
                senparcWeixinSetting.Value.WeixinCorpSecret,
                "【盛派网络】企业微信")
            //还可注册任意多个企业号

            #endregion

            #region 注册微信支付(按需)

            //注册旧微信支付版本(V2)
            .RegisterTenpayOld(() =>
            {
                //提供微信支付(旧版本)信息
                var weixinPayInfo = new TenPayInfo(senparcWeixinSetting.Value);
                return(weixinPayInfo);
            },
                               "【盛派网络小助手】公众号"//这里的 name 和第一个 RegisterMpAccount() 中的一致,会被记录到同一个 SenparcWeixinSettingItem 对象中
                               )
            //注册最新微信支付版本(V3)
            .RegisterTenpayV3(() =>
            {
                //提供微信支付(新版本 V3)信息
                var tenPayV3Info = new TenPayV3Info(senparcWeixinSetting.Value);
                return(tenPayV3Info);
            }, "【盛派网络小助手】公众号")    //记录到同一个 SenparcWeixinSettingItem 对象中

            #endregion

            #region 注册微信第三方平台(按需)

            .RegisterOpenComponent(
                senparcWeixinSetting.Value.Component_Appid,
                senparcWeixinSetting.Value.Component_Secret,

                //getComponentVerifyTicketFunc
                componentAppId =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket"));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId));
                using (var fs = new FileStream(file, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        var ticket = sr.ReadToEnd();
                        return(ticket);
                    }
                }
            },

                //getAuthorizerRefreshTokenFunc
                (componentAppId, auhtorizerId) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                if (!File.Exists(file))
                {
                    return(null);
                }

                using (Stream fs = new FileStream(file, FileMode.Open))
                {
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var result    = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs);
                    return(result.authorizer_refresh_token);
                }
            },

                //authorizerTokenRefreshedFunc
                (componentAppId, auhtorizerId, refreshResult) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                using (Stream fs = new FileStream(file, FileMode.Create))
                {
                    //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    binFormat.Serialize(fs, refreshResult);
                    fs.Flush();
                }
            }, "【盛派网络】开放平台")

            #endregion

            ;

            /* 微信配置结束 */

            #endregion
        }
Beispiel #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            //引入EnableRequestRewind中间件
            app.UseEnableRequestRewind();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            #region 微信相关配置

            #region 提供网站根目录(当前 Sample 用到,和 SDK 无关)
            if (env.ContentRootPath != null)
            {
                Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath;
            }
            Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath;              // env.ContentRootPath;
            #endregion

            /* 微信配置开始
             *
             * 建议按照以下顺序进行注册,尤其须将缓存放在第一位!
             */

            //注册开始

            var isDebug = true;                                       //当前是否是Debug状态
            RegisterService.Start(env, senparcWeixinSetting, isDebug) //这里没有 ; 下面接着写

            #region 缓存配置

            // 当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须)
            .ChangeDefaultCacheNamespace("DefaultWeixinCache")

            //配置Redis缓存
            .RegisterCacheRedis(
                senparcWeixinSetting.Value.Cache_Redis_Configuration,
                redisConfiguration => (!string.IsNullOrEmpty(redisConfiguration) && redisConfiguration != "Redis配置")
                                         ? RedisObjectCacheStrategy.Instance
                                         : null)

            #endregion

            #region 注册日志(按需)

            .RegisterTraceLog(ConfigWeixinTraceLog)    //配置TraceLog

            #endregion

            #region 注册线程(必须) 在Start()中已经自动注册,此处也可以省略,仅作演示

            .RegisterThreads()       //启动线程,RegisterThreads()也可以省略,在Start()中已经自动注册

            #endregion

            #region 注册公众号或小程序(按需)

            //注册公众号
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WeixinAppId,
                senparcWeixinSetting.Value.WeixinAppSecret,
                "【盛派网络小助手】公众号")
            //注册多个公众号或小程序
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WxOpenAppId,
                senparcWeixinSetting.Value.WxOpenAppSecret,
                "【盛派互动】小程序")

            #endregion

            #region 注册企业号(按需)

            //注册企业号
            .RegisterWorkAccount(
                senparcWeixinSetting.Value.WeixinCorpId,
                senparcWeixinSetting.Value.WeixinCorpSecret,
                "【盛派网络】企业微信")
            //还可注册任意多个企业号

            #endregion

            #region 注册微信支付(按需)

            //注册旧微信支付版本(V2)
            .RegisterTenpayOld(() =>
            {
                //提供微信支付信息
                var weixinPay_PartnerId    = senparcWeixinSetting.Value.WeixinPay_PartnerId;
                var weixinPay_Key          = senparcWeixinSetting.Value.WeixinPay_Key;
                var weixinPay_AppId        = senparcWeixinSetting.Value.WeixinPay_AppId;
                var weixinPay_AppKey       = senparcWeixinSetting.Value.WeixinPay_AppKey;
                var weixinPay_TenpayNotify = senparcWeixinSetting.Value.WeixinPay_TenpayNotify;
                var weixinPayInfo          = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key,
                                                            weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify);
                return(weixinPayInfo);
            })
            //注册最新微信支付版本(V3)
            .RegisterTenpayV3(() =>
            {
                //提供微信支付信息
                var tenPayV3_MchId        = senparcWeixinSetting.Value.TenPayV3_MchId;
                var tenPayV3_Key          = senparcWeixinSetting.Value.TenPayV3_Key;
                var tenPayV3_AppId        = senparcWeixinSetting.Value.TenPayV3_AppId;
                var tenPayV3_AppSecret    = senparcWeixinSetting.Value.TenPayV3_AppSecret;
                var tenPayV3_TenpayNotify = senparcWeixinSetting.Value.TenPayV3_TenpayNotify;
                var tenPayV3Info          = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret,
                                                             tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify);
                return(tenPayV3Info);
            })

            #endregion

            #region 注册微信第三方平台(按需)

            .RegisterOpenComponent(
                senparcWeixinSetting.Value.Component_Appid,
                senparcWeixinSetting.Value.Component_Secret,

                //getComponentVerifyTicketFunc
                componentAppId =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket"));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId));
                using (var fs = new FileStream(file, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        var ticket = sr.ReadToEnd();
                        return(ticket);
                    }
                }
            },

                //getAuthorizerRefreshTokenFunc
                (componentAppId, auhtorizerId) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                if (!File.Exists(file))
                {
                    return(null);
                }

                using (Stream fs = new FileStream(file, FileMode.Open))
                {
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var result    = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs);
                    return(result.authorizer_refresh_token);
                }
            },

                //authorizerTokenRefreshedFunc
                (componentAppId, auhtorizerId, refreshResult) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                using (Stream fs = new FileStream(file, FileMode.Create))
                {
                    //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    binFormat.Serialize(fs, refreshResult);
                    fs.Flush();
                }
            }, "【盛派网络】开放平台");

            #endregion

            ;

            //配置Memcached缓存
            #region Senparc.Weixin SDK Memcached 配置

            app.UseEnyimMemcached();

            #endregion

            /* 微信配置结束 */

            #endregion
        }
Beispiel #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            //引入EnableRequestRewind中间件
            app.UseEnableRequestRewind();
            app.UseSession();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            #region 提供网站根目录(当前 Sample 用到,和 SDK 无关)
            if (env.ContentRootPath != null)
            {
                Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath;
            }
            Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath;              // env.ContentRootPath;
            #endregion

            // 启动 CO2NET 全局注册,必须!
            IRegisterService register = RegisterService.Start(env, senparcSetting.Value)
                                        //关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore/Startup.cs
                                        .UseSenparcGlobal();

            //如果需要自动扫描自定义扩展缓存,可以这样使用:
            //register.UseSenparcGlobal(true);
            //如果需要指定自定义扩展缓存,可以这样用:
            //register.UseSenparcGlobal(false, GetExCacheStrategies);

            #region CO2NET 全局配置

            #region 全局缓存配置(按需)

            //当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须)
            register.ChangeDefaultCacheNamespace("DefaultCO2NETCache");

            #region 配置和使用 Redis

            //配置全局使用Redis缓存(按需,独立)
            var redisConfigurationStr = senparcSetting.Value.Cache_Redis_Configuration;
            var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置";
            if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的,这里的if条件可以忽略
            {
                /* 说明:
                 * 1、Redis 的连接字符串信息会从 Config.SenparcSetting.Cache_Redis_Configuration 自动获取并注册,如不需要修改,下方方法可以忽略
                 * /* 2、如需手动修改,可以通过下方 SetConfigurationOption 方法手动设置 Redis 链接信息(仅修改配置,不立即启用)
                 */
                Senparc.CO2NET.Cache.Redis.Register.SetConfigurationOption(redisConfigurationStr);

                //以下会立即将全局缓存设置为 Redis
                Senparc.CO2NET.Cache.Redis.Register.UseKeyValueRedisNow();//键值对缓存策略(推荐)
                //Senparc.CO2NET.Cache.Redis.Register.UseHashRedisNow();//HashSet储存格式的缓存策略

                //也可以通过以下方式自定义当前需要启用的缓存策略
                //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//键值对
                //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisHashSetObjectCacheStrategy.Instance);//HashSet
            }
            //如果这里不进行Redis缓存启用,则目前还是默认使用内存缓存

            #endregion

            #region 配置和使用 Memcached

            //配置Memcached缓存(按需,独立)
            var memcachedConfigurationStr = senparcSetting.Value.Cache_Memcached_Configuration;
            var useMemcached = !string.IsNullOrEmpty(memcachedConfigurationStr) && memcachedConfigurationStr != "Memcached配置";

            if (useMemcached) //这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的,这里的if条件可以忽略
            {
                app.UseEnyimMemcached();

                /* 说明:
                 * 1、Memcached 的连接字符串信息会从 Config.SenparcSetting.Cache_Memcached_Configuration 自动获取并注册,如不需要修改,下方方法可以忽略
                 * /* 2、如需手动修改,可以通过下方 SetConfigurationOption 方法手动设置 Memcached 链接信息(仅修改配置,不立即启用)
                 */
                Senparc.CO2NET.Cache.Memcached.Register.SetConfigurationOption(redisConfigurationStr);

                //以下会立即将全局缓存设置为 Memcached
                Senparc.CO2NET.Cache.Memcached.Register.UseMemcachedNow();

                //也可以通过以下方式自定义当前需要启用的缓存策略
                CacheStrategyFactory.RegisterObjectCacheStrategy(() => MemcachedObjectCacheStrategy.Instance);
            }

            #endregion

            #endregion

            #region 注册日志(按需,建议)

            register.RegisterTraceLog(ConfigTraceLog);//配置TraceLog

            #endregion

            #endregion

            #region 微信相关配置


            /* 微信配置开始
             *
             * 建议按照以下顺序进行注册,尤其须将缓存放在第一位!
             */

            //注册开始

            #region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前)

            // 微信的 Memcached 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useMemcached)
            {
                app.UseSenparcWeixinCacheMemcached();
            }

            //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useRedis)
            {
                app.UseSenparcWeixinCacheRedis();
            }

            #endregion


            //开始注册微信信息,必须!
            register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value)
            //注意:上一行没有 ; 下面可接着写 .RegisterXX()

            #region 注册公众号或小程序(按需)

            //注册公众号
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WeixinAppId,
                senparcWeixinSetting.Value.WeixinAppSecret,
                "【盛派网络小助手】公众号")
            //注册多个公众号或小程序
            .RegisterMpAccount(
                senparcWeixinSetting.Value.WxOpenAppId,
                senparcWeixinSetting.Value.WxOpenAppSecret,
                "【盛派网络小助手】小程序")    //注意:小程序和公众号的AppId/Secret属于并列关系,这里name需要区分开

            //除此以外,仍然可以在程序任意地方注册公众号或小程序:
            //AccessTokenContainer.Register(appId, appSecret, name);//命名空间:Senparc.Weixin.MP.Containers
            #endregion

            #region 注册企业号(按需)

            //注册企业微信
            .RegisterWorkAccount(
                senparcWeixinSetting.Value.WeixinCorpId,
                senparcWeixinSetting.Value.WeixinCorpSecret,
                "【盛派网络】企业微信")
            //还可注册任意多个企业号

            //除此以外,仍然可以在程序任意地方注册企业微信:
            //AccessTokenContainer.Register(corpId, corpSecret, name);//命名空间:Senparc.Weixin.Work.Containers
            #endregion

            #region 注册微信支付(按需)

            //注册旧微信支付版本(V2)
            .RegisterTenpayOld(() =>
            {
                //提供微信支付(旧版本)信息
                var weixinPayInfo = new TenPayInfo(senparcWeixinSetting.Value);
                return(weixinPayInfo);
            },
                               "【盛派网络小助手】公众号"//这里的 name 和第一个 RegisterMpAccount() 中的一致,会被记录到同一个 SenparcWeixinSettingItem 对象中
                               )
            //注册最新微信支付版本(V3)
            .RegisterTenpayV3(() =>
            {
                //提供微信支付(新版本 V3)信息
                var tenPayV3Info = new TenPayV3Info(senparcWeixinSetting.Value);
                return(tenPayV3Info);
            }, "【盛派网络小助手】公众号")    //记录到同一个 SenparcWeixinSettingItem 对象中

            #endregion

            #region 注册微信第三方平台(按需)

            .RegisterOpenComponent(
                senparcWeixinSetting.Value.Component_Appid,
                senparcWeixinSetting.Value.Component_Secret,

                //getComponentVerifyTicketFunc
                componentAppId =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket"));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId));
                using (var fs = new FileStream(file, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        var ticket = sr.ReadToEnd();
                        return(ticket);
                    }
                }
            },

                //getAuthorizerRefreshTokenFunc
                (componentAppId, auhtorizerId) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                if (!File.Exists(file))
                {
                    return(null);
                }

                using (Stream fs = new FileStream(file, FileMode.Open))
                {
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var result    = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs);
                    return(result.authorizer_refresh_token);
                }
            },

                //authorizerTokenRefreshedFunc
                (componentAppId, auhtorizerId, refreshResult) =>
            {
                var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                using (Stream fs = new FileStream(file, FileMode.Create))
                {
                    //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    binFormat.Serialize(fs, refreshResult);
                    fs.Flush();
                }
            }, "【盛派网络】开放平台")

            //除此以外,仍然可以在程序任意地方注册开放平台:
            //ComponentContainer.Register();//命名空间:Senparc.Weixin.Open.Containers
            #endregion

            ;

            /* 微信配置结束 */

            #endregion
        }