示例#1
0
文件: AppConfig.cs 项目: radtek/EBS
        public static void RegisterPaySetting()
        {
            var builder  = new ContainerBuilder();
            var gateways = new Gateways();
            //gateways.RegisterAlipay();
            var db             = AppContext.Current.Resolve <IDBContext>();
            var settings       = db.Table.FindAll <Setting>(n => n.KeyType.Like("pay.%")).ToList(); // 所有支付参数
            var normalSettings = settings.ToDictionary(n => n.KeyName);
            //按门店设置商户号参数
            var storeSettings = settings.GroupBy(n => n.StoreId);

            foreach (var storeSettingGroup in storeSettings)
            {
                /// 支付宝配置
                var alipaySetting  = storeSettingGroup.Where(n => n.KeyType.StartsWith("pay.aliypay")).ToList().ToDictionary(n => n.KeyName);
                var alipayMerchant = new PaySharp.Alipay.Merchant
                {
                    AppId           = alipaySetting.ContainsKey("pay.alipay.appid") ? alipaySetting["pay.alipay.appid"].Value : "",
                    NotifyUrl       = normalSettings.ContainsKey("pay.notify.url") ? alipaySetting["pay.alipay.notify.url"].Value : "",
                    ReturnUrl       = normalSettings.ContainsKey("pay.return.url") ? alipaySetting["pay.alipay.notify.url"].Value : "",
                    AlipayPublicKey = alipaySetting.ContainsKey("pay.alipay.publickey") ? alipaySetting["pay.alipay.publickey"].Value : "",
                    Privatekey      = alipaySetting.ContainsKey("pay.alipay.privatekey") ? alipaySetting["pay.alipay.publickey"].Value : "",
                    StoreId         = storeSettingGroup.Key
                };
                gateways.Add(new AlipayGateway(alipayMerchant)
                {
                    GatewayUrl = "https://openapi.alipaydev.com"
                });

                //微信配置
                var wechatSetting     = storeSettingGroup.Where(n => n.KeyType.StartsWith("pay.aliypay")).ToList().ToDictionary(n => n.KeyName);
                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId     = alipaySetting.ContainsKey("pay.wechat.appid") ? alipaySetting["pay.wechat.appid"].Value : "",
                    MchId     = alipaySetting.ContainsKey("pay.wechat.mchid") ? alipaySetting["pay.wechat.mchid"].Value : "",
                    Key       = alipaySetting.ContainsKey("pay.wechat.mchkey") ? alipaySetting["pay.wechat.mchkey"].Value : "",
                    AppSecret = alipaySetting.ContainsKey("pay.wechat.appsecret") ? alipaySetting["pay.wechat.appsecret"].Value : "",
                    //SslCertPath = AppDomain.CurrentDomain.BaseDirectory + "Certs/apiclient_cert.p12",
                    //SslCertPassword = "******",
                    NotifyUrl = normalSettings.ContainsKey("pay.notify.url") ? alipaySetting["pay.notify.url"].Value : "",
                    StoreId   = storeSettingGroup.Key
                };
                gateways.Add(new WechatpayGateway(wechatpayMerchant));
            }

            // builder.RegisterInstance(new DapperDBContext(Configer.MasterDB)).As<IDBContext>().InstancePerLifetimeScope();
            builder.RegisterInstance(gateways).As <IGateways>().SingleInstance();
            builder.Update(AppContext.Container);
        }
示例#2
0
        public async Task <string> GetOpenId(string code, string organizationId = null)
        {
            WeChatOpenIdResponseDTO result = null;

            BaseGateway gateway = null;

            if (string.IsNullOrEmpty(organizationId))
            {
                gateway = _gateways.Get <WechatpayGateway>();
            }
            else
            {
                WeChatAppConfiguration appConfig = _wechatAppConfigurationRepository.GetFiltered(o => o.OrganizationId == organizationId).FirstOrDefault();
                if (appConfig != null)
                {
                    var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                    {
                        AppId           = appConfig.AppId,
                        MchId           = appConfig.MchId,
                        Key             = appConfig.Key,
                        AppSecret       = appConfig.AppSecret,
                        SslCertPath     = appConfig.SslCertPath,
                        SslCertPassword = appConfig.SslCertPassword,
                        NotifyUrl       = appConfig.NotifyUrl
                    };

                    gateway = new WechatpayGateway(wechatpayMerchant);
                }
                else
                {
                    gateway = _gateways.Get <WechatpayGateway>();
                }
            }

            var reqModel = new WeChatOpenIdRequestDTO {
                AppId = gateway.Merchant.AppId, Code = code, Secret = _configuration.WeChatAppSecret
            };

            result = await _wechatApiProxy.CheckAuthCode(reqModel);

            //TODO:验签

            return(result?.OpenId ?? string.Empty);
        }
