/// <summary> /// 处理视频请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage) { var responseMessage = CreateResponseMessage <ResponseMessageText>(); responseMessage.Content = "您发送了一条视频信息,ID:" + requestMessage.MediaId; #region 材并推送到客户端 Task.Factory.StartNew(async() => { //上传素材 var dir = Server.GetMapPath("~/App_Data/TempVideo/"); var file = await MediaApi.GetAsync(appId, requestMessage.MediaId, dir); var uploadResult = await MediaApi.UploadTemporaryMediaAsync(appId, UploadMediaFileType.video, file, 50000); await CustomApi.SendVideoAsync(appId, base.WeixinOpenId, uploadResult.media_id, "这是您刚才发送的视频", "这是一条视频消息"); }).ContinueWith(async task => { if (task.Exception != null) { WeixinTrace.Log("OnVideoRequest()储存Video过程发生错误:", task.Exception.Message); var msg = string.Format("上传素材出错:{0}\r\n{1}", task.Exception.Message, task.Exception.InnerException != null ? task.Exception.InnerException.Message : null); await CustomApi.SendTextAsync(appId, base.WeixinOpenId, msg); } }); #endregion return(responseMessage); }
public void AsyncSendTemplateMessageTestForBookOptmize() { WxJsonResult finalResult = null; Task.Factory.StartNew(async() => { var openId = "olPjZjsXuQPJoV0HlruZkNzKc91E";//消息目标用户的OpenId //实际生产环境中,用户信息应该从数据库或缓存中读取 var userInfo = await UserApi.InfoAsync(_appId, openId); var data = new TemplateMessage_PaySuccessNotice( "您的订单已经支付", userInfo.nickname, "1234567890", 88.ToString("c"), "模板消息测试商品", "更详细信息,请到Senparc.Weixin SDK官方网站(http://sdk.weixin.senparc.com)查看!\r\n这条消息使用的是优化过的方法,且不带Url参数。使用异步方法。"); var result = await TemplateApi.SendTemplateMessageAsync(_appId, openId, data); //调用客服接口显示msgId finalResult = await CustomApi.SendTextAsync(_appId, openId, "上一条模板消息的MsgID:" + result.msgid); Assert.AreEqual(ReturnCode.请求成功, result.errcode); }); while (finalResult == null) { } }
public void SendNewsTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var articles = new List <Article>(); articles.Add(new Article() { Title = "测试标题", Description = "测试描述", Url = "http://sdk.weixin.senparc.com", PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg" }); articles.Add(new Article() { Title = "测试更多标题", Description = "测试更多描述", Url = "http://sdk.weixin.senparc.com", PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg" }); var result = CustomApi.SendNews(accessToken, openId, articles); Assert.IsNotNull(result); Assert.AreEqual("ok", result.errmsg); }
/// <summary> /// 发送微信消息 /// </summary> /// <param name="openid"></param> /// <param name="msg"></param> private void SendWxMsg(string openid, string msg) { if (!string.IsNullOrEmpty(msg)) { try { CustomApi.SendText(accesstoken, openid, msg); } catch (Exception ex) { LogWriter.Error(ex, string.Format("openid为{0}的用户第一次发送信息出错:{1}", openid, msg)); UpdateAccessToken(); try { CustomApi.SendText(accesstoken, openid, msg); } catch (Exception ex2) { LogWriter.Error(ex2, string.Format("openid为{0}的用户第二次发送信息出错:{1}", openid, msg)); UpdateNewAccessToken(); try { CustomApi.SendText(accesstoken, openid, msg); } catch (Exception ex3) { LogWriter.Error(ex3, string.Format("openid为{0}的用户第三次发送信息出错:{1}", openid, msg)); } } } } }
/// <summary> /// 发送微信消息 /// </summary> /// <param name="openid"></param> /// <param name="mediaid"></param> private void SendWxImg(string openid, string mediaid) { if (!string.IsNullOrEmpty(mediaid)) { try { CustomApi.SendImage(accesstoken, openid, mediaid); } catch (Exception ex) { LogWriter.Error(ex, string.Format("openid为{0}的用户第一次发送登录图片出错", openid)); UpdateAccessToken(); try { CustomApi.SendText(accesstoken, openid, mediaid); } catch (Exception ex2) { LogWriter.Error(ex2, string.Format("openid为{0}的用户第二次发送登录图片出错", openid)); UpdateNewAccessToken(); try { CustomApi.SendText(accesstoken, openid, mediaid); } catch (Exception ex3) { LogWriter.Error(ex3, string.Format("openid为{0}的用户第三次发送登录图片出错", openid)); } } } } }
public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { if (requestMessage.Content == "TESTCOMPONENT_MSG_TYPE_TEXT") { var responseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>(); responseMessage.Content = requestMessage.Content + "_callback";//固定为TESTCOMPONENT_MSG_TYPE_TEXT_callback return(responseMessage); } if (requestMessage.Content.StartsWith("QUERY_AUTH_CODE:")) { string openTicket = OpenTicketHelper.GetOpenTicket(componentAppId); var query_auth_code = requestMessage.Content.Replace("QUERY_AUTH_CODE:", ""); try { var component_access_token = ComponentApi.GetComponentAccessToken(componentAppId, componentSecret, openTicket).component_access_token; var oauthResult = ComponentApi.QueryAuth(component_access_token, componentAppId, query_auth_code); //调用客服接口 var content = query_auth_code + "_from_api"; var sendResult = CustomApi.SendText(oauthResult.authorization_info.authorizer_access_token, requestMessage.FromUserName, content); } catch (Exception ex) { throw; } } return(null); }
/// <summary> /// 处理语音请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage) { var responseMessage = CreateResponseMessage <ResponseMessageMusic>(); //上传缩略图 //var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret); var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image, Server.GetMapPath("~/Images/Logo.jpg")); //设置音乐信息 responseMessage.Music.Title = "天籁之音"; responseMessage.Music.Description = "播放您上传的语音"; responseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId; responseMessage.Music.HQMusicUrl = "http://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId; responseMessage.Music.ThumbMediaId = uploadResult.media_id; //推送一条客服消息 try { CustomApi.SendText(appId, WeixinOpenId, "本次上传的音频MediaId:" + requestMessage.MediaId); } catch { } return(responseMessage); }
/// <summary> /// 发送视频 /// </summary> /// <param name="openId">OPENID</param> /// <param name="mediaId">上传在公众平台的资源ID</param> /// <param name="title">标题</param> /// <param name="description">说明</param> public static void SendVideo(string openId, string mediaId, string title, string description) { var accessToken = GetAccessToken(); var result = CustomApi.SendVideo(accessToken, openId, mediaId, title, description); LogErrorInfo(result, openId, "SendVideo"); }
/// <summary> /// 发送语音 /// </summary> /// <param name="openId">OPENID</param> /// <param name="mediaId">上传在公众平台的资源ID</param> public static void SendVoice(string openId, string mediaId) { var accessToken = GetAccessToken(); var result = CustomApi.SendVoice(accessToken, openId, mediaId); LogErrorInfo(result, openId, "SendVoice"); }
/// <summary> /// 取消关注时间 /// </summary> /// <param name="requestMessage"></param> public void UnSubscribe(RequestMessageEvent_Unsubscribe requestMessage) { OfficialAccount_BLL obll = new OfficialAccount_BLL(); OfficialAccount model = obll.Get(a => a.OriginalID == requestMessage.ToUserName); Subscriber_BLL sbll = new Subscriber_BLL(); if (sbll.GetCount(a => a.OpenID == requestMessage.FromUserName && a.AccountID == model.AccountID) > 0) { Subscriber sub = sbll.Get(a => a.OpenID == requestMessage.FromUserName && a.AccountID == model.AccountID); sub.IsOK = false; sub.UnSubscribeTime = DateTime.Now; if (sub.UnSubscribeCount != null) { sub.UnSubscribeCount += 1; } else { sub.UnSubscribeCount = 1; } sub.Score = 0; sbll.Update(sub); if (sub.FromOpenID != null) { //if (sub.UnSubscribeCount > 1) //{ Subscriber sup = sbll.Get(a => a.OpenID == sub.FromOpenID && a.AccountID == model.AccountID); if (sup.IsOK == true) { sup.Score -= model.UnSubscribeReduceScore; sup.DirectScore -= model.UnSubscribeReduceScore; sbll.Update(sup); StringBuilder sbparent = new StringBuilder(); sbparent.Append("您好,你的粉丝【" + sub.NickName + "】取消关注了本公众号!\n"); sbparent.Append("减少积分:" + model.UnSubscribeReduceScore + "分,累计积分:" + sup.Score.ToString() + "分\n"); CustomApi.SendText(model.AppID, sup.OpenID, sbparent.ToString()); } //} } } }
public void SendImageTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var result = CustomApi.SendImage(accessToken, openId, "10001037"); Assert.IsNotNull(result); Assert.AreEqual("ok", result.errmsg); }
public void SendTextTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var result = CustomApi.SendText(accessToken, openId, "来自平台的回复<>&\n换行了"); Assert.IsNotNull(result); Assert.AreEqual("ok", result.errmsg); }
/// <summary> /// 向用户发送文本消息 /// </summary> /// <param name="openId"></param> /// <param name="message"></param> public void SendText(string openId, string message) { var accessToken = AccessToken(); if (string.IsNullOrEmpty(accessToken)) { return; } CustomApi.SendText(accessToken, openId, message); }
public static readonly string OpenId = "oZ23J1XK3gFFHApw9aNxcf33oeJ0"; //伍家烨 //public MessageBody messageBody; //public PostModel postModel; public void Send(MessageBody body) { Clients.All.SendAsync("Recv", body); //1、body存到数据库 //2、body发到微信公众号,post请求 string text = body.Content.ToString(); var sasas = CustomApi.SendText(appId, OpenId, text); var sss = sasas; }
public void SendTextTest(string openId) { Model.wx_userweixin weixin = GetWeiXinCode(); WeiXinCRMComm cpp = new WeiXinCRMComm(); string error = ""; string accessToken = cpp.getAccessToken(weixin.id, out error); var result = CustomApi.SendText(accessToken, openId, "sdfdsdf"); }
public static readonly string AppId = ConfigurationManager.AppSettings["WeixinAppId"];// Config.SenparcWeixinSetting.WeixinAppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。 public IResponseMessageBase SendMessage(string openId, IResponseMessageBase ResponseMessage) { var senparcMessageQueue = new SenparcMessageQueue(); if (ResponseMessage is ResponseMessageText) { string strResponseMsg = ""; //以下是:把同一用户的多个消息内容,加入到队列中 //myKey 加入队列排序执行 var myKey = SenparcMessageQueue.GenerateKey("MessageQueueHandlerAsync", ResponseMessage.GetType(), Guid.NewGuid().ToString(), "SendMessage"); senparcMessageQueue.Add(myKey, () => { //把需要回复的消息,整理一下 var asyncResponseMessage = ResponseMessage as ResponseMessageText; if (asyncResponseMessage != null) { asyncResponseMessage.Content += "\r\n【1-执行超过5秒,以客服消息回复】"; strResponseMsg = asyncResponseMessage.Content; } }); //Thread.Sleep(10); //myKey2 加入队列排序执行 var myKey2 = SenparcMessageQueue.GenerateKey("MessageQueueHandlerAsync", ResponseMessage.GetType(), Guid.NewGuid().ToString(), "SendMessage"); senparcMessageQueue.Add(myKey2, () => { //把需要回复的消息,整理一下 var asyncResponseMessage = ResponseMessage as ResponseMessageText; if (asyncResponseMessage != null) { asyncResponseMessage.Content += "\r\n【2-执行超过5秒,以客服消息回复】"; strResponseMsg = asyncResponseMessage.Content; } }); //执行队列,把需要回复的消息整理 SenparcMessageQueue.OperateQueue(); //通过客服消息的方式,下发给用户 CustomApi.SendText(AppId, openId, strResponseMsg); //不再给用户回复消息 return(new ResponseMessageNoResponse()); } return(ResponseMessage); }
/// <summary> /// 异步消息的发送 /// </summary> /// <param name="openId"></param> /// <returns></returns> public async Task <ActionResult> CustomeMesssageAsync(string openId = "oifDGvmdSfltOJPL2QSuCdEIN0io") { return(await Task.Factory.StartNew(async() => { for (int i = 0; i < 4; i++) { await CustomApi.SendTextAsync(Config.AppId, openId, "这是第{0}条客服消息,时间:{1}".FormatWith(i + 1, DateTime.Now.ToString("HH:mm:ss.ffff"))); } return Content("异步消息发送完毕"); }).Result); }
public void AfterDeleteVideoTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var file = @"E:\Test.mp4"; var result = MediaApi.UploadForeverVideo(accessToken, file, "测试", "测试", 100000); Assert.IsNotNull(result.media_id); CustomApi.SendVideo(accessToken, "o3IHxjrPzMVZIJOgYMH1PyoTW_Tg", result.media_id, "测试", "测试"); MediaApi.DeleteForeverMedia(accessToken, result.media_id); }
/// <summary> /// 刷新AccessToken /// </summary> /// <param name="openId"></param> /// <returns></returns> public async Task <ActionResult> ChangeAccessToken(string openId = "oifDGvmdSfltOJPL2QSuCdEIN0io") { return(await Task.Factory.StartNew(async() => { for (int i = 0; i < 4; i++) { await CustomApi.SendTextAsync(Config.AppId, openId, "这是第{0}条客服消息,时间:{1}".FormatWith(i + 1, DateTime.Now.ToString("HH:mm:ss.ffff"))); } var accessToken = AccessTokenContainer.GetAccessToken(Config.AppId, true); return Content("异步消息发送完毕.AccessToken:" + accessToken); }).Result); }
//---Public: #region 发送纯文本信息 /// <summary> /// 发送纯文本 /// </summary> /// <param name="openId">OPENID</param> /// <param name="text">纯文本信息</param> public static void SendText(string openId, string text) { if (string.IsNullOrEmpty(openId)) { return; } var accessToken = GetAccessToken(); var result = CustomApi.SendText(accessToken, openId, text); LogErrorInfo(result, openId, "SendText"); }
public void SendActivity(Wx_App app, Wx_Activity activity, string openId) { var articles = new List <Article>(); articles.Add(new Article { Title = activity.Name, Description = activity.Remark, PicUrl = activity.Poster, Url = activity.Url }); CustomApi.SendNews(app.AppId, openId, articles); }
public async Task CustomSendTextAsync(string accessTokenOrAppId, string openId, int siteId, string text) { await _wxChatRepository.ReplyAdd(new WxChat { SiteId = siteId, OpenId = openId, IsReply = true, MaterialType = MaterialType.Text, MaterialId = 0, Text = text }); await CustomApi.SendTextAsync(accessTokenOrAppId, openId, text); }
public void SendVideoTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); try { var result = CustomApi.SendVideo(accessToken, openId, "1000018", "1000012", "[description]"); Assert.Fail();//因为这里写测试代码的时候,微信账号还没有权限,所以会抛出异常(故意的),如果是已经开通的应该是“请求成功” } catch (ErrorJsonResultException ex) { Assert.AreEqual(ReturnCode.api功能未授权, ex.JsonResult.errcode); } }
public void AfterDeleteImgTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var file = @"..\..\AdvancedAPIs\Media\test.jpg"; var result = MediaApi.UploadForeverMedia(accessToken, file); Assert.IsNotNull(result.media_id); CustomApi.SendImage(accessToken, "o3IHxjrPzMVZIJOgYMH1PyoTW_Tg", result.media_id); MediaApi.DeleteForeverMedia(accessToken, result.media_id); }
/// <summary> /// 推送客服消息 /// </summary> /// <param name="openid"></param> /// <param name="message"></param> /// <returns></returns> public async Task SendCustomerMsg(string openid, string message) { var access_token = await _accessTokenContainer.TryGetAccessTokenAsync(_account.AppId, _account.AppSecret); try { await CustomApi.SendTextAsync(access_token, openid, message); } catch { access_token = await _accessTokenContainer.TryGetAccessTokenAsync(_account.AppId, _account.AppSecret, true); await CustomApi.SendTextAsync(access_token, openid, message); } }
/// <summary> /// 构造Api接口 /// </summary> public void GeneratorApi() { List <MethodInfo> methodList = GetApiMethods(); //构造Api接口 foreach (var method in methodList) { CustomApi api = new CustomApi(); api.Name = GetMethodAnnoatation(method); //Post Put WebInvokeAttribute webAttr = method.GetCustomAttribute <WebInvokeAttribute>(); if (webAttr != null) { api.RequestType = webAttr.Method; api.Address = webAttr.UriTemplate; //Post Put 输入参数都是第一个 if (api.RequestType.Equals("POST")) { ParameterInfo[] paraInfos = method.GetParameters(); //Post参数 api.PostParameterList = GetParameterList(paraInfos[0]); //输入参数 api.InParameterList = GetParameterList(1, method); } if (api.RequestType.Equals("PUT")) { ParameterInfo[] paraInfos = method.GetParameters(); //Put参数 api.PutParameterList = GetParameterList(paraInfos[0]); //输入参数 api.InParameterList = GetParameterList(1, method); } } //Get WebGetAttribute webGetAttr = method.GetCustomAttribute <WebGetAttribute>(); if (webGetAttr != null) { api.RequestType = "GET"; api.Address = webGetAttr.UriTemplate; ParameterInfo[] paraInfos = method.GetParameters(); //输入参数 api.InParameterList = GetParameterList(0, method); } //输出参数 api.OutParameterList = GetCmfChinaOutParameter(method); _apiList.Add(api); } }
public static void Main() { using (var httpClient = new HttpClient()) { var authenticator = new PasswordFlowAuthenticator(ClientId, ClientSecret, Username, Password, AuthEndpoint, httpClient); var dataApi = new DataApi(authenticator, httpClient, 44); var toolingApi = new ToolingApi(authenticator, httpClient, 44); var customApi = new CustomApi(authenticator, httpClient); new DataApiSample(dataApi).RunAsync().GetAwaiter().GetResult(); new ToolingApiSample(toolingApi).RunAsync().GetAwaiter().GetResult(); new CustomApiSample(customApi).RunAsync().GetAwaiter().GetResult(); } }
/// <summary> /// 发送客服消息 /// </summary> /// <param name="strMsgType"></param> /// <param name="wechat"></param> /// <param name="strOpenids"></param> /// <param name="obj"></param> /// <param name="strTitle"></param> /// <param name="strComment"></param> /// <returns></returns> private static WxJsonResult SendMsgKF(Weixin.MP.GroupMessageType MsgType, SysWechatConfig wechat, string[] strOpenids, object obj, string strTitle = null, string strComment = null) { WxJsonResult Ret = null; foreach (var openId in strOpenids) { WxJsonResult returnResult = null; switch (MsgType) { case GroupMessageType.text: returnResult = CustomApi.SendText(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj); break; //case GroupMessageType.mpnews: // returnResult = CustomApi.SendNews(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (List<Article>)obj); // break; case GroupMessageType.mpnews: returnResult = CustomApi.SendMpNews(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj); break; case GroupMessageType.image: returnResult = CustomApi.SendImage(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj); break; case GroupMessageType.video: returnResult = CustomApi.SendVideo(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj, strTitle, strComment); break; case GroupMessageType.voice: returnResult = CustomApi.SendVoice(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj); break; } if (returnResult.errcode != ReturnCode.请求成功) { Ret = returnResult; } else if (Ret == null) { Ret = returnResult; } } return(Ret); }
private async Task SendCustomerText(int mpid, string openid, string text) { var account = await _mpAccountAppService.GetCache(mpid); if (account != null) { //根据配置信息,调用客服接口,发送问题创建后的默认回复 try { await CustomApi.SendTextAsync(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), openid, text); } catch { await CustomApi.SendTextAsync(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), openid, text); } } }
public async static Task OnRequest(RequestMessageText requestMessage) { string appId = Yiwan.Core.GlobalContext.Configuration.GetSection("WxConfig:AppId").Value; var openId = requestMessage.FromUserName;//获取OpenId if (requestMessage.Content.Equals("容错")) { await Task.Delay(15000);//故意延时6秒,让微信多次发送消息过来,观察返回结果 CustomApi.SendText(appId, openId, string.Format("测试容错,MsgId:{0},Ticks:{1}", requestMessage.MsgId, SystemTime.Now.Ticks)); } else if (requestMessage.Content.Equals("OPENID")) { var userInfo = UserApi.Info(appId, openId, Language.zh_CN); string content = string.Format( "您的OpenID为:{0}\r\n昵称:{1}\r\n性别:{2}\r\n地区(国家/省/市):{3}/{4}/{5}\r\n关注时间:{6}\r\n关注状态:{7}", requestMessage.FromUserName, userInfo.nickname, (WeixinSex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe); CustomApi.SendText(appId, openId, content); } else if (requestMessage.Content.Equals("领取购买资格")) { try { var(success, data) = await Yiwan.YouzanAPI.UserTags.TagsAdd(openId, "200618ZPW[限粉]"); if (success) { string gdurl = "https://shop16758627.m.youzan.com/wscgoods/detail/2ou0gljjprowr"; CustomApi.SendText(appId, openId, $"购买资格领取成功!\n\n这是<a href=\"{gdurl}\">下单地址</a>\n请尽快支付,商品售完即止则无法支付购买了"); } else { CustomApi.SendText(appId, openId, $"购买资格领取失败!请稍后再试"); } } catch (Exception ex) { if (openId.Equals("oAtpFwcxvxtIg0MMRMScGAPUncsA")) { CustomApi.SendText(appId, openId, JsonConvert.SerializeObject(ex)); } } } }