Exemplo n.º 1
0
 public OAuthUserInfo GetAuthInfo(OAuthAccessTokenResult token)
 {
     try
     {
         var appid     = _settingManager.GetSettingValue(AppSettings.Weixin.AppId);
         var appsecret = _settingManager.GetSettingValue(AppSettings.Weixin.AppSecret);
         if (!AccessTokenContainer.CheckRegistered(appid))
         {
             AccessTokenContainer.Register(appid, appsecret);
         }
         var ret = Senparc.Weixin.MP.AdvancedAPIs.OAuthApi.GetUserInfo(token.access_token, token.openid);
         return(ret);
     }
     catch (Exception ex)
     {
         _logger.Error("获取微信授权信息", ex);
         return(null);
     }
 }
Exemplo n.º 2
0
        public WeChatAuthenticationOptions(string appId, string appSecret,
                                           ApplicationTypes appType, ScopeTypes scopeTypes,
                                           bool useUnionIdAsIdentity = false, bool isLoadUserInfo = false)
            : base(GetAuthenticationType(appType))

        {
            Caption               = GetAuthenticationType(appType);
            CallbackPath          = new PathString(CALLBACK_PATH);
            AuthenticationMode    = AuthenticationMode.Passive;
            BackchannelTimeout    = TimeSpan.FromSeconds(CALLBACK_TIMEOUT_SECOUNDS);
            AuthorizationEndpoint = GetAuthorizationEndpoint(appType);
            AppId                = appId;
            AppSecret            = appSecret;
            ScopeType            = scopeTypes;
            UseUnionIdAsIdentity = useUnionIdAsIdentity;
            IsLoadUserInfo       = isLoadUserInfo;

            AccessTokenContainer.Register(AppId, AppSecret);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            //微信查询用户信息
            string appId     = "";
            string appSecret = "";
            string openId    = "";

            //检查是否已经注册
            if (!AccessTokenContainer.CheckRegistered(appId))
            {
                //如果没有注册则进行注册,2小时token过期
                AccessTokenContainer.Register(appId, appSecret);
            }
            string token = AccessTokenContainer.GetAccessToken(appId);
            //如果appId,appSecret和openId不配套,报错:微信请求发生错误!错误代码:40003,说明:invalid openid hint: [2BZbQA00621527]
            var info = UserApi.Info(token, openId);

            info = UserApi.Info(appId, openId);
        }
        public void GetTokenResultTest()
        {
            //注册
            AccessTokenContainer.Register(base._corpId, base._corpSecret);

            //模拟多线程获取
            List <string> accessTokenList = new List <string>();

            int[] treads = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            Parallel.For(0, treads.Length, (i) =>
            {
                var accessTokenResult = AccessTokenContainer.GetTokenResult(base._corpId, base._corpSecret, false);
                accessTokenList.Add(accessTokenResult.access_token);//同时多次获取
            });

            Assert.AreEqual(treads.Length, accessTokenList.Count()); //只存在同一个Token,实际不会多次刷新
            Assert.AreEqual(1, accessTokenList.Distinct().Count());  //只存在同一个Token,实际不会多次刷新
            Console.WriteLine(accessTokenList[0]);
        }
Exemplo n.º 5
0
 /// <summary>
 /// 得到接口调用凭证---Token;,参数可在开发者配置环境中找到;
 /// </summary>
 /// <param name="appId">用户唯一凭证id</param>
 /// <param name="appSecret">用户的密钥</param>
 /// <returns></returns>
 public ActionResult GetToken(string appId, string appSecret)
 {
     try
     {
         if (!AccessTokenContainer.CheckRegistered(appId))
         {
             AccessTokenContainer.Register(appId, appSecret);
         }
         var result = AccessTokenContainer.GetAccessToken(appId);
         //也可以直接一步到位:
         //var result = AccessTokenContainer.TryGetToken(appId, appSecret);
         return(Json(result, JsonRequestBehavior.AllowGet));
     }
     catch (Exception)
     {
         //TODO:为简化代码,这里不处理异常(如Token过期)
         return(Json(new { error = "执行过程发生错误!" }, JsonRequestBehavior.AllowGet));
     }
 }