示例#3
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region  务注册
            //添加appsettings.json
            services.AddOptions();

            // Controller As Service
            services.AddMvc().AddControllersAsServices().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // MemoryCache
            services.AddScoped <ICaching, MemoryCaching>();
            services.AddSingleton <IMemoryCache>(factory =>
            {
                var cache = new MemoryCache(new MemoryCacheOptions());
                return(cache);
            });

            // Redis
            services.AddSingleton <IRedisHelper, RedisHelper>();
            // Context
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // Cookie
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            // Session
            services.AddSession();

            #endregion

            #region Office
            services.AddEasyOffice(new OfficeOptions());
            #endregion

            #region IpRateLimitOptions

            //需要存储速率和ip规则
            services.AddMemoryCache();
            //加载配置项
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
            //单机计时器和规则
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
            //分布式缓存计时器
            //services.AddSingleton<IClientPolicyStore, DistributedCacheClientPolicyStore>();
            //services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();

            #endregion

            #region 初始化
            // DB
            services.AddScoped <DbContext>();
            // Mapper
            services.AddAutoMapper(typeof(Startup));

            #endregion

            #region AllowCors

            services.AddCors(c =>
            {
                if (Def.AllowedCrosFlg)
                {
                    c.AddPolicy(Def.CorsName, policy =>
                    {
                        policy
                        .WithOrigins(Def.AllowedCrosOrigins.Split(","))
                        .AllowAnyHeader()
                        .AllowCredentials()
                        .AllowAnyMethod();
                    });
                }
                else
                {
                    c.AddPolicy(Def.CorsName, policy =>
                    {
                        policy
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
                }
            });
            #endregion

            #region  务监控

            services.AddMiniProfiler(options =>
            {
                options.RouteBasePath = "/profiler";
                (options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes(10);
            }
                                     );

            #endregion

            #region 接口文档

            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
            services.AddSwaggerGen(c =>
            {
                //遍历出全部的版本,做文档信息展示
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new Info
                    {
                        // {ApiName} 定义成全局变量
                        Version        = version,
                        Title          = $"{Def.ApiName} 接口文档",
                        Description    = $"{Def.ApiName} " + version,
                        TermsOfService = "None",
                        Contact        = new Contact {
                            Name = Def.ApiName, Email = "*****@*****.**", Url = "https://www.xxxxxx.com/"
                        }
                    });
                    // 按相对路径排序
                    c.OrderActionsBy(o => o.RelativePath);
                });
                //解决相同类名会报错的问题
                c.CustomSchemaIds(type => type.FullName);
                //配置的xml文件名
                var xmlPath = Path.Combine(basePath, Def.ApiName + ".xml");
                c.IncludeXmlComments(xmlPath, true);
                //这个就是Model层的xml文件名
                var xmlModelPath = Path.Combine(basePath, "Autumn.Model.xml");
                c.IncludeXmlComments(xmlModelPath);

                #region Token绑定到ConfigureServices
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();

                // 发行人
                var IssuerName = Def.Issuer;
                var security   = new Dictionary <string, IEnumerable <string> > {
                    { IssuerName, new string[] { } },
                };
                c.AddSecurityRequirement(security);

                //方案名称“Autumn”可自定义,上下一致即可
                c.AddSecurityDefinition(IssuerName, new ApiKeyScheme
                {
                    Description = "请在下框中输入Bearer {token}",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
                #endregion
            });

            #endregion

            #region 全局异常捕获

            //注入全局异常捕获
            services.AddMvc(o =>
            {
                // 模型有效认证
                o.Filters.Add <ModelValidationAttribute>();
                // 授权许可
                o.Filters.Add <PermissionAttribute>();
                // 全局异常过滤
                o.Filters.Add(typeof(GlobalExceptionsFilter));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            // 取消默认驼峰
            .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });

            #endregion

            #region SignalR
            if (Def.SignalrFlg)
            {
                services.AddSignalR();
            }
            #endregion

            #region HttpContext
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            #endregion

            // configuration (resolvers, counter key builders)
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            #region 策略授权
            // 第一步:配置【策略授权】
            // 第二步:配置【统一认证】
            // 第三步:开启中间件app.UseAuthentication()
            #region 参数
            // 读取配置文件
            var symmetricKeyAsBase64 = Def.Secret;
            // 发行人
            var symIssuer = Def.Issuer;
            // 订阅人
            var symAudience = Def.Audience;

            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);

            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            // 如果要数据库动态绑定,这里先留个空,后边处理器里动态赋值
            var permission = new List <PermissionItem>();

            #endregion

            #endregion

            #region 统一认证
            // 令牌验证参数
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = symIssuer,
                ValidateAudience      = true,
                ValidAudience         = symAudience,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.FromSeconds(30),
                RequireExpirationTime = true,
            };

            // JWT认证
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            #endregion

            #region AutoFac DI
            //实例化容器
            var builder = new ContainerBuilder();
            builder.RegisterType <HydCacheAOP>();
            builder.RegisterType <HydRedisCacheAOP>();
            builder.RegisterType <HydLogAOP>();

            #region 带有接口层的服务注入

            #region  务切片注入

            //获取项目绝对路径
            var servicesDllFile = Path.Combine(basePath, "Autumn.Services.dll");
            //加载文件
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);

            // 切片开关
            var cacheType = new List <Type>();
            if (Def.RedisCachingFlg)
            {
                cacheType.Add(typeof(HydRedisCacheAOP));
            }
            if (Def.MemoryCachingFlg)
            {
                cacheType.Add(typeof(HydCacheAOP));
            }
            if (Def.LogFlg)
            {
                cacheType.Add(typeof(HydLogAOP));
            }

            builder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope()
            .EnableInterfaceInterceptors()          // 引用Autofac.Extras.DynamicProxy
            .InterceptedBy(cacheType.ToArray());    // 允许将拦截器服务的列表分配给注册
            #endregion

            #region Repository.dll 注入,有对应接口
            var repositoryDllFile   = Path.Combine(basePath, "Autumn.Repository.dll");
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();

            #endregion

            #endregion

            //将services填充到Autofac容器生成器中
            builder.Populate(services);

            //使用已进行的组件创建新容器
            var ApplicationContainer = builder.Build();

            #endregion

            #region Payment Gateway

            services.AddWebEncoders(opt =>
            {
                opt.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
            });

            services.AddPaySharp(a =>
            {
                var alipayMerchant = new PaySharp.Alipay.Merchant
                {
                    AppId           = Def.AlipayAppId,
                    NotifyUrl       = Def.AlipayNotifyUrl,
                    ReturnUrl       = Def.AlipayReturnUrl,
                    AlipayPublicKey = Def.AlipayPublicKey,
                    Privatekey      = Def.AlipayPrivatekey
                };

                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId           = Def.WechatpayAppId,
                    MchId           = Def.WechatpayMchId,
                    Key             = Def.WechatpayKey,
                    AppSecret       = Def.WechatpayAppSecret,
                    SslCertPath     = Def.WechatpaySslCertPath,
                    SslCertPassword = Def.WechatpaySslCertPassword,
                    NotifyUrl       = Def.WechatpayNotifyUrl
                };

                a.Add(new AlipayGateway(alipayMerchant)
                {
                    GatewayUrl = Def.AlipayGatewayUrl
                });

                a.Add(new WechatpayGateway(wechatpayMerchant));

                a.UseAlipay(Configuration);

                a.UseWechatpay(Configuration);
            });

            #endregion

            #region Csrf
            if (Def.CsrfFlg)
            {
                services.AddAntiforgery(options => { options.Cookie.SameSite = SameSiteMode.Lax; options.HeaderName = "X-XSRF-TOKEN"; });
            }
            #endregion

            //IOC接管内置DI
            return(new AutofacServiceProvider(ApplicationContainer));
        }
