Esempio n. 1
0
        public virtual async Task <string> UploadAndGetMediaID(int mpid, string fileUrl, MpMessageType type)
        {
            var account = await _mpAccountAppService.Get(new Abp.Application.Services.Dto.EntityDto <int> {
                Id = mpid
            });

            var access_token = await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret);

            UploadForeverMediaResult responseModel = null;
            var fileName = fileUrl.Substring(fileUrl.LastIndexOf("/") + 1);

            try
            {
                responseModel = JsonConvert.DeserializeObject <UploadForeverMediaResult>(await HttpHelper.HttpPost($"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type={type.ToString()}", fileUrl, fileName));
            }
            catch (Exception ex)
            {
                Logger.Error($"上传图片到微信出错:{ex.Message}");
                access_token = await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true);

                try
                {
                    responseModel = JsonConvert.DeserializeObject <UploadForeverMediaResult>(await HttpHelper.HttpPost($"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type={type.ToString()}", fileUrl, fileName));
                }
                catch (Exception e)
                {
                    Logger.Error($"上传图片到微信出错:{e.Message}");
                    throw new UserFriendlyException(e.Message);
                }
            }
            return(responseModel != null ? responseModel.media_id : "");
        }
Esempio n. 2
0
        public virtual async Task <string> UploadVideoAndGetMediaID(int mpid, string fileUrl, MpMessageType type, string title, string introduction)
        {
            var account = await _mpAccountAppService.Get(new Abp.Application.Services.Dto.EntityDto <int> {
                Id = mpid
            });

            var access_token = await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret);

            UploadForeverMediaResult responseModel = null;
            var fileName = fileUrl.Substring(fileUrl.LastIndexOf("/") + 1);
            Dictionary <string, string> content = new Dictionary <string, string>()
            {
                { "description", JsonConvert.SerializeObject(new { title = title, introduction = introduction }) }
            };


            try
            {
                responseModel = JsonConvert.DeserializeObject <UploadForeverMediaResult>(await HttpHelper.HttpPostVideo($"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type={type.ToString()}", fileUrl, content.First(), fileName));
            }
            catch
            {
                access_token = await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true);

                try
                {
                    responseModel = JsonConvert.DeserializeObject <UploadForeverMediaResult>(await HttpHelper.HttpPostVideo($"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type={type.ToString()}", fileUrl, content.First(), fileName));
                }
                catch (Exception e)
                {
                    throw new UserFriendlyException(e.Message);
                }
            }
            return(responseModel != null ? responseModel.media_id : "");
        }
Esempio n. 3
0
        public async Task UploadMediaImage(UploadMediaImageInput input)
        {
            string accessToken = await GetAccessToken();

            string path = HttpContext.Current.Server.MapPath(input.Path);
            UploadForeverMediaResult uploadForeverMediaResult = await Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadForeverMediaAsync(accessToken, path);
        }
Esempio n. 4
0
        public UploadForeverMediaResult UploadForeverMedia(string path)
        {
            UploadForeverMediaResult uploadForeverMediaResult = null;
            string appId = WxOperatorProvider.Provider.GetCurrent().AppId;

            uploadForeverMediaResult = MediaApi.UploadForeverMedia(appId, path);
            return(uploadForeverMediaResult);
        }
