private async Task Register(WeChatConfig weChatConfig) { await AccessTokenContainer.RegisterAsync( weChatConfig.WeChatAppId, weChatConfig.WeChatAppSecret, weChatConfig.WeChatName); }
public async Task <IActionResult> OnPostAsync(int id = 0) { IsEdit = id > 0; MpAccount mpAccount = null; if (IsEdit) { mpAccount = await _mpAccountService.GetObjectAsync(z => z.Id == id); if (mpAccount == null) { return(RenderError("公众号信息不存在!")); } _mpAccountService.Mapper.Map(MpAccountDto, mpAccount); } else { mpAccount = new MpAccount(MpAccountDto); } await _mpAccountService.SaveObjectAsync(mpAccount); //重新进行公众号注册 await AccessTokenContainer.RegisterAsync(mpAccount.AppId, mpAccount.AppSecret, $"{mpAccount.Name}-{mpAccount.Id}"); //立即获取 AccessToken await AccessTokenContainer.GetAccessTokenAsync(mpAccount.AppId, true); //return RedirectToPage("./Edit", new { id = mpAccount.Id, uid = Uid }); return(Ok(new { id = mpAccount.Id, uid = Uid })); }
public override IApplicationBuilder UseXscfModule(IApplicationBuilder app, IRegisterService registerService) { try { //未安装数据库表的情况下可能会出错,因此需要try using (var scope = app.ApplicationServices.CreateScope()) { var allMpAccount = GetAllMpAccounts(scope.ServiceProvider); //批量自动注册公众号 foreach (var mpAccount in allMpAccount) { Task.Factory.StartNew(async() => { await AccessTokenContainer.RegisterAsync(mpAccount.AppId, mpAccount.AppSecret, $"{mpAccount.Name}-{mpAccount.Id}"); }); } } } catch { } return(base.UseXscfModule(app, registerService)); }
public async Task <IActionResult> OnPostAjaxAsync([FromBody] MpAccountDto mpAccountDto) { MpAccount mpAccount = null; if (mpAccountDto.Id > 0) { mpAccount = await _mpAccountService.GetObjectAsync(z => z.Id == mpAccountDto.Id); if (mpAccount == null) { return(RenderError("公众号信息不存在!")); } mpAccountDto.AddTime = mpAccount.AddTime; _mpAccountService.Mapper.Map(mpAccountDto, mpAccount); mpAccount.LastUpdateTime = DateTime.Now; } else { mpAccount = new MpAccount(mpAccountDto); } await _mpAccountService.SaveObjectAsync(mpAccount); //重新进行公众号注册 await AccessTokenContainer.RegisterAsync(mpAccount.AppId, mpAccount.AppSecret, $"{mpAccount.Name}-{mpAccount.Id}"); //立即获取 AccessToken await AccessTokenContainer.GetAccessTokenAsync(mpAccount.AppId, true); //return RedirectToPage("./Edit", new { id = mpAccount.Id, uid = Uid }); return(Ok(new { id = mpAccount.Id, uid = Uid })); }
public async Task <ActionResult> Test() { //注册 await AccessTokenContainer.RegisterAsync(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret); var accessToken = AccessTokenContainer.TryGetAccessToken("wx4b58f9e96371d9ff", "43c5c4d9b8207634eb293a72ddad5bb1", true); var token = await AccessTokenContainer.TryGetAccessTokenAsync(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, false); //获取Ticket完整结果(包括当前过期秒数) var ticketResult = JsApiTicketContainer.GetJsApiTicketResult(TenPayV3Info.AppId); // //只获取Ticket字符串 var ticket = JsApiTicketContainer.GetJsApiTicket(TenPayV3Info.AppId); //getNewTicket { ticket = JsApiTicketContainer.TryGetJsApiTicket(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, false); ticket = JsApiTicketContainer.TryGetJsApiTicket(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, true); //Assert.AreNotEqual(ticketResult.ticket, ticket);//如果微信服务器缓存,此处会相同 } return(Content(token)); }
void Init() { SenparcSetting senparcSetting = new SenparcSetting(Options.WeChatDevOptions.IsDebug); IRegisterService register = RegisterService.Start(senparcSetting).UseSenparcGlobal(); //CO2NET全局注册,必须! SenparcWeixinSetting senparcWeixinSetting = new SenparcWeixinSetting(Options.WeChatDevOptions.IsDebug); register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting); ////微信全局注册,必须! AccessTokenContainer.RegisterAsync(Options.WeChatBaseOptions.AppId, Options.WeChatBaseOptions.Appsecret).GetAwaiter().GetResult(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Use(next => context => { context.Request.EnableBuffering(); return(next(context)); }); //app.UseMiddleware<TokenAuth>(); app.UseHttpsRedirection(); app.UseRouting(); //跨域 app.UseCors("all"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.Map("/", context => { context.Response.Redirect("/swagger"); return(Task.CompletedTask); }); }); #region 微信模块 // 启动 CO2NET 全局注册,必须! IRegisterService register = RegisterService.Start(senparcSetting.Value) .UseSenparcGlobal(false, null); //开始注册微信信息,必须! register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value); //全局注册appid AccessTokenContainer.RegisterAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppSecret); JsApiTicketContainer.RegisterAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppSecret); #endregion #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHellp V1"); c.DocumentTitle = "Api帮助文档"; }); #endregion }
public override IApplicationBuilder UseXncfModule(IApplicationBuilder app, IRegisterService registerService) { //注册微信 Senparc.Weixin.WeixinRegister.UseSenparcWeixin(null, null, senparcSetting: null); try { //未安装数据库表的情况下可能会出错,因此需要try using (var scope = app.ApplicationServices.CreateScope()) { var allMpAccount = GetAllMpAccounts(scope.ServiceProvider); //批量自动注册公众号 foreach (var mpAccount in allMpAccount) { Task.Factory.StartNew(async() => { await AccessTokenContainer.RegisterAsync(mpAccount.AppId, mpAccount.AppSecret, $"{mpAccount.Name}-{mpAccount.Id}"); }); //TODO:更多执行过程中的动态注册 } } } catch { } //app.UseSwagger(); //app.UseSwaggerUI(c => //{ // //c.DocumentTitle = "Senparc Weixin SDK Demo API"; // c.InjectJavascript("/lib/jquery/dist/jquery.min.js"); // c.InjectJavascript("/js/swagger.js"); // //c.InjectJavascript("/js/tongji.js"); // c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); // foreach (var neucharApiDocAssembly in WeixinApiService.WeixinApiAssemblyCollection) // { // //TODO:真实的动态版本号 // var verion = WeixinApiService.WeixinApiAssemblyVersions[neucharApiDocAssembly.Key]; //neucharApiDocAssembly.Value.ImageRuntimeVersion; // var docName = WeixinApiService.GetDocName(neucharApiDocAssembly.Key); // //Console.WriteLine($"\tAdd {docName}"); // c.SwaggerEndpoint($"/swagger/{docName}/swagger.json", $"{neucharApiDocAssembly.Key} v{verion}"); // } //}); return(base.UseXncfModule(app, registerService)); }
public static IApplicationBuilder UserWork(this IApplicationBuilder app, IHostEnvironment env) { var register = Senparc.CO2NET.AspNet.RegisterServices.RegisterService.Start(env, senparcSetting).UseSenparcGlobal(); register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);//.RegisterWorkAccount(senparcWeixinSetting.Value, "企业微信"); var workSetting = app.ApplicationServices.GetService <IOptions <WorkSetting> >().Value; workSetting.ContactsAccessTokenKey = AccessTokenContainer.BuildingKey(workSetting.CorpId, workSetting.ContactsSecret); AccessTokenContainer.RegisterAsync(workSetting.CorpId, workSetting.ContactsSecret, "Contacts"); workSetting.MsgAccessTokenKey = AccessTokenContainer.BuildingKey(workSetting.CorpId, workSetting.MsgSecret); AccessTokenContainer.RegisterAsync(workSetting.CorpId, workSetting.MsgSecret, "Msg"); workSetting.LoginAccessTokenKey = AccessTokenContainer.BuildingKey(workSetting.CorpId, workSetting.LoginSecret); AccessTokenContainer.RegisterAsync(workSetting.CorpId, workSetting.LoginSecret, "Login"); return(app); }
/// <summary> /// 获取token(无缓存) /// </summary> /// <returns></returns> public string GetAccessToken(string appid = "") { if (appid == "") { appid = _senparcWeixinSetting.WeixinAppId; } //根据appId判断获取 if (!AccessTokenContainer.CheckRegistered(_senparcWeixinSetting.WeixinAppId)) //检查是否已经注册 { //如果没有注册则进行注册 AccessTokenContainer.RegisterAsync(_senparcWeixinSetting.WeixinAppId, _senparcWeixinSetting.WeixinAppSecret); } return(AccessTokenContainer.GetAccessToken(appid)); }
protected void Application_Start() { var isGLobalDebug = true; //设置全局 Debug 状态 var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug); var register = RegisterService.Start(senparcSetting).UseSenparcGlobal(); //CO2NET全局注册,必须! var isWeixinDebug = true; //设置微信 Debug 状态 var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug); register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);////微信全局注册,必须! AccessTokenContainer.RegisterAsync("wxad6fecee3bf4ba2f", "f2b4532be0ba85edee3425bfa86f2187", "微信cjj小程序"); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);//MVC 2nd BundleConfig.RegisterBundles(BundleTable.Bundles); }
public IActionResult Auth(string code, string state) { AccessTokenContainer.RegisterAsync(_wxSetting.WeixinAppId, _wxSetting.WeixinAppSecret, "doctor_platform"); string state1 = IdHelper.ObjectId(); //随机数,用于识别请求可靠性 HttpContext.Session.SetString("State", state1); //储存随机数到Session string signUrl = Request.AbsoluteUri(); // LoggerHelper.Info(signUrl); // MemoryCacheHelper.Set("test", "nihao", TimeSpan.FromMinutes(1)); // var keys= MemoryCacheHelper.GetCacheKeys(); if (!string.IsNullOrEmpty(code)) { var result = OAuthApi.GetAccessToken(_wxSetting.WeixinAppId, _wxSetting.WeixinAppSecret, code); if (result.errcode != ReturnCode.请求成功) { return(Content("错误:" + result.errmsg)); } //LoggerHelper.Info(result.openid); //尝试获取用户信息 //OAuthUserInfo userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid); //string json = userInfo.ToJson(); //LoggerHelper.Info(json); //Task.Factory.StartNew(() => GetUserInfo(result.access_token, result.openid)); string key = "{access_token}:wxtoken"; var redisClient = RedisFactory.GetRedisClient(); redisClient.Set(key, result, result.expires_in); RequestHelper.SetOpenId(result.openid, result.expires_in); string homeUrl = $"/wechat/index.html?openId={result.openid}"; return(Redirect(homeUrl)); } else { // signUrl = signUrl + "/WxExpert/Index";snsapi_userinfo snsapi_base var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", _wxSetting.WeixinAppId, signUrl.UrlEncode(), state1); return(Redirect(url)); } }
/// <summary> /// 启动应用程序 /// </summary> protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // 开启Log4Net日志配置 LogFactory.LogFactoryConfig(); //注册定时作业任务 SystemTask.PublicSystemTask t = new SystemTask.PublicSystemTask(); t.StartUp(); #if 使用RegisterServices方式注册微信 //设置全局 Debug 状态 var isGLobalDebug = false; //全局设置参数,将被储存到 Senparc.CO2NET.Config.SenparcSetting var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug); //也可以通过这种方法在程序任意位置设置全局 Debug 状态: //Senparc.CO2NET.Config.IsDebug = isGLobalDebug; //CO2NET 全局注册,必须!! IRegisterService register = RegisterService.Start(senparcSetting).UseSenparcGlobal(); //--------注册公众号-------------- //设置微信 Debug 状态 var isWeixinDebug = true; //全局设置参数,将被储存到 Senparc.Weixin.Config.SenparcWeixinSetting var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug); //微信全局注册,必须!! register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting).RegisterMpAccount(senparcWeixinSetting, "我的公众号名称"); //可以在程序任意地方注册公众号或小程序: //AccessTokenContainer.Register(weixin.T_AppId, weixin.T_AppSecret, weixin.T_WxName); WxBaseConfigApp app = new WxBaseConfigApp(); var weixin = app.GetDefaultConfig(); AccessTokenContainer.RegisterAsync(weixin.AppId, weixin.AppSecret, weixin.WxName); #endif }
/// <summary> /// /// </summary> protected void Application_Start() { AreaRegistration.RegisterAllAreas(); //var container = new Container(); //GlobalConfiguration.Configuration.DependencyResolver = // new SimpleInjectorWebApiDependencyResolver(container); GlobalConfiguration.Configure(WebApiConfig.Register); // FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var isGLobalDebug = true; //设置全局 Debug 状态 var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug); var register = RegisterService.Start(senparcSetting).UseSenparcGlobal(); //CO2NET全局注册,必须! var isWeixinDebug = true; //设置微信 Debug 状态 var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug); register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);////微信全局注册,必须 AccessTokenContainer.RegisterAsync(WXController.AppId, "5e6bc09d33684d9c41dccb6c8eec230b"); }
public async Task <ActionResult> BindingUser(LoginModel model, string weChatSessionID) { if (ModelState.IsValid) { if (userService.ValidateUser(model.UserName, model.Password)) { string openId = encryptionService.Decrypt(weChatSessionID, appSecret); await AccessTokenContainer.RegisterAsync(appId, appSecret); var memberToGroupResult = GroupsApi.MemberUpdate(appId, openId, 100); if (memberToGroupResult.errcode == 0) { User user = userService.GetUser(model.UserName); user.WeChatOpenID = openId; userService.UpdateUser(user); return(View("MessagePage", new MessagePageModel { Title = "绑定成功", Message = "您已成功绑定零度云账号。" })); } else { ModelState.AddModelError(string.Empty, "指定用户分组失败"); } } else { ModelState.AddModelError(string.Empty, Resources.InvalidUserNameOrPassword); } } ViewBag.WeChatSessionID = weChatSessionID; return(View("BindingUserLogin", model)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Use(next => context => { context.Request.EnableBuffering(); return(next(context)); }); //app.UseMiddleware<TokenAuth>(); app.UseHttpsRedirection(); app.UseRouting(); #region 配置跨域 app.UseCors("allCors"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.Map("/", context => { context.Response.Redirect("/swagger"); return(Task.CompletedTask); }); }); #endregion #region 微信模块 // 启动 CO2NET 全局注册,必须! IRegisterService register = RegisterService.Start(senparcSetting.Value) .UseSenparcGlobal(false, null); //开始注册微信信息,必须! register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value); //全局注册appid AccessTokenContainer.RegisterAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppSecret); JsApiTicketContainer.RegisterAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppSecret); //小程序 AccessTokenContainer.RegisterAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WxOpenAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WxOpenAppSecret); JsApiTicketContainer.RegisterAsync(Senparc.Weixin.Config.SenparcWeixinSetting.WxOpenAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WxOpenAppSecret); #endregion #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHellp V1"); c.DocumentTitle = "Api帮助文档"; }); #endregion #region 配置静态文件路径 //获取当前程序运行的路径 dynamic type = new Program().GetType(); string basePath = Path.GetDirectoryName(type.Assembly.Location); string StaticFilePath = Path.Combine(basePath, "StaticFiles"); app.UseStaticFiles(new StaticFileOptions { //配置除了默认的wwwroot文件中的静态文件以外的文件夹 提供 Web 根目录外的文件 经过此配置以后,就可以访问StaticFiles文件下的文件 FileProvider = new PhysicalFileProvider(StaticFilePath), RequestPath = "/StaticFiles", }); #endregion #region 使用SignalR //使用 SignalR app.UseEndpoints(endpoints => { endpoints.MapHub <YvanHub>("/yvanHub"); }); #endregion }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region 读取静态文件 app.UseStaticFiles(); //app.UseStaticFiles(new StaticFileOptions //{ // FileProvider = new PhysicalFileProvider( // Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")), // RequestPath = "/StaticFiles" //}); #endregion 读取静态文件 app.UseCookiePolicy(); //使用缓存 app.UseResponseCaching(); //注册Session服务 app.UseSession(); #region 使用跨域 app.UseCors("Cors"); #endregion 使用跨域 #region 使用swagger //使用swagger app.UseSwagger(); //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); //option.SwaggerEndpoint("/swagger/v2/swagger.json", "API V1"); option.RoutePrefix = "swagger"; option.DocumentTitle = "sparktodo API"; }); #endregion 使用swagger #region 使用Ids服务 app.UseIdentityServer(); #endregion 使用Ids服务 //使用https app.UseHttpsRedirection(); //默认网站打开跳转静态地址 if (!string.IsNullOrEmpty(Appsettings.GetSectionValue("AppSettings:DefaultHtml"))) { DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add(Appsettings.GetSectionValue("AppSettings:DefaultHtml")); app.UseDefaultFiles(defaultFilesOptions); } app.UseStaticFiles(); app.UseRouting(); //app.UseMvc(); #region Senparc.Weixin SDK // 启动 CO2NET 全局注册,必须! 关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore3/Startup.cs var registerService = app.UseSenparcGlobal(env, senparcSetting.Value, globalRegister => { #region CO2NET 全局配置 #region APM 系统运行状态统计记录配置 //测试APM缓存过期时间(默认情况下可以不用设置) Senparc.CO2NET.APM.Config.EnableAPM = true;//默认已经为开启,如果需要关闭,则设置为 false Senparc.CO2NET.APM.Config.DataExpire = TimeSpan.FromMinutes(60); #endregion APM 系统运行状态统计记录配置 #endregion CO2NET 全局配置 }, true) //使用 Senparc.Weixin SDK .UseSenparcWeixin(senparcWeixinSetting.Value, weixinRegister => { #region 微信相关配置 /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ #region 注册公众号或小程序(按需) //注册公众号(可注册多个) -- DPBMARK MP weixinRegister .RegisterMpAccount(senparcWeixinSetting.Value, "公众号") // DPBMARK_END //除此以外,仍然可以在程序任意地方注册公众号或小程序: //AccessTokenContainer.Register(appId, appSecret, name);//命名空间:Senparc.Weixin.MP.Containers #endregion 注册公众号或小程序(按需) #region 注册微信支付(按需) -- DPBMARK TenPay //注册最新微信支付版本(V3)(可注册多个) .RegisterTenpayV3(senparcWeixinSetting.Value, "公众号") //记录到同一个 SenparcWeixinSettingItem 对象中 #endregion 注册微信支付(按需) -- DPBMARK TenPay ; /* 微信配置结束 */ #endregion 微信相关配置 }); AccessTokenContainer.RegisterAsync(senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret); #endregion Senparc.Weixin SDK #region 授权认证ids app.UseAuthentication(); //认证 app.UseAuthorization(); //授权 #endregion 授权认证ids app.UseMiddleware <Middleware.AskMiddleWare>(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //注册socket app.Map("/socket", WebSocketHelper.Map); }