示例#4
0
 /// <summary>
 /// 初始化微信支付网关
 /// </summary>
 /// <param name="merchant">商户数据</param>
 public WechatpayGateway(Merchant merchant)
     : base(merchant)
 {
     _merchant = merchant;
 }
示例#5
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(a =>
            {
                a.MapHttpAttributeRoutes();

                a.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}",
                    defaults: new { id = RouteParameter.Optional }
                    );
            });
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            var containerBuilder = new ContainerBuilder();

            PaySharpConfig.Register(typeof(MvcApplication), containerBuilder, a =>
            {
                var gateways = new Gateways();
                //gateways.RegisterAlipay();

                var alipayMerchant = new PaySharp.Alipay.Merchant
                {
                    AppId           = "2016081600256163",
                    NotifyUrl       = "http://localhost:64852/Notify",
                    ReturnUrl       = "http://localhost:64852/Notify",
                    AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsW6+mN2E3Oji2DPjSKuYgRzK6MlH9q6W0iM0Yk3R0qbpp5wSesSXqudr2K25gIBOTCchiIbXO7GXt/zEdnhnC32eOa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jzSJ5NQO0Tv+q8vKY+cd6BuJ6OUQw82ICLANIfHJZNxtvtTCmmqBwSJDpcQJQXmKXTECgYEA2SQCSBWZZONkvhdJ15K+4IHP2HRbYWi+C1OvKzUiK5bdJm77zia4yJEJo5Y/sY3mV3OK0Bgb7IAaxL3i0oH+WNTwbNoGpMlYHKuj4x1453ITyjOwPNj6g27FG1YSIDzhB6ZC4dBlkehi/7gIlIiQt1wkIZ+ltOqgI5IqIdXoSHECgYB3zCiHYt4oC1+UW7e/hCrVNUbHDRkaAygSGkEB5/9QvU5tK0QUsrmJcPihj/RUK9YW5UK7b0qbwWWsr/dFpLEUi8GWvdkSKuLprQxbrDN44O96Q5Z96Vld9WV4DtJkhs4bdWNsMQFzf4I7D9PuKeJfcvqRjaztz6nNFFSqcrqkkQKBgQCJKlUCohpG/9notp9fvQQ0n+viyQXcj6TVVOSnf6X5MRC8MYmBHTbHA8+59bSAfanO/l7muwQQro+6TlUVMyaviLvjlwpxV/sACXC6jCiO06IqreIbXdlJ41RBw2op0Ss5gM5pBRLUS58V+HP7GBWKrnrofofXtAq6zZ8txok4EQKBgQCXrTeGMs7ECfehLz64qZtPkiQbNwupg938Z40Qru/G1GR9u0kmN7ibTyYauI6NNVHGEZa373EBEkacfN+kkkLQMs1tj5Zrlw+iITm+ad/irpXQZS/NHCcrg6h82vu0LcgiKnHKlmW6K5ne0w4LqmsmRCm7JdJjt9WlapAs0ticiw=="
                };

                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId           = "wx2428e34e0e7dc6ef",
                    MchId           = "1233410002",
                    Key             = "e10adc3849ba56abbe56e056f20f883e",
                    AppSecret       = "51c56b886b5be869567dd389b3e5d1d6",
                    SslCertPath     = AppDomain.CurrentDomain.BaseDirectory + "Certs/apiclient_cert.p12",
                    SslCertPassword = "******",
                    NotifyUrl       = "http://localhost:64852/Notify"
                };

                var unionpayMerchant = new PaySharp.Unionpay.Merchant
                {
                    AppId     = "777290058110048",
                    CertPwd   = "000000",
                    CertPath  = AppDomain.CurrentDomain.BaseDirectory + "Certs/acp_test_sign.pfx",
                    NotifyUrl = "http://localhost:64852/Notify",
                    ReturnUrl = "http://localhost:64852/Notify"
                };

                gateways.Add(new AlipayGateway(alipayMerchant)
                {
                    GatewayUrl = "https://openapi.alipaydev.com"
                });
                gateways.Add(new WechatpayGateway(wechatpayMerchant));
                gateways.Add(new UnionpayGateway(unionpayMerchant)
                {
                    GatewayUrl = "https://gateway.test.95516.com"
                });

                return(gateways);
            });
        }