Exemplo n.º 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "企业微信 API", Version = "v1"
                });
                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "Work.AspNetCore.xml");
                c.IncludeXmlComments(xmlPath);
            });


            //注册微信应用信息
            AccessTokenContainer.Register("ww13e9492fe4b02153", "dsq1HWzRkcJ27VxrC8gRsTXu17Kq39LlJIY5kk3w-g4", "企业微信(开发)");
        }
 public string GetTokenByAppId(string appId, string appSecret)
 {
     try
     {
         if (!AccessTokenContainer.CheckRegistered(appId))
         {
             AccessTokenContainer.Register(appId, appSecret);
         }
         var result = AccessTokenContainer.GetTokenResult(appId); //CommonAPIs.CommonApi.GetToken(appId, appSecret);
         //也可以直接一步到位:
         //var result = AccessTokenContainer.TryGetToken(appId, appSecret);
         Loger.Current.Write("WeiXinService.GetToken() accessToken=" + result.access_token);
         return(result.access_token);
     }
     catch (Exception)
     {
         return("error");
     }
 }
Exemplo n.º 8
0
 public string GetAuthorizeUrl(string redirect)
 {
     try
     {
         var appid     = _settingManager.GetSettingValue(AppSettings.Weixin.AppId);
         var appsecret = _settingManager.GetSettingValue(AppSettings.Weixin.AppSecret);
         if (!AccessTokenContainer.CheckRegistered(appid))
         {
             AccessTokenContainer.Register(appid, appsecret);
         }
         var ret = Senparc.Weixin.MP.AdvancedAPIs.OAuthApi.GetAuthorizeUrl(appid, redirect, "0", OAuthScope.snsapi_userinfo);
         return(ret);
     }
     catch (Exception ex)
     {
         _logger.Error("获取微信授权地址", ex);
         return("");
     }
 }
Exemplo n.º 9
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            IRegisterService register = RegisterService.Start(env, senparcSetting.Value).UseSenparcGlobal(); // 启动 CO2NET 全局注册,必须!

            register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value);                     //微信全局注册,必须!
            AccessTokenContainer.Register(Configuration["wechat:appid"], Configuration["wechat:appSecret"]);
            app.UseHealthChecks("/health");

            app.UseDeveloperExceptionPage();

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseOpenApi();

            app.UseSwaggerUi3();

            app.UseMvc();
        }
Exemplo n.º 10
0
        public OAuthAccessTokenResult GetOauthResult(string code)
        {
            try
            {
                var appid     = _settingManager.GetSettingValue(AppSettings.Weixin.AppId);
                var appsecret = _settingManager.GetSettingValue(AppSettings.Weixin.AppSecret);
                if (!AccessTokenContainer.CheckRegistered(appid))
                {
                    AccessTokenContainer.Register(appid, appsecret);
                }
                var ret = Senparc.Weixin.MP.AdvancedAPIs.OAuthApi.GetAccessToken(appid, appsecret, code);

                return(ret);
            }
            catch (Exception ex)
            {
                _logger.Error("获取微信授权Token", ex);
                return(null);
            }
        }
Exemplo n.º 11
0
        public void Configuration(IAppBuilder app)
        {
            app.UseAbp();



            app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            if (IsTrue("ExternalAuth.Facebook.IsEnabled"))
            {
                app.UseFacebookAuthentication(CreateFacebookAuthOptions());
            }

            if (IsTrue("ExternalAuth.Twitter.IsEnabled"))
            {
                app.UseTwitterAuthentication(CreateTwitterAuthOptions());
            }

            if (IsTrue("ExternalAuth.Google.IsEnabled"))
            {
                app.UseGoogleAuthentication(CreateGoogleAuthOptions());
            }

            app.MapSignalR();

            AccessTokenContainer.Register(Common.CommonConst.AppID, Common.CommonConst.AppSecret);

            //ENABLE TO USE HANGFIRE dashboard (Requires enabling Hangfire in SShouWebModule)
            //app.UseHangfireDashboard("/hangfire", new DashboardOptions
            //{
            //    Authorization = new[] { new AbpHangfireAuthorizationFilter() } //You can remove this line to disable authorization
            //});
        }
