/// <summary>
        /// 处理语音请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            var responseMessage = CreateResponseMessage <ResponseMessageText>();
            var path            = MediaApi.Get(appId, requestMessage.MediaId, $"{Server.AppDomainAppPath}App_Data/Audio/");
            var outPutPath      = $"{path.Substring(0, path.Length - 4)}.mp3";
            var success         = FFmpegUtil.Arm2Mp3Async(path, outPutPath).ConfigureAwait(false).GetAwaiter().GetResult();

            if (success)
            {
                var intelligentVoiceServer = new IntelligentVoiceServer();
                var text = intelligentVoiceServer.Voice2Text(outPutPath).ConfigureAwait(false).GetAwaiter().GetResult();
                responseMessage.Content = text;
                File.Delete(path);
                File.Delete(outPutPath);
            }
            else
            {
                File.Delete(path);
                responseMessage.Content = "转换失败";
            }
            return(responseMessage);
        }
Example #2
0
        //上传多媒体文件
        public JsonResult PostImage(string appid)
        {
            UploadForeverResultJson ret = new UploadForeverResultJson();

            var Config = WeChatCommonService.GetWeChatConfigByID(int.Parse(appid));

            if (Request.Files.Count > 0)
            {
                //var strToken = Rtntoken(int.Parse(appid));
                var strToken = WeChatCommonService.GetWeiXinToken(Config.Id);

                Dictionary <string, Stream> dic     = new Dictionary <string, Stream>();
                HttpPostedFileBase          objFile = Request.Files[0];
                var filename = objFile.FileName;
                var stream   = objFile.InputStream;
                dic.Add(filename, stream);
                // ret = MediaApi.UploadForeverMedia(strToken, appid, UploadMediaFileType.image, dic, "");
                // ret = MediaApi.UploadPermanent(strToken, UploadMediaFileType.image, dic, "");
                ret = MediaApi.AddMaterial(strToken, UploadMediaFileType.image, dic, "");
            }
            return(Json(ret, JsonRequestBehavior.AllowGet));
        }
Example #3
0
        //[TestMethod]
        private string UploadAndUpdateNewsTest(string accessToken)
        {
            var file   = @"E:\1.jpg";
            var result = MediaApi.UploadForeverMedia(accessToken, file);

            Assert.IsNotNull(result.media_id);

            var new1 = new NewsModel()
            {
                author             = "test",
                content            = "test",
                content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png",
                digest             = "test",
                show_cover_pic     = "1",
                thumb_media_id     = result.media_id,
                title = "test"
            };

            var new2 = new NewsModel()
            {
                author             = "test",
                content            = "test111",
                content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png",
                digest             = "test",
                show_cover_pic     = "1",
                thumb_media_id     = result.media_id,
                title = "test"
            };

            var result1 = MediaApi.UploadNews(accessToken, 10000, new1, new2);

            Assert.IsNotNull(result1.media_id);

            //var result2 = MediaApi.UpdateForeverNews(accessToken, result1.media_id, 0, 10000, new2);

            //Assert.AreEqual(result2.errcode, ReturnCode.请求成功);

            return(result1.media_id);
        }
Example #4
0
        // GET: api/News
        public async Task <IHttpActionResult> Get(int pageIndex = 1, int pageSize = 6)
        {
            var data     = MediaApi.GetNewsMediaList(AccessToken, (pageIndex - 1) * pageSize, pageSize);
            var dataList = data.item
                           .Select(p =>
                                   new MaterialNewsViewModel
            {
                Id           = p.media_id,
                Title        = p.content.news_item.First().title,
                UpdateTime   = p.update_time.ConvertToDateTime(),
                ThumbMediaId = p.content.news_item.First().thumb_media_id,
                Digest       = p.content.news_item.First().digest,
                Url          = p.content.news_item.First().url
            });
            var path = HttpContext.Current.Server.MapPath("~/MediaFiles");

            path = Path.Combine(path, "thumb");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            foreach (var item in dataList)
            {
                var mediaPath = Path.Combine(path, item.ThumbMediaId + ".jpg");
                if (!File.Exists(mediaPath))
                {
                    using (var fs = File.Create(mediaPath))
                    {
                        MediaApi.GetForeverMedia(AccessToken, item.ThumbMediaId, fs);
                        fs.Close();
                    }
                }
            }
            var pagedList = new DataPageListViewModel <MaterialNewsViewModel>(dataList, pageIndex, pageSize,
                                                                              data.total_count);

            return(Ok(pagedList));
        }