Esempio n. 5
0
        private void SendGroupMessage(string tempStr, string accessToken, MediaList_OthersResult imgResult, string strAction)
        {
            string sendCountTxt = Server.MapPath("sendcount.txt");
            var    sendCount    = int.Parse(File.ReadAllText(sendCountTxt));

            NewsModel[] newsList   = new NewsModel[sendCount];
            var         dataSevice = new DataAccessSerive();
            var         jobList    = dataSevice.GetTopJobInfoList();

            if (jobList.Count > 0)
            {
                List <Article> articles = new List <Article>();
                int            i        = 0;
                string         imgName;
                foreach (var job in jobList)
                {
                    if (i == sendCount)
                    {
                        break;
                    }
                    imgName = "send" + i.ToString() + ".jpg";
                    string imgUrl    = string.Format("{0}/image/{1}", WebConfigurationManager.AppSettings["domain"], imgName);
                    var    jobDetail = dataSevice.GetJobDetail(job.JobId);
                    var    news      = new NewsModel();
                    news.author  = "";
                    news.content = tempStr.Replace("[ComName]", job.ComName)
                                   .Replace("[ComBrief]", jobDetail.ComBrief)
                                   .Replace("[DetailPalce]", jobDetail.DetailPalce)
                                   .Replace("[LinkMan]", jobDetail.LinkMan)
                                   .Replace("[Phone]", jobDetail.Phone)
                                   .Replace("[JobName]", jobDetail.JobName)
                                   .Replace("[JobType]", jobDetail.JobType)
                                   .Replace("[LowMoney]", jobDetail.LowMoney)
                                   .Replace("[HrNum]", jobDetail.HrNum)
                                   .Replace("[Edu]", jobDetail.Edu)
                                   .Replace("[RegisterDate]", jobDetail.RegisterDate)
                                   .Replace("[EffectDate]", jobDetail.EffectDate)
                                   .Replace("[Other]", jobDetail.Other)
                                   .Replace("[Sex]", jobDetail.Sex)
                    ;
                    //news.content_source_url = WebConfigurationManager.AppSettings["domain"] + "/html/detail.html?id=" + job.JobId;
                    news.content_source_url = WebConfigurationManager.AppSettings["website"];
                    news.digest             = job.ComName + "诚聘" + job.JobName;
                    news.show_cover_pic     = "0";
                    news.thumb_media_id     = imgResult.item.Find(p => p.name == imgName).media_id;
                    news.title  = job.ComName + "诚聘" + job.JobName;
                    newsList[i] = news;
                    i++;
                }
                UploadForeverMediaResult mediaResult = MediaApi.UploadNews(accessToken, 100000, newsList);
                try
                {
                    GroupMessageApi.SendGroupMessageByGroupId
                        (accessToken, "-1", mediaResult.media_id, GroupMessageType.mpnews, true);
                    txtResult.Text += "提交成功一次" + strAction + " 推送成功";
                }
                catch (Exception ex)
                {
                    txtResult.Text += "提交成功一次订" + strAction + " 推送失败 " + ex.Message;
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        ///     上传站点资源
        /// </summary>
        /// <param name="resoureType"></param>
        /// <param name="file"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static Site_FileBase Upload(Site_ResourceType resoureType, string fileName, byte[] fileStream,
                                           AppDbContext db, out AjaxResponse ajaxMessage)
        {
            ajaxMessage = new AjaxResponse {
                Success = true
            };
            var fileSaveName = Guid.NewGuid().ToString("N") + Path.GetExtension(fileName);
            var tenantId     = WeiChatApplicationContext.Current.TenantId;

            var dirName = tenantId.ToString();
            var path    = Path.Combine(HttpContext.Current.Server.MapPath("~/MediaFiles"), dirName);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, fileSaveName);
            File.WriteAllBytes(path, fileStream);
            UploadForeverMediaResult result = null;

            result = resoureType.ResourceType == SiteResourceTypes.Video
                ? MediaApi.UploadForeverVideo(WeChatConfigManager.Current.GetAccessToken(), path, fileName, "test")
                : MediaApi.UploadForeverMedia(WeChatConfigManager.Current.GetAccessToken(), path);
            if (!string.IsNullOrWhiteSpace(result.errmsg))
            {
                ajaxMessage.Success = false;
                ajaxMessage.Message = result.errmsg;
            }
            else
            {
                switch (resoureType.ResourceType)
                {
                case SiteResourceTypes.Gallery:
                {
                    var pic = new Site_Image
                    {
                        IsFrontCover    = false,
                        MediaId         = result.media_id,
                        Name            = fileName,
                        SiteUrl         = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName),
                        Url             = result.url,
                        ResourcesTypeId = resoureType.Id,
                        CreateBy        = HttpContext.Current.User.Identity.GetUserId(),
                        CreateTime      = DateTime.Now,
                        TenantId        = tenantId
                    };
                    db.Site_Images.Add(pic);
                    db.SaveChanges();
                    return(pic);
                }
                break;

                case SiteResourceTypes.Voice:
                {
                    var voice = new Site_Voice
                    {
                        MediaId         = result.media_id,
                        Name            = fileName,
                        SiteUrl         = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName),
                        Url             = result.url,
                        ResourcesTypeId = resoureType.Id,
                        CreateBy        = HttpContext.Current.User.Identity.GetUserId(),
                        CreateTime      = DateTime.Now,
                        TenantId        = tenantId
                    };
                    db.Site_Voices.Add(voice);
                    db.SaveChanges();
                    return(voice);
                }
                break;

                case SiteResourceTypes.Video:
                {
                    var video = new Site_Video
                    {
                        MediaId         = result.media_id,
                        Name            = fileName,
                        SiteUrl         = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName),
                        Url             = result.url,
                        ResourcesTypeId = resoureType.Id,
                        CreateBy        = HttpContext.Current.User.Identity.GetUserId(),
                        CreateTime      = DateTime.Now,
                        TenantId        = tenantId
                    };
                    db.Site_Videos.Add(video);
                    db.SaveChanges();
                    return(video);
                }
                break;

                default:
                    ajaxMessage.Success = false;
                    ajaxMessage.Message = "不支持上传此类型";
                    break;
                }
            }
            return(null);
        }
        public void PushNews(string accessToken, string webPath, string tempStr)
        {
            OpenIdResultJson json = UserApi.Get(accessToken, "");
            var imgResult         = MediaApi.GetOthersMediaList(accessToken, UploadMediaFileType.image, 0, 10000);
            var DircetPath        = Environment.CurrentDirectory + "/image/";

            if (!Directory.Exists(DircetPath))
            {
                Directory.CreateDirectory(DircetPath);
            }

            for (int i = 0; i < 6; i++)
            {
                string imgName = string.Format("send{0}.jpg", i);
                if (imgResult.item.Find(p => p.name == imgName) == null)
                {
                    var imgPath  = webPath + "/image/" + imgName;
                    var filePath = DircetPath + "/image/" + imgName;
                    CommonUtility.HttpUtility.DownloadFile(imgPath, filePath);
                    var mediaId = MediaApi.UploadForeverMedia(accessToken, filePath).media_id;
                }
            }
            imgResult = MediaApi.GetOthersMediaList(accessToken, UploadMediaFileType.image, 0, 10000);


            string sendCountTxtUrl = webPath + "/" + "sendcount.txt";
            var    sendCountTxt    = CommonUtility.HttpUtility.Get(sendCountTxtUrl);
            var    sendCount       = int.Parse(sendCountTxt);

            NewsModel[] newsList = new NewsModel[sendCount];

            var dataSevice = new DataAccessSerive();
            var jobList    = dataSevice.GetTopJobInfoList();

            if (jobList.Count > 0)
            {
                List <Article> articles = new List <Article>();
                int            i        = 0;
                string         imgName;
                foreach (var job in jobList)
                {
                    if (i == sendCount)
                    {
                        break;
                    }
                    string domain  = ConfigurationManager.AppSettings.Get("domain");
                    string website = ConfigurationManager.AppSettings.Get("website");
                    imgName = "send" + i.ToString() + ".jpg";
                    string imgUrl    = string.Format("{0}/image/{1}", domain, imgName);
                    var    jobDetail = dataSevice.GetJobDetail(job.JobId);
                    var    news      = new NewsModel()
                    {
                        author  = "",
                        content = tempStr.Replace("[ComName]", job.ComName)
                                  .Replace("[ComBrief]", jobDetail.ComBrief)
                                  .Replace("[DetailPalce]", jobDetail.DetailPalce)
                                  .Replace("[LinkMan]", jobDetail.LinkMan)
                                  .Replace("[Phone]", jobDetail.Phone)
                                  .Replace("[JobName]", jobDetail.JobName)
                                  .Replace("[JobType]", jobDetail.JobType)
                                  .Replace("[LowMoney]", jobDetail.LowMoney)
                                  .Replace("[HrNum]", jobDetail.HrNum)
                                  .Replace("[Edu]", jobDetail.Edu)
                                  .Replace("[RegisterDate]", jobDetail.RegisterDate)
                                  .Replace("[EffectDate]", jobDetail.EffectDate)
                                  .Replace("[Other]", jobDetail.Other)
                                  .Replace("[Sex]", jobDetail.Sex)
                        ,
                        //content_source_url = domain + "/html/detail.html?id=" + job.JobId,
                        content_source_url = website,
                        digest             = job.ComName + "诚聘" + job.JobName,
                        show_cover_pic     = "0",
                        thumb_media_id     = imgResult.item.Find(p => p.name == imgName).media_id,
                        title = job.ComName + "诚聘" + job.JobName
                    };
                    newsList[i] = news;
                    i++;
                }
                UploadForeverMediaResult mediaResult = MediaApi.UploadNews(accessToken, 100000, newsList);
                try
                {
                    if (isDebug != "1")
                    {
                        GroupMessageApi.SendGroupMessageByGroupId(accessToken, "-1", mediaResult.media_id, GroupMessageType.mpnews, true);
                    }
                    Console.WriteLine("素材提交推送  推送成功");
                    logger.Info(DateTime.Now.ToString() + " 素材提交推送  推送成功");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("素材提交推送  推送失败 " + ex.Message);
                    var MailService = new MailSendFunc();
                    MailService.SendMail("*****@*****.**", ex.Message, "素材提交推送异常", mailCfg);
                    logger.ErrorException(DateTime.Now.ToString() + "素材提交推送失败 " + ex.Message, ex);
                }
            }
        }