示例#6
0
        /// <summary>
        /// 负责调用autofac实现依赖注入,负责创建MVC控制器类的对象(调用控制器的有参构造函数),接管DefaultControllerFactory的工作
        /// </summary>
        public static void Register()
        {
            // 第一步:注册控制器
            var builder = new ContainerBuilder();

            // 告诉autofac将来要创建的控制器类存放在哪个程序集
            //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);
            // 把当前程序集中的 Controller 都注册
            builder.RegisterControllers(typeof(MvcApplication).Assembly)
            // 自动给属性进行“注入”
            .PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterFilterProvider();

            // 第二步:注册接口

            // 获取所有相关类库的程序集
            Assembly[] repository_assemblies = new Assembly[] { Assembly.Load(Assemblies.RepositoryAssembly) };
            // 把当前程序集中的类都注册
            builder.RegisterAssemblyTypes(repository_assemblies)
            // 注入类本身
            .AsSelf()
            // 剔除抽象类; type1.IsAssignableFrom(type2):type2是否实现了type1的接口/或者是否集成自type1。这样就只注册实现了IBaseService接口的类,避免注册其它无关的类
            .Where(type => !type.IsAbstract)
            // 为接口注入具体类
            .AsImplementedInterfaces()
            // 自动给属性进行“注入”
            .PropertiesAutowired()
            // 同一个Lifetime生成的对象是同一个实例
            .InstancePerLifetimeScope();

            // 获取所有相关类库的程序集
            Assembly[] service_assemblies = new Assembly[] { Assembly.Load(Assemblies.ServiceAssembly) };
            // 把当前程序集中的类都注册
            builder.RegisterAssemblyTypes(service_assemblies)
            // 剔除抽象类; type1.IsAssignableFrom(type2):type2是否实现了type1的接口/或者是否集成自type1。这样就只注册实现了IBaseService接口的类,避免注册其它无关的类
            .Where(type => !type.IsAbstract)
            // 注入类本身
            .AsSelf()
            // 为接口注入具体类
            .AsImplementedInterfaces()
            // 自动给属性进行“注入”
            .PropertiesAutowired()
            // 同一个Lifetime生成的对象是同一个实例
            .InstancePerLifetimeScope();

            // 其他
            builder.RegisterType <DefaultDbContext>().OnRelease(db => db.Dispose()).InstancePerLifetimeScope();
            builder.RegisterType <RedisHelper>().OnRelease(db => db.Dispose()).InstancePerLifetimeScope();
            //builder.RegisterType<BackgroundJobClient>().SingleInstance();//指定生命周期为单例
            //builder.RegisterType<HangfireBackJob>().As<IHangfireBackJob>().PropertiesAutowired(PropertyWiringOptions.PreserveSetValues).InstancePerDependency();

            // 支付平台
            builder.Register(a =>
            {
                var gateways = new Gateways();

                #region gateways.RegisterAlipay();
                //gateways.RegisterAlipay();
                var alipayMerchant = new PaySharp.Alipay.Merchant
                {
                    AppId           = "2016081600256163",
                    NotifyUrl       = "http://localhost:50160/Notify",
                    ReturnUrl       = "http://localhost:50160/Notify",
                    AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsW6+mN2E3Oji2DPjSKuYgRzK6MlH9q6W0iM0Yk3R0qbpp5wSesSXqudr2K25gIBOTCchiIbXO7GXt/zEdnhnC32eOaTnonDsnuBWIp+q7LoVx/gvKIX5LTHistCvGli8VW4EDGsu2jAyQXyMPgPrIz+/NzWis/gZsa4TaqVY4SpWRuSgMXxleh2ERB6k0ijK0IYM+Cv5fz1ZPDCgk7EbII2jk2fDxtlMLoN5UYEJCcD8OUyivm3Hti3u1kPolckCCf0xk+80g/4EdmzFAffsVgPeXZrkm5EIuiTTOIeRHXlTg3HtkkCw2Wl0CpYSKB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kIZ+ltOqgI5IqIdXoSHECgYB3zCiHYt4oC1+UW7e/hCrVNUbHDRkaAygSGkEB5/9QvU5tK0QUsrmJcPihj/RUK9YW5UK7b0qbwWWsr/dFpLEUi8GWvdkSKuLprQxbrDN44O96Q5Z96Vld9WV4DtJkhs4bdWNsMQFzf4I7D9PuKeJfcvqRjaztz6nNFFSqcrqkkQKBgQCJKlUCohpG/9notp9fvQQ0n+viyQXcj6TVVOSnf6X5MRC8MYmBHTbHA8+59bSAfanO/l7muwQQro+6TlUVMyaviLvjlwpxV/sACXC6jCiO06IqreIbXdlJ41RBw2op0Ss5gM5pBRLUS58V+HP7GBWKrnrofofXtAq6zZ8txok4EQKBgQCXrTeGMs7ECfehLz64qZtPkiQbNwupg938Z40Qru/G1GR9u0kmN7ibTyYauI6NNVHGEZa373EBEkacfN+kkkLQMs1tj5Zrlw+iITm+ad/irpXQZS/NHCcrg6h82vu0LcgiKnHKlmW6K5ne0w4LqmsmRCm7JdJjt9WlapAs0ticiw=="
                };
                gateways.Add(new AlipayGateway(alipayMerchant)
                {
                    GatewayUrl = "https://openapi.alipaydev.com"
                });
                #endregion

                #region gateways.RegisterWechatpay();
                //gateways.RegisterWechatpay();
                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId           = "wx2428e34e0e7dc6ef",
                    MchId           = "1233410002",
                    Key             = "e10adc3849ba56abbe56e056f20f883e",
                    AppSecret       = "51c56b886b5be869567dd389b3e5d1d6",
                    SslCertPath     = AppDomain.CurrentDomain.BaseDirectory + "Certs/apiclient_cert.p12",
                    SslCertPassword = "******",
                    NotifyUrl       = "http://localhost:64852/Notify"
                };
                gateways.Add(new WechatpayGateway(wechatpayMerchant));
                #endregion

                #region gateways.RegisterUnionpay();
                //gateways.RegisterUnionpay();
                var unionpayMerchant = new PaySharp.Unionpay.Merchant
                {
                    AppId     = "777290058110048",
                    CertPwd   = "000000",
                    CertPath  = AppDomain.CurrentDomain.BaseDirectory + "Certs/acp_test_sign.pfx",
                    NotifyUrl = "http://localhost:50160/Notify",
                    ReturnUrl = "http://localhost:50160/Notify"
                };

                gateways.Add(new UnionpayGateway(unionpayMerchant)
                {
                    GatewayUrl = "https://gateway.test.95516.com"
                });
                #endregion

                return(gateways);
            }).As <IGateways>().InstancePerRequest();

            // 第三步:注册系统容器,所有对象都从这里获取。
            Container = builder.Build();

            //5.0 将当前容器交给MVC底层,保证容器不被销毁,控制器由autofac来创建
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
            GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(Container);

            //注册系统级别的 DependencyResolver,这样当 MVC 框架创建 Controller 等对象的时候都是管 Autofac 要对象。
            DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
        }