Example #5
0
        public MatrixApi(Uri url, string applicationToken, string userId)
        {
            if (url != null && url.IsWellFormedOriginalString() && !url.IsAbsoluteUri)
            {
                throw new MatrixException(Resources.InvalidUrl);
            }

            _isAppservice = true;
            Backend       = new HttpBackend(url, userId);
            Backend.SetAccessToken(applicationToken);
            UserId  = userId;
            BaseUrl = url;
            Rng     = new Random(DateTime.Now.Millisecond);

            Room             = new RoomApi(this);
            LoginEndpoint    = new LoginEndpoint(this);
            VersionsEndpoint = new VersionsEndpoint(this);
            Device           = new DeviceApi(this);
            Media            = new MediaApi(this);
            Profile          = new ProfileApi(this);
            Sync             = new SyncEndpoint(this);
            RoomDirectory    = new RoomDirectoryApi(this);
        }
 /// <summary>
 /// 下载微信临时素材Image
 /// </summary>
 /// <param name="serverId"></param>
 /// <param name="fileName"></param>
 /// <param name="getNewToken"></param>
 /// <returns></returns>
 public bool DownloadTemplate(string serverId, string fileName, bool getNewToken = false)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         var senparcWeixinSetting = SenparcDI.GetService <IOptions <SenparcWeixinSetting> >().Value;
         MediaApi.Get(senparcWeixinSetting.WeixinAppId, serverId, ms);
         //保存到文件
         ms.Position = 0;
         byte[] buffer    = new byte[1024];
         int    bytesRead = 0;
         //判断是否上传成功
         byte[] topBuffer = new byte[1];
         ms.Read(topBuffer, 0, 1);
         if (topBuffer[0] == '{')
         {
             //写入日志
             ms.Position = 0;
             byte[] logBuffer = new byte[1024];
             ms.Read(logBuffer, 0, logBuffer.Length);
             string str = System.Text.Encoding.Default.GetString(logBuffer);
             Senparc.Ncf.Log.LogUtility.Weixin.InfoFormat("下载失败:{0}。serverId:{1}", str, serverId);
             return(false);
         }
         ms.Position = 0;
         //创建目录
         using (FileStream fs = new FileStream(fileName, FileMode.Create))
         {
             while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
             {
                 fs.Write(buffer, 0, bytesRead);
             }
             fs.Flush();
         }
         Senparc.Ncf.Log.LogUtility.Weixin.InfoFormat("下载成功:Path[{0}]", fileName);
     }
     return(true);
 }
Example #7
0
        public ActionResult Edit(DbQRInfo info)
        {
            DbQRInfo poco = TF.QR.Config.Helper.SingleById <DbQRInfo>(info.Id);

            if (poco.OpenID != base.Request.Cookies["openid"].Value)
            {
                return(base.Error("没有操作权限"));
            }
            string str = base.Request.Form["mediaid"];

            if (!string.IsNullOrEmpty(str))
            {
                string accessTokenOrAppId = AccessTokenContainer.TryGetAccessToken(TF.QR.Config.AppId, TF.QR.Config.AppSecret, false);
                string path = string.Concat(new object[] { "/upload/", DateTime.Now.Year, "/", DateTime.Now.Month.ToString("D2"), "/", DateTime.Now.Day.ToString("D2"), "/" });
                if (!Directory.Exists(base.Server.MapPath(path)))
                {
                    Directory.CreateDirectory(base.Server.MapPath(path));
                }
                Guid       guid   = Guid.NewGuid();
                string     str4   = path + guid + ".jpg";
                FileStream stream = new FileStream(base.Server.MapPath(str4), FileMode.Create);
                MediaApi.Get(accessTokenOrAppId, str, stream);
                stream.Close();
                poco.Photo = str4;
            }
            poco.RealName       = info.RealName;
            poco.Sex            = info.Sex;
            poco.BirthDay       = info.BirthDay;
            poco.Address        = info.Address;
            poco.ContactName    = info.ContactName;
            poco.ContactMobile  = info.ContactMobile;
            poco.ContactName2   = info.ContactName2;
            poco.ContactMobile2 = info.ContactMobile2;
            poco.Tip            = info.Tip;
            TF.QR.Config.Helper.Save(poco);
            return(base.Success("提交成功"));
        }