Exemplo n.º 12
0
        private string souideaKey = WebConfigurationManager.AppSettings["WeixinAgentWeiweihiKey"]; //SouideaKey专门用于对接www.souidea.com平台,获取方式见:http://www.souidea.com/ApiDocuments/Item/25#51
#endif

        public CustomMessageHandler(Stream inputStream, string token, string appid, string secrect, int maxRecordCount = 0)
            : base(inputStream, maxRecordCount)
        {
            //这里设置仅用于测试,实际开发可以在外部更全局的地方设置,
            //比如MessageHandler<MessageContext>.GlobalWeixinContext.ExpireMinutes = 3。
            WeixinContext.ExpireMinutes = 3;

            try
            {
                if (!AccessTokenContainer.CheckRegistered(appid))
                {
                    AccessTokenContainer.Register(appid, secrect);
                }

                _tokenRes = AccessTokenContainer.GetTokenResult(appid); //CommonAPIs.CommonApi.GetToken(appId, appSecret);
            }
            catch
            {
                FileLogUtility.Inform(string.Format("获取到 token 失败, appid: {0},secret: {1}。", appid, secrect));
            }
        }
Exemplo n.º 13
0
        private void InitAppKey()
        {
            if (new[] { appId, secret }.Any(string.IsNullOrEmpty))
            {
                lock (initLock)
                {
                    if (new[] { appId, secret }.Any(string.IsNullOrEmpty))
                    {
                        var account = YunClient.Instance.Execute(new GetWxAccountsRequest {
                            PageNum = 1, PageSize = 1
                        }).Accounts[0];
                        appId          = account.AppId;
                        secret         = account.Secret;
                        wxtoken        = account.AccessToken;
                        encodingAESKey = account.Encodingaeskey;

                        AccessTokenContainer.Register(appId, secret);
                    }
                }
            }
        }
Exemplo n.º 14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
                              IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                // Browser Link is not compatible with Kestrel 1.1.0
                // For details on enabling Browser Link, see https://go.microsoft.com/fwlink/?linkid=840936
                // app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

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

            #region 微信相关

            //注册微信
            AccessTokenContainer.Register(senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret);

            //Senparc.Weixin SDK 配置
            Senparc.Weixin.Config.DefaultSenparcWeixinSetting = senparcWeixinSetting.Value;

            #endregion
        }
Exemplo n.º 15
0
        public ActionResult SendText(FormCollection collection)
        {
            string text = collection["text"];

            Response.Write("你发送消息" + text);
            AccessTokenContainer.Register(SystemContext.Instance.WeiXinAppInfo.AppID, SystemContext.Instance.WeiXinAppInfo.AppSecret);
            var accessToken = AccessTokenContainer.GetAccessToken(SystemContext.Instance.WeiXinAppInfo.AppID);

            try
            {
                var result = Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(accessToken, SystemContext.Instance.WeiXinAppInfo.OpenID, text);
            }
            catch (ErrorJsonResultException ex)
            {
                Response.Write("发送失败");

                return(View());
            }

            Response.Write("发送成功");
            return(View());
        }