示例#7
0
        public async Task <OpenIDSessionKeyDTO> GetSessionKey(string code, string organizationId = null, string applicationId = null)
        {
            WeChatOpenIdResponseDTO result = null;

            BaseGateway gateway = null;

            if (string.IsNullOrEmpty(organizationId))
            {
                gateway = _gateways.Get <WechatpayGateway>();
            }
            else
            {
                WeChatAppConfiguration appConfig = _wechatAppConfigurationRepository.GetFiltered(o => o.OrganizationId == organizationId).FirstOrDefault();
                if (appConfig != null)
                {
                    var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                    {
                        AppId           = appConfig.AppId,
                        MchId           = appConfig.MchId,
                        Key             = appConfig.Key,
                        AppSecret       = appConfig.AppSecret,
                        SslCertPath     = appConfig.SslCertPath,
                        SslCertPassword = appConfig.SslCertPassword,
                        NotifyUrl       = appConfig.NotifyUrl
                    };

                    gateway = new WechatpayGateway(wechatpayMerchant);
                }
                else
                {
                    gateway = _gateways.Get <WechatpayGateway>();
                }
            }

            var reqModel = new WeChatOpenIdRequestDTO {
                AppId = gateway.Merchant.AppId, Code = code, Secret = _configuration.WeChatAppSecret
            };

            result = await _wechatApiProxy.CheckAuthCode(reqModel);

            //TODO:验签

            AppletUserSessionDTO dto = null;

            if (result != null)
            {
                await _authServiceProxy.AddOrUpdateAppletUser(new AppletUserDTO
                {
                    ApplicationId  = applicationId,
                    Channel        = UserChannel.WeChat,
                    NickName       = "",
                    OpenId         = result.OpenId,
                    OrganizationId = organizationId,
                    UserId         = "",
                    UserPortrait   = ""
                });

                dto = await _authServiceProxy.AddOrUpdateAppletUserSession(new AppletUserSessionDTO
                {
                    UserId     = "",
                    OpenId     = result.OpenId,
                    SessionKey = result.SessionKey
                });
            }

            return(new OpenIDSessionKeyDTO {
                GooiosSessionKey = dto.GooiosSessionKey, OpenId = dto.OpenId
            });
        }