Example #8
0
        public void DeleteForm(string keyValue)
        {
            var    id = Convert.ToInt64(keyValue);
            var    genericFetchStrategy = new GenericFetchStrategy <WxNews>().Include(p => p.WxNewsItems);
            WxNews wxNews = wxNewsRepository.Get(id, genericFetchStrategy);

            if (!string.IsNullOrEmpty(wxNews.MediaId))
            {
                string            appId             = WxOperatorProvider.Provider.GetCurrent().AppId;
                AccessTokenResult accessTokenResult = AccessTokenContainer.GetAccessTokenResult(appId);
                var wxJsonResult = MediaApi.DeleteForeverMedia(accessTokenResult.access_token, wxNews.MediaId, 10000);
                if (wxJsonResult.ErrorCodeValue == 0)
                {
                    wxNews.MediaId      = null;
                    wxNews.DeletedMark  = true;
                    wxNews.DeletionTime = DateTime.Now;
                    foreach (WxNewsItem item in wxNews.WxNewsItems)
                    {
                        item.DeletedMark  = true;
                        item.DeletionTime = DateTime.Now;
                    }
                    wxNewsRepository.Update(wxNews);
                }
            }
            else
            {
                wxNews.MediaId      = null;
                wxNews.DeletedMark  = true;
                wxNews.DeletionTime = DateTime.Now;
                foreach (WxNewsItem item in wxNews.WxNewsItems)
                {
                    item.DeletedMark  = true;
                    item.DeletionTime = DateTime.Now;
                }
                wxNewsRepository.Update(wxNews);
            }
        }
Example #9
0
        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            var responseMessage = CreateResponseMessage <ResponseMessageMusic>();
            //上传缩略图
            var uploadResult = MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image,
                                                             Server.GetMapPath("~/Images/Logo.jpg"));

            //设置音乐信息
            responseMessage.Music.Title        = "天籁之音";
            responseMessage.Music.Description  = "播放您上传的语音";
            responseMessage.Music.MusicUrl     = "http://wx.wftx666.com/Media/GetVoice?mediaId=" + requestMessage.MediaId;
            responseMessage.Music.HQMusicUrl   = "http://wx.wftx666.com/Media/GetVoice?mediaId=" + requestMessage.MediaId;
            responseMessage.Music.ThumbMediaId = uploadResult.media_id;

            //推送一条客服消息
            try
            {
                CustomApi.SendText(appId, WeixinOpenId, "本次上传的音频MediaId:" + requestMessage.MediaId);
            }
            catch {
            }

            return(responseMessage);
        }
Example #10
0
        public void DownloadToDirTest()
        {
            ////下载图片
            //var file = string.Format("qr-{0}.jpg", DateTime.Now.Ticks);
            //using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate))
            //{
            //    Get.Download(url, fs);//下载
            //    fs.Flush();//直接保存,无需处理指针
            //}

            var fileName = @"E:\Senparc项目\WeiXinMPSDK\src\Senparc.Weixin.MP\Senparc.Weixin.MP.Test\qr.jpg";

            //上传素材
            var result = MediaApi.UploadTemporaryMedia(base._appId, UploadMediaFileType.image, fileName);

            Console.WriteLine("MediaId:" + result.media_id);

            //下载
            var url            = "http://sdk.weixin.senparc.com/images/v2/ewm_01.png";
            var filePath       = @"E:\Senparc项目\WeiXinMPSDK\src\Senparc.Weixin.MP\Senparc.Weixin.MP.Test\qr_" + DateTime.Now.ToString("HHmmss") + ".jpg";
            var downloadResult = Senparc.Weixin.HttpUtility.Get.Download(url, filePath);

            Console.WriteLine(downloadResult);
        }
        public ActionResult Messages(int pageIndex = 1, int pageSize = 18)
        {
            var data     = MediaApi.GetNewsMediaList(AccessToken, pageIndex, pageSize);
            var dataList = data.item
                           .Select(p =>
                                   new MaterialNewsViewModel
            {
                Id           = p.media_id,
                Title        = p.content.news_item.First().title,
                UpdateTime   = p.update_time.ConvertToDateTime(),
                ThumbMediaId = p.content.news_item.First().thumb_media_id,
                Digest       = p.content.news_item.First().digest,
                Url          = p.content.news_item.First().url
            });
            var path = Server.MapPath("~/MediaFiles");

            path = Path.Combine(path, "thumb");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            foreach (var item in dataList)
            {
                var mediaPath = Path.Combine(path, item.ThumbMediaId + ".jpg");
                if (!System.IO.File.Exists(mediaPath))
                {
                    using (var stream = System.IO.File.Create(mediaPath))
                    {
                        MediaApi.GetForeverMedia(AccessToken, item.ThumbMediaId, stream);
                    }
                }
            }
            var pagedList = new PagedList <MaterialNewsViewModel>(dataList, pageIndex, pageSize, data.total_count);

            return(View(pagedList));
        }