Exemplo n.º 16
0
        public IEnumerable <string> Get()
        {
            try
            {
                AccessTokenContainer.Register("wx4f8e94b7a153ff43", "700fcec799b8ff8f1463eb31585eafbc");

                var accessToken = AccessTokenContainer.GetAccessToken("wx4f8e94b7a153ff43");

                Card_GrouponData data1 = new Card_GrouponData()
                {
                    base_info   = _BaseInfo,
                    deal_detail = "测试"
                };

                //string json = JsonConvert.SerializeObject(card_BaseInfoBase);

                var result1 = CardApi.CreateCard(accessToken, data1);

                var data = new Card_MemberCardData()
                {
                    base_info         = _BaseInfo,
                    supply_bonus      = true,
                    supply_balance    = false,
                    prerogative       = "123123",
                    bind_old_card_url = "www.daidu.com",
                    wx_activate       = true
                };

                var result = CardApi.CreateCard(accessToken, data);
            }
            catch (Exception ex)
            {
                throw;
            }



            return(new string[] { "value1", "value2" });
        }
Exemplo n.º 17
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //... register ...

            //设置全局 Debug 状态
            var isGLobalDebug = true;
            //全局设置参数,将被储存到 Senparc.CO2NET.Config.SenparcSetting
            var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug);

            //CO2NET 全局注册,必须!!
            IRegisterService register = RegisterService.Start(senparcSetting).UseSenparcGlobal();

            /* 微信配置开始
             * 建议按照以下顺序进行注册
             */

            //设置微信 Debug 状态
            var isWeixinDebug = true;
            //全局设置参数,将被储存到 Senparc.Weixin.Config.SenparcWeixinSetting
            var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug);

            //也可以通过这种方法在程序任意位置设置微信的 Debug 状态:
            //Senparc.Weixin.Config.IsDebug = isWeixinDebug;

            //微信全局注册,必须!!
            register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);

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

            Database.SetInitializer <WeChatHelloWorld1Context>(null);
        }
Exemplo n.º 18
0
Arquivo: WxFO.cs Projeto: Luyingjin/Qy
        /// <summary>
        /// 获取公众号认证令牌
        /// </summary>
        /// <param name="QyID"></param>
        /// <returns></returns>
        public string GetAccessToken(string QyID, bool GetNewToken = false)
        {
            var token = "";

            //LogWriter.Info(string.Format("qyid为{0}的静默授权在通过code获取token时异常,原因:{1}", corpid, result.errmsg));
            LogWriter.Info("GetAccessToken:1");
            var account = CacheHelper.Get(string.Format("WxAccount{0}", QyID)) as QyAccount;

            if (account == null)
            {
                LogWriter.Info("GetAccessToken:2");
                account = entities.QyAccount.Where(c => c.ID == QyID && c.IsDelete == 0).FirstOrDefault();
                CacheHelper.Set(string.Format("WxAccount{0}", QyID), account);
            }
            if (account != null)
            {
                LogWriter.Info(GetNewToken + "-GetAccessToken:3-" + account.CorpID + "@" + account.CorpSecret);
                if (!AccessTokenContainer.CheckRegistered(account.CorpID + "@" + account.CorpSecret) || GetNewToken)
                {
                    LogWriter.Info("GetAccessToken:4");
                    AccessTokenContainer.Register(account.CorpID, account.CorpSecret);
                }
                var result = AccessTokenContainer.GetTokenResult(account.CorpID + "@" + account.CorpSecret, GetNewToken);
                LogWriter.Info("key=" + account.CorpID + "@" + account.CorpSecret + GetNewToken + "GetAccessToken:5-" + JsonHelper.ToJson(result));
                if (result.access_token != account.AccessToken)
                {
                    LogWriter.Info("GetAccessToken:6");
                    account                       = entities.QyAccount.Where(c => c.ID == QyID && c.IsDelete == 0).FirstOrDefault();
                    account.AccessToken           = result.access_token;
                    account.AccessTokenExpireTime = DateTime.Now.AddSeconds(result.expires_in);
                    account.ModifyDate            = DateTime.Now;
                    entities.SaveChanges();
                    CacheHelper.Set(string.Format("WxAccount{0}", QyID), account);
                }
                token = account.AccessToken;
            }
            return(token);
        }