示例#8
0
        public async Task SyncOrderStatus(string orderId)
        {
            var orderDTO = await _orderServiceProxy.GetById(orderId);

            if (orderDTO == null)
            {
                return;
            }

            BaseGateway gateway = null;

            if (string.IsNullOrEmpty(orderDTO.OrganizationId))
            {
                gateway = _gateways.Get <WechatpayGateway>();
            }
            else
            {
                WeChatAppConfiguration appConfig = _wechatAppConfigurationRepository.GetFiltered(o => o.OrganizationId == orderDTO.OrganizationId).FirstOrDefault();
                if (appConfig != null)
                {
                    var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                    {
                        AppId           = appConfig.AppId,
                        MchId           = appConfig.MchId,
                        Key             = appConfig.Key,
                        AppSecret       = appConfig.AppSecret,
                        SslCertPath     = appConfig.SslCertPath,
                        SslCertPassword = appConfig.SslCertPassword,
                        NotifyUrl       = appConfig.NotifyUrl
                    };

                    gateway = new WechatpayGateway(wechatpayMerchant);
                }
                else
                {
                    gateway = _gateways.Get <WechatpayGateway>();
                }
            }


            var request = new QueryRequest();

            request.AddGatewayData(new QueryModel()
            {
                OutTradeNo = orderDTO.OrderNo
            });

            var response = gateway.Execute(request);

            if (response.ReturnCode == "SUCCESS")
            {
                if (response.ResultCode == "SUCCESS")
                {
                    if (response.TradeState == TradeState.SUCCESS.ToString())
                    {
                        await _orderServiceProxy.SetOrderPaidSuccessed(orderId);
                    }
                    if (response.TradeState == TradeState.REVOKED.ToString() ||
                        response.TradeState == TradeState.CLOSED.ToString())
                    {
                        await _orderServiceProxy.SetOrderPaidFailed(orderId);
                    }
                }
            }
        }