Example #12
0
        /// <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          = ServerUtility.ContentRootMapPath("~/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, "这是您刚才发送的视频", "这是一条视频消息");
                await CustomApi.SendVideoAsync(appId, base.OpenId, 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);
                    await CustomApi.SendTextAsync(appId, base.OpenId, msg);
                }
            });

            #endregion

            return(responseMessage);
        }
Example #13
0
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;

            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
            case "OneClick":
            {
                //这个过程实际已经在OnTextOrEventRequest中完成,这里不会执行到。
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
            }
            break;

            case "SubClickRoot_Text":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Content = "您点击了子菜单按钮。";
            }
            break;

            case "SubClickRoot_News":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageNews>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Articles.Add(new Article()
                    {
                        Title       = "您点击了子菜单图文按钮",
                        Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                        PicUrl      = "http://www.w3ccloud.com/Images/qrcode.jpg",
                        Url         = "http://www.w3ccloud.com"
                    });
            }
            break;

            case "SubClickRoot_Music":
            {
                //上传缩略图
                var accessToken  = AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                var uploadResult = MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.thumb,
                                                                 Server.GetMapPath("~/Images/Logo.jpg"));
                //设置音乐信息
                var strongResponseMessage = CreateResponseMessage <ResponseMessageMusic>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Music.Title        = "天籁之音";
                strongResponseMessage.Music.Description  = "真的是天籁之音";
                strongResponseMessage.Music.MusicUrl     = "http://www.w3ccloud.com/Content/music1.mp3";
                strongResponseMessage.Music.HQMusicUrl   = "http://www.w3ccloud.com/Content/music1.mp3";
                strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id;
            }
            break;

            case "SubClickRoot_Image":
            {
                //上传图片
                var accessToken  = AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                var uploadResult = MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image,
                                                                 Server.GetMapPath("~/Images/Logo.jpg"));
                //设置图片信息
                var strongResponseMessage = CreateResponseMessage <ResponseMessageImage>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Image.MediaId = uploadResult.media_id;
            }
            break;

            case "SubClickRoot_Agent":    //代理消息
            {
                //获取返回的XML
                DateTime dt1 = DateTime.Now;
                reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                DateTime dt2 = DateTime.Now;

                if (reponseMessage is ResponseMessageNews)
                {
                    (reponseMessage as ResponseMessageNews)
                    .Articles[0]
                    .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                }
            }
            break;

            case "Member":    //托管代理会员信息
            {
                //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
                reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
            }
            break;

            case "OAuth":    //OAuth授权测试
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageNews>();
                strongResponseMessage.Articles.Add(new Article()
                    {
                        Title       = "OAuth2.0测试",
                        Description = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试(是专门的一个临时测试账号的授权,并非Senparc.Weixin.MP SDK官方账号,所以如果授权后出现错误页面数正常情况),测试号随时可能过期。请将此DEMO部署到您自己的服务器上,并使用自己的appid和secret。",
                        Url         = "http://www.w3ccloud.com/oauth2",
                        PicUrl      = "http://www.w3ccloud.com/Images/qrcode.jpg"
                    });
                reponseMessage = strongResponseMessage;
            }
            break;

            case "Description":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = GetWelcomeInfo();
                reponseMessage = strongResponseMessage;
            }
            break;

            case "SubClickRoot_PicPhotoOrAlbum":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Content = "您点击了【微信拍照】按钮。系统将会弹出拍照或者相册发图。";
            }
            break;

            case "SubClickRoot_ScancodePush":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Content = "您点击了【微信扫码】按钮。";
            }
            break;

            default:
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                reponseMessage = strongResponseMessage;
            }
            break;
            }

            return(reponseMessage);
        }
        public static string GetMediaInfo(AutoReplyContentEnum cate, NewsInfoView news, int iAppID)
        {
            string   mediaId        = null;
            string   saveFileName   = null;
            string   targetFilePath = null;
            string   saveDir        = null;
            FileInfo fi             = null;
            dynamic  ret            = null;


            //上次的素材还没过期
            if (!string.IsNullOrEmpty(news.MediaId) && news.MediaCreateTime > 0)
            {
                if (DateTimeHelper.GetDateTimeFromXml(news.MediaCreateTime).AddDays(3) > DateTime.Now)
                {
                    return(news.MediaId);
                }
            }


            Dictionary <string, Stream> dic = new Dictionary <string, Stream>();

            var objConfig = WeChatCommonService.GetWeChatConfigByID(iAppID);

            bool isCrop = (objConfig.IsCorp == null || objConfig.IsCorp.Value);

            string strToken = (objConfig.IsCorp != null && !objConfig.IsCorp.Value) ? "" : Innocellence.Weixin.QY.CommonAPIs.AccessTokenContainer.TryGetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);


            log.Debug("GetMediaInfo start:  cate:{0}  iAppID:{1}", cate, iAppID);

            switch (cate)
            {
            case AutoReplyContentEnum.IMAGE:
                //saveFileName = Path.GetFileName(news.ImageContent.Replace("_t", "")); //不发缩略图
                //targetFilePath = news.ImageContent.Substring(0, news.ImageContent.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.ImageContent.Replace("_t", ""));

                if (isCrop)
                {
                    dic.Add(fi.Name, fi.OpenRead());
                    ret = MediaApi.Upload(strToken, UploadMediaFileType.image, dic, "", 50 * 10000);
                }
                else
                {
                    ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret,
                                                                                            Innocellence.Weixin.MP.UploadMediaFileType.image, fi.OpenRead(), fi.FullName, 50 * 10000);
                }

                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            case AutoReplyContentEnum.VOICE:
                //saveFileName = Path.GetFileName(news.SoundSrc);
                //targetFilePath = news.SoundSrc.Substring(0, news.SoundSrc.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.SoundSrc.Replace("_t", ""));

                dic.Add(fi.Name, fi.OpenRead());
                try
                {
                    if (isCrop)
                    {
                        ret = MediaApi.Upload(strToken, UploadMediaFileType.voice, dic, "", 50 * 10000);
                    }
                    else
                    {
                        ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret,
                                                                                                Innocellence.Weixin.MP.UploadMediaFileType.voice, fi.OpenRead(),
                                                                                                fi.FullName, 50 * 10000);
                    }
                }
                catch (ErrorJsonResultException ex)
                {
                    if (ex.JsonResult.errcode == Weixin.ReturnCode.语音播放时间超过限制)
                    {
                        throw new Exception("语音播放时间超过限制,请上传播放长度不超过60秒的语音文件。");
                    }
                    else
                    {
                        throw;
                    }
                }
                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            case AutoReplyContentEnum.VIDEO:
                //saveFileName = Path.GetFileName(news.VideoContent);
                //targetFilePath = news.VideoContent.Substring(0, news.VideoContent.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.VideoContent.Replace("_t", ""));


                if (isCrop)
                {
                    dic.Add(fi.Name, fi.OpenRead());
                    ret = MediaApi.Upload(strToken, UploadMediaFileType.video, dic, "", 50 * 10000);
                }
                else
                {
                    ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret,
                                                                                            Innocellence.Weixin.MP.UploadMediaFileType.video, fi.OpenRead(), fi.FullName, 50 * 10000);
                }
                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            case AutoReplyContentEnum.FILE:
                //saveFileName = Path.GetFileName(news.FileSrc);
                //targetFilePath = news.FileSrc.Substring(0, news.FileSrc.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.FileSrc.Replace("_t", ""));
                string extention   = fi.Name.Substring(fi.Name.LastIndexOf('.'));
                string fileName    = string.IsNullOrEmpty(news.RealFileName) ? news.NewsTitle : news.RealFileName;
                string displayName = fileName.EndsWith(extention) ? fileName : fileName + extention;
                if (isCrop)
                {
                    dic.Add(displayName, fi.OpenRead());
                    ret = MediaApi.Upload(strToken, UploadMediaFileType.file, dic, "", 50 * 10000);
                }
                else
                {
                    //服务号暂时不支持推送文件.
                    //ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret, Innocellence.Weixin.MP.UploadMediaFileType.voice, fi.OpenRead(), Path.Combine(saveDir, saveFileName), 50 * 10000);
                }
                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            default:
                break;
            }

            if (ret != null)
            {
                news.MediaCreateTime = ret.created_at;


                log.Debug("GetMediaInfo end:  media_id:{0} ", ret.media_id);
            }
            return(mediaId);
        }