Exemplo n.º 19
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            var appid  = ConfigurationManager.AppSettings["AppID"];
            var secret = ConfigurationManager.AppSettings["AppSecret"];

            AccessTokenContainer.Register(appid, secret);

            var entities  = new MkmEntities();
            var allStatus = entities.SystemStatus.ToList();

            SystemStaticData.UserStatus           = allStatus.Where(p => p.SystemStatusCategoryId == (int)StatusCategory.User);
            SystemStaticData.AdvStatus            = allStatus.Where(p => p.SystemStatusCategoryId == (int)StatusCategory.Adv);
            SystemStaticData.AdvRewardStatus      = allStatus.Where(p => p.SystemStatusCategoryId == (int)StatusCategory.AdvReward);
            SystemStaticData.SystemIncomeStatus   = allStatus.Where(p => p.SystemStatusCategoryId == (int)StatusCategory.SystemIncome);
            SystemStaticData.RechargeRewardStatus = allStatus.Where(p => p.SystemStatusCategoryId == (int)StatusCategory.RechargeReward);
        }
Exemplo n.º 20
0
        private static async Task GetAllUsers()
        {
            using (HttpClient client = new HttpClient())
            {
                var appId     = "";
                var appSecret = "";
                //起始位置,为空则从头开始查询
                var next_openid = "";
                //注册一次即可
                AccessTokenContainer.Register(appId, appSecret);
                var    token = AccessTokenContainer.GetAccessToken(appId);
                string url   = string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}", token);
                if (!string.IsNullOrEmpty(next_openid))
                {
                    url += "&next_openid=" + next_openid;
                }
                var response = await client.GetAsync(url);

                var resultStr = await response.Content.ReadAsStringAsync();

                GetAllUsersOutput result = JsonConvert.DeserializeObject <GetAllUsersOutput>(resultStr);
            }
        }
