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)); }
public async Task <APIResultDto> CreateMenu(GetMenuResultFull fullJson) { try { //GetMenuResultFull resultFull = Newtonsoft.Json.JsonConvert.DeserializeObject<GetMenuResultFull>(fullJson); //重新整理按钮信息 WxJsonResult result = null; IButtonGroupBase buttonGroup = null; buttonGroup = CommonApi.GetMenuFromJsonResult(fullJson, new ButtonGroup()).menu; var accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(AppId, AppSecret); result = CommonApi.CreateMenu(accessToken, buttonGroup); return(new APIResultDto() { Code = 0, Msg = "上传菜单成功", Data = result }); } catch (Exception ex) { return(new APIResultDto() { Code = 901, Msg = "更新菜单失败", Data = ex.Message }); } }
public async Task <(bool, string, string)> GetAccessTokenAsync(string mpAppId, string mpAppSecret) { var success = false; var errorMessage = string.Empty; string token = null; try { token = await AccessTokenContainer.TryGetAccessTokenAsync(mpAppId, mpAppSecret); success = true; } catch (ErrorJsonResultException ex) { if (ex.JsonResult.errcode == ReturnCode.调用接口的IP地址不在白名单中) { var startIndex = ex.JsonResult.errmsg.IndexOf("invalid ip ", StringComparison.Ordinal) + 11; var endIndex = ex.JsonResult.errmsg.IndexOf(" ipv6", StringComparison.Ordinal); var ip = ex.JsonResult.errmsg.Substring(startIndex, endIndex - startIndex); errorMessage = $"调用接口的IP地址不在白名单中,请进入微信公众平台,将本服务器的IP地址 {ip} 添加至白名单"; } else { errorMessage = $"API 调用发生错误:{ex.JsonResult.errmsg}"; } } catch (Exception ex) { errorMessage = $"执行过程发生错误:{ex.Message}"; } return(success, token, errorMessage); }
/// <summary> /// 活动开始,关注公众号全部用户发消息 /// </summary> /// <returns></returns> public async Task AllSendTemplateMessage() { try { var accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(mpAppId, mpAppSecret); var result = await Senparc.Weixin.MP.AdvancedAPIs.UserApi.GetAsync(accessToken, null); if (result.total > 0) { var msgData = new MPTemplateData("您好,您预约的实现吧!愿望君!活动已经开启,快来实现你的愿望吧~", "实现吧!2021愿望君!", $"{DateTime.Now.ToString("yyyy年MM月dd日")}", "快来前往月野兔星球小程序~", "点击即可立即进入哦~"); var miniProgram = new TemplateModel_MiniProgram() { appid = appId, pagepath = "pages/index/index" }; // 因为是同一个公众号,根据环境变量处理测试数据 if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") { var betaList = new List <string>() { "oHxnJwqEKSsUnMq8vpbwJQ3k5jYQ", //fly "oHxnJwuuMR3eZ04mhVcNLfY3Mouo", //LIsa "oHxnJwvwhG-hTcdfzWySqRkaqYkY", //鑫鑫 "oHxnJwl_xD09u_2hZB-Y5FiMrYWQ", //C. "oHxnJwpAl4RU7OLy6q1ZhQKbMbNo", //烟花 "oHxnJwqXoOrJw2hI3Z3FHZB1H0VM", //太阳女神 }; foreach (var openid in result.data.openid) { if (betaList.Where(e => e.Contains(openid)).Any()) // 测试白名单 { await Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessageAsync(accessToken, openid, MPTemplateID.mpStart, null, msgData, miniProgram); } } } else { foreach (var openid in result.data.openid) { await Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessageAsync(accessToken, openid, MPTemplateID.mpStart, null, msgData, miniProgram); } } } } catch (Exception ex) { Console.WriteLine(string.Concat("AllSendTemplateMessage:", ex.Message)); } }
public async Task <string> RefreshAccessToken() { string appId = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.General.AppId, InfrastructureSession.TenantId.Value); string secret = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.General.Secret, InfrastructureSession.TenantId.Value); string accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(appId, secret, true); return(accessToken); }
public void ContainerAsyncTest() { //注册 AccessTokenContainer.Register(base._appId, base._appSecret); //获取Token完整结果(包括当前过期秒数) DateTime dt1 = DateTime.Now; var tokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId).Result; DateTime dt2 = DateTime.Now; Assert.IsNotNull(tokenResult); Console.WriteLine(tokenResult.access_token); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); //只获取Token字符串 dt1 = DateTime.Now; var token = AccessTokenContainer.GetAccessTokenAsync(base._appId).Result; dt2 = DateTime.Now; Assert.AreEqual(tokenResult.access_token, token); Console.WriteLine(tokenResult.access_token); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); //getNewToken { dt1 = DateTime.Now; token = AccessTokenContainer.TryGetAccessTokenAsync(base._appId, base._appSecret, false).Result; dt2 = DateTime.Now; Assert.AreEqual(tokenResult.access_token, token); Console.WriteLine(tokenResult.access_token); Console.WriteLine("强制重新获取AccessToken"); dt1 = DateTime.Now; token = AccessTokenContainer.TryGetAccessTokenAsync(base._appId, base._appSecret, true).Result; dt2 = DateTime.Now; Assert.AreNotEqual(tokenResult.access_token, token);//如果微信服务器缓存,此处会相同 Console.WriteLine(tokenResult.access_token); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); } { tokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId).Result; Console.WriteLine("HashCode:{0}", tokenResult.GetHashCode()); dt1 = DateTime.Now; var allItems = AccessTokenContainer.GetAllItems(); dt2 = DateTime.Now; Assert.IsTrue(allItems.Count > 0); Assert.AreSame(tokenResult, allItems[0].AccessTokenResult);//证明缓存成功 Console.WriteLine("All Items:{0}", allItems.Count); Console.WriteLine("HashCode:{0}", allItems[0].AccessTokenResult.GetHashCode()); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); } }
private async Task <int> UniformSendMPTemplateAsync(int makeWishId, string mPTemplateID, int memberId = 0) { int resCode = 0; string pagepath = mPTemplateID == MPTemplateID.mpReserve ? string.Empty : $"pages/detail/index?wishId={makeWishId}"; string tOpenId = string.Empty; try { MPTemplateData tData = null; (tData, tOpenId) = await _activityApplication.GetWishOpenId(makeWishId, mPTemplateID, memberId); if (tData != null) { var accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(appId, appSecret); var msgData = new UniformSendData { touser = tOpenId, mp_template_msg = new Mp_Template_Msg { appid = mpAppId, template_id = mPTemplateID, miniprogram = new Miniprogram { appid = appId, pagepath = pagepath, }, data = tData } }; var result = await TemplateApi.UniformSendAsync(accessToken, msgData); resCode = 1; if (mPTemplateID == MPTemplateID.mpReserve) //预约提醒只发送一次,发送成功更新 { await _activityApplication.SaveMemberIsSend(memberId); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(string.Concat("mPTemplateID:", mPTemplateID, "----memberID:", memberId, "----openId:", tOpenId)); } return(resCode); }
/// <summary> /// 异步更新AccessToken /// </summary> /// <param name="getNewToken"></param> public static string GetTokenAsync(bool getNewToken = false) { //AccessTokenResult r = CommonApi.GetToken(Qyinfo.corpId, Qyinfo.corpSecret, "client_credential"); string strIp = CommonHelp.getIP(HttpContext.Current); string _username = CommonHelp.GetUserNameByszhlcode(); var task1 = new Task <string>(() => AccessTokenContainer.TryGetAccessTokenAsync(AppId, AppSecret, getNewToken).Result ); task1.Start(); string accesstoken = task1.Result; if (accesstoken.Trim().Length > 0) { CommonHelp.UpdateAppConfig("AccessToken", accesstoken); new JH_Auth_LogB().InsertLog("WXFWHelper", "更新AccessToken为" + accesstoken, "WXFWHelper", _username, _username, 0, strIp); Updatejsapiticket(accesstoken, _username, strIp); } return(accesstoken); }
/// <summary> /// 未兑换愿望提醒 /// </summary> /// <param name="wishId"></param> /// <param name="wishName"></param> /// <param name="openId"></param> /// <param name="nickName"></param> /// <param name="mch_no"></param> /// <returns></returns> public async Task NoExchangeSendTemplateMessage(int wishId, string wishName, string openId, string nickName, string mch_no) { try { var pagepath = string.IsNullOrEmpty(mch_no) ? $"pages/detail/index?wishId={wishId}" : $"pages/conversion/index?wishId={wishId}"; var accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(appId, appSecret); var msgData = new UniformSendData { touser = openId, mp_template_msg = new Mp_Template_Msg { appid = mpAppId, template_id = MPTemplateID.mpNoExchange, miniprogram = new Miniprogram { appid = appId, pagepath = pagepath, }, data = new MPTemplateData( "您还有愿望未进行兑现哦!快来进行愿望兑现吧~", $"{wishName}", $"{nickName}", "", "点击查看详情哟~" ) } }; await Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.UniformSendAsync(accessToken, msgData); } catch (Exception ex) { Console.WriteLine(string.Concat("NoExchangeSendTemplateMessage:", ex.Message)); } }
public void ContainerAsyncTest() { bool useRedis = true; if (useRedis) { var redisConfiguration = "localhost:6379"; RedisManager.ConfigurationOption = redisConfiguration; CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//Redis } //注册 AccessTokenContainer.Register(base._appId, base._appSecret); //获取Token完整结果(包括当前过期秒数) var dt1 = SystemTime.Now; var tokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId).Result; var dt2 = SystemTime.Now; Assert.IsNotNull(tokenResult); Console.WriteLine(tokenResult.access_token); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); //只获取Token字符串 dt1 = SystemTime.Now; var token = AccessTokenContainer.GetAccessTokenAsync(base._appId).Result; dt2 = SystemTime.Now; Assert.AreEqual(tokenResult.access_token, token); Console.WriteLine(tokenResult.access_token); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); //getNewToken { dt1 = SystemTime.Now; token = AccessTokenContainer.TryGetAccessTokenAsync(base._appId, base._appSecret, false).Result; dt2 = SystemTime.Now; Assert.AreEqual(tokenResult.access_token, token); Console.WriteLine(tokenResult.access_token); Console.WriteLine("强制重新获取AccessToken"); dt1 = SystemTime.Now; token = AccessTokenContainer.TryGetAccessTokenAsync(base._appId, base._appSecret, true).Result; dt2 = SystemTime.Now; Assert.AreNotEqual(tokenResult.access_token, token);//如果微信服务器缓存,此处会相同 Console.WriteLine(tokenResult.access_token); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); } { tokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId).Result; Console.WriteLine("HashCode:{0}", tokenResult.GetHashCode()); dt1 = SystemTime.Now; var allItems = AccessTokenContainer.GetAllItems(); dt2 = SystemTime.Now; Assert.IsTrue(allItems.Count > 0); Assert.AreSame(tokenResult, allItems[0].AccessTokenResult);//证明缓存成功 Console.WriteLine("All Items:{0}", allItems.Count); Console.WriteLine("HashCode:{0}", allItems[0].AccessTokenResult.GetHashCode()); Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds); } }
public async Task <IActionResult> Index() { var tokenResult = await AccessTokenContainer.TryGetAccessTokenAsync(_weChatAppId, _weChatAppSecret); return(Content(tokenResult)); }
/// <summary> /// 【异步方法】获取调用微信JS接口的临时票据 /// </summary> /// <param name="appId"></param> /// <param name="secret"></param> /// <param name="type"></param> /// <returns></returns> public static async Task <JsApiTicketResult> GetTicketAsync(string appId, string secret, string type = "jsapi") { var accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(appId, secret); return(GetTicketByAccessToken(accessToken, type)); }