Example #15
0
        //[TestMethod]
        private void DeleteForeverMediaTest(string accessToken, string mediaId)
        {
            var result = MediaApi.DeleteForeverMedia(accessToken, mediaId);

            Assert.AreEqual(result.errcode, ReturnCode.请求成功);
        }
Example #16
0
 /// <summary>
 /// 修改永久图文素材
 /// </summary>
 /// <param name="access_token"></param>
 /// <param name="timeOut"></param>
 /// <param name="news"></param>
 /// <returns></returns>
 public async Task <WxJsonResult> UpdateForeverNewsAsync(string appid, string mediaId, NewsModel news, int timeOut = 10000)
 {
     return(await MediaApi.UpdateForeverNewsAsync(appid, mediaId, 0, news));
 }
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //TODO:这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs

            //这里可以进行数据库记录或处理

            //发送一条客服消息回复用户

            var contentUpper = requestMessage.Content.ToUpper();

            if (contentUpper == "LINK")
            {
                //发送客服消息
                Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendLink(appId, OpenId, "欢迎使用 Senparc.Weixin SDK", "感谢大家的支持!\r\n\r\n盛派永远在你身边!",
                                                                      "https://weixin.senparc.com", "https://sdk.weixin.senparc.com/images/book-cover-front-small-3d-transparent.png");
            }
            else if (contentUpper == "CARD")
            {
                //上传封面临时素材
                var uploadResult = MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image, ServerUtility.ContentRootMapPath("~/Images/Logo.thumb.jpg"));

                //发送客服消息
                Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendMiniProgramPage(appId, OpenId, "欢迎使用 Senparc.Weixin SDK", "pages/websocket/websocket",
                                                                                 uploadResult.media_id);
            }
            else if (contentUpper == "客服")
            {
                Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendText(appId, OpenId, "您即将进入客服");
                var responseMessage = base.CreateResponseMessage <ResponseMessageTransfer_Customer_Service>();
                return(responseMessage);
            }
            else
            {
                var result = new StringBuilder();
                result.AppendFormat("您刚才发送了文字信息:{0}\r\n\r\n", requestMessage.Content);

                if (CurrentMessageContext.RequestMessages.Count > 1)
                {
                    result.AppendFormat("您刚才还发送了如下消息({0}/{1}):\r\n", CurrentMessageContext.RequestMessages.Count,
                                        CurrentMessageContext.StorageData);
                    for (int i = CurrentMessageContext.RequestMessages.Count - 2; i >= 0; i--)
                    {
                        var    historyMessage = CurrentMessageContext.RequestMessages[i];
                        string content        = null;
                        if (historyMessage is RequestMessageText)
                        {
                            content = (historyMessage as RequestMessageText).Content;
                        }
                        else if (historyMessage is RequestMessageEvent_UserEnterTempSession)
                        {
                            content = "[进入客服]";
                        }
                        else
                        {
                            content = string.Format("[非文字信息:{0}]", historyMessage.GetType().Name);
                        }

                        result.AppendFormat("{0} 【{1}】{2}\r\n",
                                            historyMessage.CreateTime.ToString("HH:mm:ss"),
                                            historyMessage.MsgType.ToString(),
                                            content
                                            );
                    }
                    result.AppendLine("\r\n");
                }

                //处理微信换行符识别问题
                var msg = result.ToString().Replace("\r\n", "\n");

                //发送客服消息
                Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendText(appId, OpenId, msg);

                //也可以使用微信公众号的接口,完美兼容:
                //Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(appId, WeixinOpenId, msg);
            }

            return(new SuccessResponseMessage());

            //和公众号一样回复XML是无效的:
            //            return new SuccessResponseMessage()
            //            {
            //                ReturnText = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
            //<xml>
            //    <ToUserName><![CDATA[{0}]]></ToUserName>
            //    <FromUserName><![CDATA[{1}]]></FromUserName>
            //    <CreateTime>1357986928</CreateTime>
            //    <MsgType><![CDATA[text]]></MsgType>
            //    <Content><![CDATA[TNT2]]></Content>
            //</xml>",requestMessage.FromUserName,requestMessage.ToUserName)
            //            };
        }