示例#9
0
        public async Task <RequestPaymentResponseDTO> RequestPayment(RequestPaymentRequestDTO model)
        {
            var orderDTO = await _orderServiceProxy.GetById(model.OrderId);

            if (orderDTO == null)
            {
                return(null);
            }

            var request = new AppletPayRequest();

            var body   = "";
            var orgStr = (orderDTO.OrderItems.FirstOrDefault()?.Title ?? "-");

            if (orgStr.Length > 20)
            {
                body = orgStr.Substring(0, 20);
            }
            else
            {
                body = orgStr;
            }

            request.AddGatewayData(new AppletPayModel()
            {
                Body        = body,
                OutTradeNo  = orderDTO.OrderNo,
                TotalAmount = (int)(orderDTO.PayAmount * 100),
                OpenId      = model.OpenId
            });

            IGateway gateway = null;

            var organizationId = "";

            organizationId = orderDTO.OrganizationId ?? "";
            WeChatAppConfiguration appConfig = null;

            if (!string.IsNullOrEmpty(organizationId))
            {
                appConfig = _wechatAppConfigurationRepository.GetFiltered(o => o.OrganizationId == organizationId).FirstOrDefault();
            }

            if (appConfig != null)
            {
                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId           = appConfig.AppId,
                    MchId           = appConfig.MchId,
                    Key             = appConfig.Key,
                    AppSecret       = appConfig.AppSecret,
                    SslCertPath     = appConfig.SslCertPath,
                    SslCertPassword = appConfig.SslCertPassword,
                    NotifyUrl       = appConfig.NotifyUrl
                };

                gateway = new WechatpayGateway(wechatpayMerchant);
            }
            else
            {
                gateway = _gateways.Get <WechatpayGateway>();
            }

            var response = gateway.Execute(request);

            var ns   = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 20);
            var ts   = GetTimeStamp();
            var pkg  = $"prepay_id={response?.PrepayId}";
            var sign = GetSign(((WechatpayGateway)gateway).Merchant.AppId, ns, response?.PrepayId, ts.ToString(), ((WechatpayGateway)gateway).Merchant.Key);

            var result = new RequestPaymentResponseDTO
            {
                NonceStr  = ns,
                Package   = pkg,
                PaySign   = sign,
                TimeStamp = ts.ToString()
            };

            return(result);
        }