Exemplo n.º 21
0
        public static string certPwd  = "";                                     //GetKeyValue("mchid");//证书密码  及   商户平台商户号  初始密码  可以修改
        public ActionResult WeChat()
        {
            HttpContext.Response.ContentType = "text/plain";
            Appsecret = sysConfigs.GetKeyValue("appsecret");
            AppId     = sysConfigs.GetKeyValue("appid");
            apisecret = sysConfigs.GetKeyValue("apisecret");
            URLToken  = sysConfigs.GetKeyValue("token");
            try
            {
                if (HttpContext.Request.HttpMethod.ToUpper() == "GET")
                {
                    if (!AccessTokenContainer.CheckRegistered(AppId))
                    {
                        AccessTokenContainer.Register(AppId, Appsecret);
                    }

                    Auth(); //微信接入的测试  成为开发者第一步
                }
                if (HttpContext.Request.HttpMethod.ToUpper() == "POST")
                {
                    if (!AccessTokenContainer.CheckRegistered(AppId))
                    {
                        AccessTokenContainer.Register(AppId, Appsecret);
                    }



                    //responseMsg();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("一般处理程序入口错误:", ex);
            }

            return(Content(""));
        }
Exemplo n.º 22
0
        public ActionResult BindingUser(LoginModel model, string weChatSessionID)
        {
            if (ModelState.IsValid)
            {
                if (userService.ValidateUser(model.UserName, model.Password))
                {
                    string openId = encryptionService.Decrypt(weChatSessionID, appSecret);

                    AccessTokenContainer.Register(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));
        }
Exemplo n.º 23
0
        public GzhCfg(XmlNode node)
        {
            this._node = node;

            this.appName   = DomUtil.GetAttr(node, "appName");
            this.appNameCN = DomUtil.GetAttr(node, "appNameCN");

            this.appId          = DomUtil.GetAttr(node, "appId");
            this.secret         = DomUtil.GetAttr(node, "secret");
            this.token          = DomUtil.GetAttr(node, "token");
            this.encodingAESKey = DomUtil.GetAttr(node, "encodingAESKey");
            if (this.appName == "")
            {
                throw new Exception("尚未定义公众号名称");
            }

            string isDefaultText = DomUtil.GetAttr(node, "isDefault").ToLower();

            if (isDefaultText == "true")
            {
                isDefault = true;
            }

            //// 模板id,todo 模板名称有空变成常量,与配置文件对应
            //this.Template_Bind_Id = this.GetTemplateId(node, "Bind");
            //this.Template_UnBind_Id = this.GetTemplateId(node, "UnBind");
            //this.Template_Borrow_Id = this.GetTemplateId(node, "Borrow");
            //this.Template_Return_Id = this.GetTemplateId(node, "Return");
            //this.Template_Pay_Id = this.GetTemplateId(node, "Pay");
            //this.Template_CancelPay_Id = this.GetTemplateId(node, "CancelPay");
            //this.Template_Message_Id = this.GetTemplateId(node, "Message");
            //this.Template_Arrived_Id = this.GetTemplateId(node, "Arrived");
            //this.Template_CaoQi_Id = this.GetTemplateId(node, "CaoQi");

            //全局只需注册一次
            AccessTokenContainer.Register(this.appId, this.secret);
        }
Exemplo n.º 24
0
        public CommonApiTest()
        {
            if (_useRedis)
            {
                var redisConfiguration = "localhost:6379";
                RedisManager.ConfigurationOption = redisConfiguration;
                CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//Redis
            }

            //全局只需注册一次
            AccessTokenContainer.Register(_appId, _appSecret);

            ////注册小程序
            //if (!string.IsNullOrEmpty(_wxOpenAppId))
            //{
            //    AccessTokenContainer.Register(_wxOpenAppId, _wxOpenSecret);
            //}

            //ThreadUtility.Register();

            //v13.3.0之后,JsApiTicketContainer已经合并入AccessTokenContainer,已经不需要单独注册
            ////全局只需注册一次
            //JsApiTicketContainer.Register(_appId, _appSecret);
        }
Exemplo n.º 25
0
        public static void SendWeChatNotice(string openID, string formID, string data)
        {
            string appId     = "wxc7445db4fff61eb9";
            string appSecret = "4dcd295b0ec93878d52aa1d54e99aa50";

            //根据appId判断获取
            if (!AccessTokenContainer.CheckRegistered(appId))                                           //检查是否已经注册
            {
                AccessTokenContainer.Register(appId, appSecret);                                        //如果没有注册则进行注册
            }
            string        access_token = AccessTokenContainer.GetAccessTokenResult(appId).access_token; //AccessToken
            string        tagUrl       = string.Format("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={0}", access_token);
            StringBuilder paramsStr    = new StringBuilder();

            paramsStr.Append("{");
            paramsStr.Append("\"touser\": \"" + openID + "\",");
            paramsStr.Append("\"template_id\": \"" + WeChatTemplateID + "\",");
            paramsStr.Append("\"page\": \"" + WeChatPage + "\",");
            paramsStr.Append("\"form_id\":\"" + formID + "\",");
            paramsStr.Append("\"data\":" + data);
            paramsStr.Append("}");
            string param  = paramsStr.ToString();
            string result = Method.PostMoths(tagUrl, param);
        }
        public void ContainerTest()
        {
            //注册
            AccessTokenContainer.Register(base._corpId, base._corpSecret);

            //获取Token完整结果(包括当前过期秒数)
            var tokenResult = AccessTokenContainer.GetTokenResult(base._corpId, base._corpSecret);

            Assert.IsNotNull(tokenResult);

            //只获取Token字符串
            var token = AccessTokenContainer.GetToken(base._corpId, base._corpSecret);

            Assert.AreEqual(tokenResult.access_token, token);

            //getNewToken
            {
                token = AccessTokenContainer.TryGetToken(base._corpId, base._corpSecret, false);
                Assert.AreEqual(tokenResult.access_token, token);

                token = AccessTokenContainer.TryGetToken(base._corpId, base._corpSecret, true);
                Assert.AreEqual(tokenResult.access_token, token);//现在微信服务器有AccessToken缓存,短时间内一致
            }
        }
Exemplo n.º 27
0
        public static string certPwd  = "";                                     //GetKeyValue("mchid");//证书密码  及   商户平台商户号  初始密码  可以修改
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Appsecret = WeChatConfig.GetKeyValue("appsecret");
            AppId     = WeChatConfig.GetKeyValue("appid");
            apisecret = WeChatConfig.GetKeyValue("apisecret");
            URLToken  = WeChatConfig.GetKeyValue("token");
            try
            {
                if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
                {
                    if (!AccessTokenContainer.CheckRegistered(AppId))
                    {
                        AccessTokenContainer.Register(AppId, Appsecret);
                    }

                    Auth(); //微信接入的测试  成为开发者第一步
                }
                if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
                {
                    if (!AccessTokenContainer.CheckRegistered(AppId))
                    {
                        AccessTokenContainer.Register(AppId, Appsecret);
                    }



                    responseMsg();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("一般处理程序入口错误:", ex);
            }
            // context.Response.Write("Hello World");
        }
Exemplo n.º 28
0
        //OPENTM207622205

        /// <summary>
        /// 推送提醒
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="title">系统检测到您昨日未读经</param>
        /// <param name="content">您昨日未读书,请您及时补读</param>
        /// <param name="time">昨日</param>
        /// <param name="msg">点击打开账户,补读未读经</param>
        /// <param name="link">http://www.yuedujing.com/wx_login.aspx</param>
        /// <returns></returns>
        public bool SendRemind(string openid, string title, string content, string time, string msg, string link)
        {
            try
            {
                string templateId = "R-Ply-04h1bSfrtOcGZtetWcblblPAlgW9JmpBaFfeM";

                if (!AccessTokenContainer.CheckRegistered(appId))                                    //检查是否已经注册
                {
                    AccessTokenContainer.Register(appId, appSecret);                                 //如果没有注册则进行注册
                }
                string access_token = AccessTokenContainer.GetAccessTokenResult(appId).access_token; //AccessToken
                string link_url     = link;
                var    data         = new TemplateMsg()
                {
                    first    = new TemplateDataItem(title, "#000000"),
                    keyword1 = new TemplateDataItem(content, "#000000"),
                    keyword2 = new TemplateDataItem(time, "#000000"),
                    remark   = new TemplateDataItem(msg, "#0077ff")
                };

                //发送成功
                if (Send(openid, templateId, link_url, data))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteDebugLog("[wx push msg]:" + ex.Message + "," + ex.Source);
                return(false);
            }
        }
Exemplo n.º 29
0
        public object Do_Login(object param)
        {
            LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(param.ToString());

            if (loginParam == null)
            {
                throw new ApiException(CodeMessage.InvalidParam, "InvalidParam");
            }

            var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code);

            if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功)
            {
                var manager = Senparc.Weixin.Cache.Redis.RedisManager.Manager;

                AccessTokenContainer.Register(Global.APPID, Global.APPSECRET);
                var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key);
                return(new { sessionId = sessionBag.Key });
            }
            else
            {
                throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg);
            }
        }
Exemplo n.º 30
0
        public string GetHeadImage(string openid, string defaultImage)
        {
            var appid     = _settingManager.GetSettingValue(AppSettings.Weixin.AppId);
            var appsecret = _settingManager.GetSettingValue(AppSettings.Weixin.AppSecret);

            if (!AccessTokenContainer.CheckRegistered(appid))
            {
                AccessTokenContainer.Register(appid, appsecret);
            }
            var userInfo = UserApi.Info(appid, openid);

            if (userInfo == null)
            {
                return(defaultImage);
            }

            string image = userInfo.headimgurl;

            if (string.IsNullOrEmpty(image))
            {
                return(defaultImage);
            }
            return(image);
        }