Example #18
0
        public static Dictionary <string, string> WXUploadFile(string ServerID, UploadImageInfo model)
        {
            //string gps= map_tx2bd(double.Parse(model.GPSLatitude), double.Parse(model.GPSLongitude));

            string filePath    = System.Configuration.ConfigurationManager.AppSettings[BaseDictType.TempFileUploadPath];
            var    filename    = Util.RPCNow.Ticks.ToString() + Util.RPCNow.Millisecond + ".jpg";
            var    saveURl     = System.Web.HttpContext.Current.Server.MapPath(filePath) + filename;
            var    accessToken = WeixinCache.GetCorpAccessToken();

            using (MemoryStream stream = new MemoryStream())
            {
                MediaApi.Get(accessToken, ServerID, stream);

                if (!System.IO.Directory.Exists(saveURl))
                {
                    System.IO.Directory.CreateDirectory(saveURl.Replace(filename, ""));
                }
                using (var fs = new FileStream(saveURl, FileMode.CreateNew))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(fs);
                    fs.Flush();
                }
            }

            Dictionary <string, string> data = new Dictionary <string, string>();

            MemoryStream ms = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(saveURl));

            try
            {
                string strDescription = model.DateTimeOriginal + "\r\n";
                strDescription += model.StoreAddr + "\r\n";                 // + " 精度(" + model.SignPoint + ")" ;
                strDescription += model.StoreCode + " " + model.StoreName + "\r\n";
                strDescription += model.EmpCode + " " + model.EmpName + "(" + model.EmpDuty + ")\r\n";

                System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                Graphics             g     = Graphics.FromImage(image);
                //Brush drawBrush = new SolidBrush(System.Drawing.Color.FromArgb(((System.Byte)(222)), ((System.Byte)(243)), ((System.Byte)(255)))); //自定义字体颜色
                Font       font    = new Font("宋体", 10);
                SizeF      sizeF   = g.MeasureString(" " + strDescription + " ", font);
                Color      Mycolor = System.Drawing.Color.FromArgb(0, 0, 0, 0);           //说明:1-(128/255)=1-0.5=0.5 透明度为0.5,即50%
                SolidBrush sb1     = new System.Drawing.SolidBrush(Mycolor);
                g.FillRectangle(sb1, new RectangleF(new PointF(0, image.Height - 100), sizeF));
                //FillRoundRectangle(g, sb1, new Rectangle(15, 20, (int)sizeF.Width+20, (int)sizeF.Height), 8);
                //DrawRoundRectangle(g, Pens.Transparent, new Rectangle(15, 20, (int)sizeF.Width +20, (int)sizeF.Height), 8);
                g.DrawString(strDescription, new Font("宋体", 10), Brushes.White, new PointF(2, image.Height - 94));

                System.IO.File.Delete(saveURl);
                image.Save(saveURl);

                var url = filePath + filename;

                data.Add("status", "1");
                data.Add("content", "上传成功");
                data.Add("url", url);
                data.Add("filename", filename);
            }
            catch (Exception ex)
            {
                data.Add("status", "0");
                data.Add("content", "上传失败");
                data.Add("url", "");
                data.Add("filename", "");
            }
            finally
            {
                ms.Close();
            }

            //string returnstring=PostApply(hpf, DateTimeOriginal, GPSLatitude, GPSLongitude);


            return(data);
        }