示例#10
0
        public static void RegisterPaySetting()
        {
            var builder  = new ContainerBuilder();
            var gateways = new Gateways();

            var db = AppContext.Current.Resolve <IDBContext>();

            // 注册所有配置
            var allSettings = db.Table.FindAll <Setting>().ToList();  // 所有支付参数

            builder.RegisterInstance(new SettingsCollection(allSettings)).As <Domain.ISettings>().SingleInstance();

            // 注册支付配置
            var settings       = allSettings.Where(n => n.KeyName.StartsWith("pay.")).ToList();
            var normalSettings = settings.ToDictionary(n => StoreKey(n.KeyName, n.StoreId)); // key+ 门店ID 唯一
            //按门店设置商户号参数
            var storeSettings = settings.GroupBy(n => n.StoreId);
            var domainUrl     = allSettings.FirstOrDefault(n => n.KeyName == SettingKeys.System_Domain).Value;

            foreach (var storeSettingGroup in storeSettings)
            {
                /// 支付宝配置
                var alipaySetting  = storeSettingGroup.Where(n => n.KeyName.StartsWith("pay.alipay")).ToList().ToDictionary(n => StoreKey(n.KeyName, n.StoreId));
                var storeid        = storeSettingGroup.Key;
                var alipayMerchant = new PaySharp.Alipay.Merchant
                {
                    AppId           = alipaySetting.ContainsKey(StoreKey(SettingKeys.Pay_Alipay_Appid, storeid)) ? alipaySetting[StoreKey(SettingKeys.Pay_Alipay_Appid, storeid)].Value : "",
                    NotifyUrl       = domainUrl + (normalSettings.ContainsKey(StoreKey(SettingKeys.Pay_Notify_Url, storeid)) ? normalSettings[StoreKey(SettingKeys.Pay_Notify_Url, storeid)].Value : ""),
                    ReturnUrl       = domainUrl + (normalSettings.ContainsKey(StoreKey(SettingKeys.Pay_Return_Url, storeid)) ? normalSettings[StoreKey(SettingKeys.Pay_Return_Url, storeid)].Value : ""),
                    AlipayPublicKey = alipaySetting.ContainsKey(StoreKey(SettingKeys.Pay_Alipay_Public_Key, storeid)) ? alipaySetting[StoreKey(SettingKeys.Pay_Alipay_Public_Key, storeid)].Value : "",
                    Privatekey      = alipaySetting.ContainsKey(StoreKey(SettingKeys.Pay_Alipay_Private_Key, storeid)) ? alipaySetting[StoreKey(SettingKeys.Pay_Alipay_Private_Key, storeid)].Value : "",
                    StoreId         = storeid
                };
                gateways.Add(new AlipayGateway(alipayMerchant)
                {
                    GatewayUrl = "https://openapi.alipaydev.com"
                });

                //微信配置
                var wechatSetting     = storeSettingGroup.Where(n => n.KeyName.StartsWith("pay.wechat")).ToList().ToDictionary(n => StoreKey(n.KeyName, n.StoreId));
                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId     = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_Appid, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_Appid, storeid)].Value : "",
                    MchId     = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_MchId, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_MchId, storeid)].Value : "",
                    Key       = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_MchKey, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_MchKey, storeid)].Value : "",
                    AppSecret = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_AppSecret, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_AppSecret, storeid)].Value : "",
                    //SslCertPath = AppDomain.CurrentDomain.BaseDirectory + "Certs/apiclient_cert.p12",
                    //SslCertPassword = "******",
                    NotifyUrl = domainUrl + (normalSettings.ContainsKey(StoreKey(SettingKeys.Pay_Notify_Url, storeid)) ? normalSettings[StoreKey(SettingKeys.Pay_Notify_Url, storeid)].Value : ""),
                    StoreId   = storeid
                };
                gateways.Add(new WechatpayGateway(wechatpayMerchant));
            }

            // builder.RegisterInstance(new DapperDBContext(Configer.MasterDB)).As<IDBContext>().InstancePerLifetimeScope();
            builder.RegisterInstance(gateways).As <IGateways>().SingleInstance();

            // 注册支付路由
            PayServices.IPayRoute route = new PayServices.DefaultPayRoute();
            route.InitRoute();

            builder.RegisterInstance(route).As <PayServices.IPayRoute>().SingleInstance();

            builder.Update(AppContext.Container);
        }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add <ApiKeyFilter>();
                options.Filters.Add <ApiExceptionFilter>();
                options.Filters.Add <LogFilter>();
            });
            services.Configure <ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
            services.Configure <ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
            services.AddOptions();

            services.AddPaySharp(a =>
            {
                var gateways          = new Gateways();
                var wechatpayMerchant = new PaySharp.Wechatpay.Merchant
                {
                    AppId           = "wx0a5983b08057acd0",
                    AppSecret       = "7a6e9a59bc4ea25379945979d5423b1e",
                    SslCertPath     = "Certs/apiclient_cert.p12",
                    SslCertPassword = "******",
                    MchId           = "1504096781",
                    Key             = "sCafbvydmAoLaNjFDfd2nfVMG86bKBY8",
                    //NotifyUrl = "https://partnergateway.gooios.com/api/wechat/v1/paymentnotify"
                    NotifyUrl = "https://apigateway.gooios.com/paymentservice/wechatpayment/v1/paymentnotify"
                };
                a.Add(new WechatpayGateway(wechatpayMerchant));
                a.UseWechatpay(Configuration);
            });

            services.AddSingleton <IEventBus, EventBus>();
            services.AddTransient <IEventAggregator, EventAggregator>();

            services.AddSingleton <IServiceConfigurationProxy, ServiceConfigurationProxy>();
            services.AddSingleton <IWeChatAppConfigurationRepository, WeChatAppConfigurationRepository>();

            services.AddScoped <IDbUnitOfWork, DbUnitOfWork>();
            services.AddScoped <IDbContextProvider, DbContextProvider>();

            services.AddDbContext <DatabaseContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("ServiceDb"));
            });

            services.AddTransient <IWeChatPaymentNotifyMessageRepository, WeChatPaymentNotifyMessageRepository>();
            services.AddTransient <IWeChatPaymentNotifyMessageAppService, WeChatPaymentNotifyMessageAppService>();
            services.AddTransient <IWeChatPaymentAppService, WeChatPaymentAppService>();
            services.AddTransient <IOrderServiceProxy, OrderServiceProxy>();
            services.AddTransient <IWeChatApiProxy, WeChatApiProxy>();
            services.AddTransient <IAuthServiceProxy, AuthServiceProxy>();

            //services.AddTransient<IImageAppService, ImageAppService>();
            //services.AddTransient<IImageRepository, ImageRepository>();

            //services.AddTransient<IDomainEventHandler<VerificationCreatedEvent>, VerificationCreatedEventHandler>();

            var container = services.ToServiceContainer();

            container.Configure(config =>
            {
                config.Interceptors.AddTyped <ExceptionInterceptor>(m => m.DeclaringType.Name.EndsWith("AppService"));
            });

            return(IocProvider.Container = container.Build());
        }