Example #19
0
        /// <summary>
        /// 上传临时图文素材
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="timeOut"></param>
        /// <param name="news"></param>
        /// <returns></returns>
        public async Task <UploadTemporaryMediaResult> UploadTempNewsAsync(string appid, NewsModel[] news, int timeOut = 10000)
        {
            var access_token = this.GetAccessToken(appid);

            return(await MediaApi.UploadTemporaryNewsAsync(access_token, timeOut, news));
        }
Example #20
0
        /// <summary>
        /// 上传图文素材中的图片获取url
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task <UploadImgResult> UploadImgAsync(string appId, string filePath)
        {
            var wxRet = await MediaApi.UploadImgAsync(appId, filePath);

            return(wxRet);
        }
Example #21
0
        /// <summary>
        /// 上传视频
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task <UploadForeverMediaResult> uploadVideopasync(string appId, string filePath)
        {
            var wxRet = await MediaApi.UploadForeverVideoAsync(appId, filePath, "武田制作", "武田出品");

            return(wxRet);
        }
Example #22
0
        /// <summary>
        /// 获取图文消息列表
        /// </summary>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public async Task <MediaList_NewsResult> GetForeverNewsListAsync(string appId, int offset, int count)
        {
            var wxRet = await MediaApi.GetNewsMediaListAsync(appId, offset, count);

            return(wxRet);
        }
Example #23
0
        /// <summary>
        /// 获取微信文章
        /// </summary>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public async Task <GetNewsResultJson> GetForeverNewsAsync(string appId, string mediaId)
        {
            var wxRet = await MediaApi.GetForeverNewsAsync(appId, mediaId);

            return(wxRet);
        }
Example #24
0
        /// <summary>
        /// 获取素材列表(图片、视频、音频)
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="mediaFileType"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public async Task <MediaList_OthersResult> GetOthersMediaListAsync(string appId, UploadMediaFileType mediaFileType, int offset, int count)
        {
            var wxRet = await MediaApi.GetOthersMediaListAsync(appId, mediaFileType, offset, count);

            return(wxRet);
        }
Example #25
0
 /// <summary>
 /// 获取文件流
 /// </summary>
 /// <param name="accessToken"></param>
 /// <param name="mediaId"></param>
 /// <returns></returns>
 public static void Get(string accessToken, string mediaId, Stream ms)
 {
     MediaApi.Get(accessToken, mediaId, ms);
 }
Example #26
0
 /// <summary>
 /// 获取微信视频
 /// </summary>
 /// <param name="appId"></param>
 /// <param name="mediaId"></param>
 /// <returns></returns>
 public async Task <GetForeverMediaVideoResultJson> GetForeverMediaVideoAsync(string appId, string mediaId)
 {
     return(await MediaApi.GetForeverVideoAsync(appId, mediaId));
 }
Example #27
0
 /// <summary>
 /// 图片消息
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="strAPPID"></param>
 /// <param name="strUserS"></param>
 public void SendImage(string filePath, string strAPPID, string strUserS = "@all")
 {
     try
     {
         if (strUserS == "")
         {
             return;
         }
         if (Qyinfo.IsUseWX == "Y")
         {
             Senparc.Weixin.Work.AdvancedAPIs.Media.UploadTemporaryResultJson md = MediaApi.Upload(GetToken(), Senparc.Weixin.Work.UploadMediaFileType.image, filePath);
             if (md.media_id != "")
             {
                 MassApi.SendImage(GetToken(), strUserS, "", "", strAPPID, md.media_id);
             }
         }
     }
     catch { }
 }
Example #28
0
        /// <summary>
        /// 删除永久素材
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task <WxJsonResult> DelForeverMediaAsync(string appid, string mediaId)
        {
            var wxRet = await MediaApi.DeleteForeverMediaAsync(appid, mediaId);

            return(wxRet);
        }
Example #29
0
        /// <summary>
        /// 获取素材数量(图文、图片、视频、音频)
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        public async Task <GetMediaCountResultJson> GetMediaCountAsync(string appId)
        {
            var wxRet = await MediaApi.GetMediaCountAsync(appId);

            return(wxRet);
        }
Example #30
0
        public ActionResult GetOnlineList()
        {
            var result = MediaApi.GetNewsMediaList("", 0, 5);

            return(Content(result.ToJson()));
        }