/// <summary> /// 上传图文消息内的图片获取URL /// </summary> /// <param name="filePathName">包含完整访问路径的图片文件名</param> /// <returns>包含图片URL的微信响应结果</returns> public WeChatResult <WeChatURL> GetUrlByUpdateImg(string filePathName) { string accessToken = connect.GetAccessToken(); string url = $"https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={accessToken}"; string fileName = Path.GetFileName(filePathName); using (Stream fileStream = new FileStream(filePathName, FileMode.Open)) { string resultStr = SimulateRequest.UploadFile(new UploadFileParam(url, fileName, fileStream)); WeChatResult <WeChatURL> weChatResult = new WeChatResult <WeChatURL>(resultStr); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(MethodBase.GetCurrentMethod(), $"上传图文消息内的图片获取URLGetUrlByUpdateImg,微信服务报错:{weChatResult}"); } return(weChatResult); } }
/// <summary> /// 设置客服帐号的头像,头像图片文件必须是jpg格式,推荐使用640*640大小的图片以达到最佳效果 /// </summary> /// <param name="account">账号,如:[email protected]</param> /// <param name="filePathName">包含完整访问路径的文件名,文件必须是jpg格式,推荐使用640*640大小的图片</param> /// <returns>设置头像的微信结果</returns> public WeChatResult UpdateHeadImg(string account, string filePathName) { string accessToken = connect.GetAccessToken(); string url = $"http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token={accessToken}&kf_account={account}"; string fileName = Path.GetFileName(filePathName); using (Stream fileStream = new FileStream(filePathName, FileMode.Open)) { string resultStr = SimulateRequest.UploadFile(new UploadFileParam(url, fileName, fileStream)); WeChatResult weChatResult = new WeChatResult(resultStr); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(GetType().FullName, $"设置客服帐号的头像UpdateHeadImg,微信服务报错:{weChatResult}"); } return(weChatResult); } }
/// <summary> /// 删除群发消息 /// </summary> /// <param name="msgId">发送出去的消息ID</param> /// <param name="articleIndex">要删除的文章在图文消息中的位置,第一篇编号为1,该字段不填或填0会删除全部文章</param> /// <returns>删除结果</returns> public WeChatResult DeleteSendInfo(int msgId, int articleIndex = 0) { string accessToken = connect.GetAccessToken(); string url = $"https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token={accessToken}"; string resultData = SimulateRequest.HttpPost(url, new { msg_id = msgId, article_idx = articleIndex }); WeChatResult weChatResult = new WeChatResult(resultData); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(GetType().FullName, $"上传图文消息素材UpdateNews,微信服务报错:{weChatResult}"); } return(weChatResult); }
public void SendMsgTest() { CustomerServiceMsg serviceMsg = new ContentKFMsg() { touser = "", text = new Text_Msg() { content = "您好,互联01客服为您服务。" }, customservice = new KFAccount() { kf_account = "*****@*****.**" } }; WeChatResult wechatResult = customerServiceMsgLinkUp.SendMsg(serviceMsg); Assert.IsTrue(wechatResult.errcode == WeChatErrorCode.SUCCESS); }
/// <summary> /// 修改永久图文素材 /// </summary> /// <param name="mediaId">要修改的永久图文素材Id</param> /// <param name="index">要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义),第一篇为0</param> /// <returns>微信服务返回的修改结果</returns> public WeChatResult UpdateNews(string mediaId, int index, ArticleMaterial articleMaterial) { string accessToken = connect.GetAccessToken(); string url = "https://api.weixin.qq.com/cgi-bin/material/update_news?access_token=" + accessToken; string resultStr = SimulateRequest.HttpPost(url, new { media_id = mediaId, index, articles = articleMaterial }); WeChatResult weChatResult = new WeChatResult(resultStr); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(MethodBase.GetCurrentMethod(), $"修改永久图文素材UpdateNews,微信服务报错:{weChatResult}"); } return(weChatResult); }
/// <summary> /// 创建自定义菜单 /// </summary> /// <param name="menuButton">菜单按钮数组</param> /// <returns>微信服务返回的创建结果</returns> public WeChatResult CreateMenu(List <MenuButton> menuButtonList) { if (menuButtonList == null) { return(null); } string accessToken = connect.GetAccessToken(); string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;//POST string menuBtnData = JsonConvert.SerializeObject(new { button = menuButtonList }); string resultStr = SimulateRequest.HttpPost(url, menuBtnData); WeChatResult weChatResult = new WeChatResult(resultStr); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(GetType().FullName, $"创建自定义菜单CreateMenu,微信服务报错:{weChatResult}"); } return(weChatResult); }
/// <summary> /// 获取临时素材 /// </summary> /// <param name="mediaId">临时素材的媒体文件ID</param> /// <param name="filePathName">指定个临时包含路径的文件名</param> /// <returns>实际保存好的包含路径的文件名</returns> public WeChatResult <string> GetTempMaterial(string mediaId, string filePathName) { string accessToken = connect.GetAccessToken(); string url = $"https://api.weixin.qq.com/cgi-bin/media/get?access_token={accessToken}&media_id={mediaId}"; try { string fileName = SimulateRequest.DownloadFile(url, filePathName); WeChatResult <string> weChatResult = new WeChatResult <string>("{\"errcode\":0,\"errmsg\":\"SUCCESS\"}"); weChatResult.resultData = fileName; return(weChatResult); } catch (Exception ex) { SystemLogHelper.Error(MethodBase.GetCurrentMethod(), $"获取临时素材GetTempMaterial,报错", ex); WeChatResult <string> errorResult = new WeChatResult <string>(ex.Message); return(errorResult); } }
/// <summary> /// 修改客服帐号 /// </summary> /// <param name="account">账号,如:[email protected]</param> /// <param name="nickName">昵称,如:客服1</param> /// <param name="password">客服登录密码,内部会转成md5</param> /// <returns>修改的微信结果</returns> public WeChatResult UpdateAccount(string account, string nickName, string password) { string accessToken = connect.GetAccessToken(); string url = "https://api.weixin.qq.com/customservice/kfaccount/update?access_token=" + accessToken;//POST string postData = JsonConvert.SerializeObject( new { kf_account = account, nickname = nickName, password = EncryptHelper.HashMD532(password) }); string resultStr = SimulateRequest.HttpPost(url, postData); WeChatResult weChatResult = new WeChatResult(resultStr); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(GetType().FullName, $"修改客服帐号UpdateAccount,微信服务报错:{weChatResult}"); } return(weChatResult); }
/// <summary> /// 获取永久素材,返回ArticleItemsInfo、VideoMaterialResult或fileName /// </summary> /// <param name="mediaId">永久素材的媒体文件ID</param> /// <param name="filePathName">指定个临时包含路径的文件名</param> /// <returns>图文素材请解析为ArticleItemsInfo,视频素材请解析为VideoMaterialResult,其他素材为实际保存好的包含路径的文件名</returns> public WeChatResult <string> GetMaterial(string mediaId, string filePathName) { string accessToken = connect.GetAccessToken(); string url = $"https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={accessToken}"; try { string fileName = SimulateRequest.DownloadFilePost(url, filePathName, new { media_id = mediaId }); WeChatResult <string> weChatResult = new WeChatResult <string>("{\"errcode\":0,\"errmsg\":\"SUCCESS\"}"); weChatResult.resultData = fileName; return(weChatResult); } catch (Exception ex) { SystemLogHelper.Error(GetType().FullName, $"获取永久素材GetMaterial,报错", ex); WeChatResult <string> errorResult = new WeChatResult <string>(ex.Message); return(errorResult); } }
/// <summary> /// 创建预支付订单 /// </summary> /// <param name="param"></param> /// <returns></returns> public static WeChatResult UnifiedOrder(WeChatInfo param, string appName) { WeChatPayFactory factory = new WeChatPayFactory(appName); try { if (param == null) { throw new Exception("WeChatInfo is null"); } WeChatResult wxResult = factory.UnifiedOrder(param); //if (wxResult == null) throw new Exception("DAL.WeChat.WeChatPayFactory.UnifiedOrder()==0"); return(wxResult); } catch (Exception ex) { LogHelper.WriteLog(new Log() { message = ex.Message }, "UnifiedOrder"); throw ex; } }
/// <summary> /// 获取素材列表 /// </summary> /// <param name="type">素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)</param> /// <param name="offset">从全部素材的该偏移位置开始返回,0表示从第一个素材 返回</param> /// <param name="count">返回素材的数量,取值在1到20之间</param> /// <returns>微信服务返回的素材列表结果</returns> public WeChatResult <MaterialListInfo> GetMaterialList(string type, int offset, int count) { string accessToken = connect.GetAccessToken(); string url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accessToken; string resultStr = SimulateRequest.HttpPost(url, new { type, offset, count }); WeChatResult <MaterialListInfo> weChatResult = new WeChatResult <MaterialListInfo>(resultStr); weChatResult.resultData.item.Clear(); JObject wechatResultObj = JsonConvert.DeserializeObject <JObject>(resultStr); if ("news".Equals(type)) //图文消息素材 { weChatResult.resultData.item.AddRange(JsonConvert.DeserializeObject <List <NewsMaterialItem> >(wechatResultObj["item"].ToString())); } else //其他多媒体素材 { weChatResult.resultData.item.AddRange(JsonConvert.DeserializeObject <List <MediaMaterialItem> >(wechatResultObj["item"].ToString())); } if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(MethodBase.GetCurrentMethod(), $"获取素材列表GetMaterialList,微信服务报错:{weChatResult}"); } return(weChatResult); }
/// <summary> /// 第一步:请求CODE /// 第二步:通过code获取access_token /// 第三步:通过access_token调用接口 /// </summary> /// <param name="code"></param> /// <param name="state"></param> /// <returns></returns> public WeChatResult userLogin(string code, string state) { WeChatResult WXresult = new WeChatResult(); //直接登陆 //LoginUnionid("o30T-wQKMCy-LiyR6qHxzKnjFFAI"); //return new WeChatResult //{ // result = 2, //}; //以上代码发布前需要注释 WXresult.userinfo = new Wx_login_userinfo(); //通过code 和 state获取微信用户的基本信息 string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WholeSituation.WX_Login.LogAppid + "&secret=" + WholeSituation.WX_Login.LogSecret + "&code=" + code + "&grant_type=authorization_code"; //微信信息获取 openid try { WebClient wb = new WebClient(); Stream sc = wb.OpenRead(url); StreamReader sr = new StreamReader(sc); string result = sr.ReadToEnd(); Wx_login_Result li = JsonConvert.DeserializeObject <Wx_login_Result>(result); sc.Close(); sr.Close(); //用户存在的话直接登陆 if (li.unionid != null) { if (UserManager.Users.Where(t => t.unionid == li.unionid).Count() > 0) { if (LoginUnionid(li.unionid) == 1) { WXresult.result = 2; } else { WXresult.result = -1; } return(WXresult); } } else { if (UserManager.Users.Where(t => t.openid == li.openid).Count() > 0) { if (Login(li.openid) == 1) { WXresult.result = 2; } else { WXresult.result = -1; } return(WXresult); } } //获取验证失败 返回登陆失败标识码 if (li.access_token == null) { WXresult.result = 0; return(WXresult); } //通过openid 和access_token获取用户的基本信息 string url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + li.access_token + "&openid=" + li.openid + "&lang=zh-CN"; try { WebClient wb2 = new WebClient(); Stream sc2 = wb2.OpenRead(url2); StreamReader sr2 = new StreamReader(sc2); string result2 = sr2.ReadToEnd(); Wx_login_userinfo userinfo = JsonConvert.DeserializeObject <Wx_login_userinfo>(result2); sc2.Close(); sr2.Close(); //返回用户信息和用户为注册标识 WXresult.result = 1; WXresult.userinfo = userinfo; return(WXresult); } catch (Exception e) { //记录登录失败日志 WXresult.result = 0; return(WXresult); } } catch (Exception e) { //记录登录失败日志 WXresult.result = 0; return(WXresult); } }
public void SearchKFListTest() { WeChatResult <KFAccountInfo> wechatResult = customerServiceMsgLinkUp.SearchKFList(); Assert.IsTrue(wechatResult.errcode == WeChatErrorCode.SUCCESS); }
public ActionResult Register(WeChatRegister model) { WeChatResult viewModel = new WeChatResult { userinfo = new Wx_login_userinfo { openid = model.openid, nickname = model.nickname, sex = model.sex, language = model.language, country = model.country, province = model.province, headimgurl = model.headimgurl, unionid = model.unionid, }, result = 1 }; //ModelState.AddModelError("", "用户名不存在");//错误显示 UserInfo dbsuer = new UserInfo(); var create = dbsuer.WxRegister(model); if (create.result == 0 || create.result == -1) { //0重复 -1用户名不能包含汉字 string str = ""; if (create.resultEmail == 0 || create.resultName == 0 || create.resultPhone == 0) { if (create.resultEmail == 0) { str += "邮箱,"; } if (create.resultName == 0) { str += "用户名,"; } if (create.resultPhone == 0) { str += "电话,"; } ModelState.AddModelError("", str + "已存在,请重新填写"); return(View("CallBack", viewModel)); } else { ModelState.AddModelError("", "用户名只能包含字母和数字或下划线"); return(View("CallBack", viewModel)); } } else { //用户登录 var logresult = dbsuer.Login(create.userinfo); if (logresult == 1) { return(Redirect("/home")); } else { ModelState.AddModelError("", "服务器原因注册失败"); return(View()); } } }
/// <summary> /// 创建个性化菜单按钮,menuButton公众号的所有个性化菜单,最多只能设置为跳转到3个域名下的链接;matchrule共六个字段,均可为空,但至少要有一个匹配信息是不为空的 /// </summary> /// <param name="menuButton">菜单按钮数组,其中链接跳转不能多于3个</param> /// <param name="matchRule">matchrule共六个字段,均可为空,但不能全部为空,至少要有一个匹配信息是不为空的</param> /// <returns>微信服务返回的创建结果</returns> public WeChatResult <MenuCreateInfo> CreatePersonalMenu(List <MenuButton> menuButtonList, MatchRule matchRule) { if (menuButtonList == null) { return(null); } if (matchRule == null) { matchRule = new MatchRule() { country = "中国", province = "广东", language = "zh_CN" } } ; string menuBtnData = JsonConvert.SerializeObject(new { button = menuButtonList, matchrule = "{0}" }); //开始生成菜单按钮的个性化匹配规则 //country、province、city组成地区信息,将按照country、province、city的顺序进行验证,要符合地区信息表的内容。 //地区信息从大到小验证 StringBuilder ruleBuilder = new StringBuilder(); ruleBuilder.Append("{"); if (!string.IsNullOrEmpty(matchRule.tag_id)) { ruleBuilder.Append($"\"tag_id\":\"{matchRule.tag_id}\","); } if (matchRule.sex.HasValue) { ruleBuilder.Append($"\"sex\":\"{matchRule.sex}\","); } if (!string.IsNullOrEmpty(matchRule.country)) { ruleBuilder.Append($"\"country\":\"{matchRule.country}\","); } if (!string.IsNullOrEmpty(matchRule.province)) { ruleBuilder.Append($"\"province\":\"{matchRule.province}\","); } if (!string.IsNullOrEmpty(matchRule.city)) { ruleBuilder.Append($"\"city\":\"{matchRule.city}\","); } if (matchRule.client_platform_type.HasValue) { ruleBuilder.Append($"\"client_platform_type\":\"{matchRule.client_platform_type}\","); } if (!string.IsNullOrEmpty(matchRule.language)) { ruleBuilder.Append($"\"language\":\"{matchRule.language}\","); } if (ruleBuilder.ToString().EndsWith(",")) { ruleBuilder.Remove(ruleBuilder.Length - 1, 1); } ruleBuilder.Append("}"); string[] menuBtnSplitAry = menuBtnData.Split("\"{0}\"");//把"{0}"替换成matchRule对象 menuBtnData = string.Join(ruleBuilder.ToString(), menuBtnSplitAry); string accessToken = connect.GetAccessToken(); string url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=" + accessToken;//POST string resultStr = SimulateRequest.HttpPost(url, menuBtnData); WeChatResult <MenuCreateInfo> weChatResult = new WeChatResult <MenuCreateInfo>(resultStr); if (weChatResult.errcode != WeChatErrorCode.SUCCESS) { SystemLogHelper.Warn(GetType().FullName, $"创建个性化菜单CreatePersonalMenu,微信服务报错:{weChatResult}"); } return(weChatResult); }
public void ApiClearQuotaTest() { WeChatResult result = connectLinkUp.ApiClearQuota(); Assert.IsTrue(result.errcode == WeChatErrorCode.SUCCESS); }
/// <summary> /// 创建预支付订单 /// </summary> /// <param name="param"></param> /// <returns></returns> public WeChatResult UnifiedOrder(WeChatInfo param) { WeChatResult wxResult = new WeChatResult(); // 回调地址 string notifyUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["notifyUrl"].ToString(); try { // 检查服务端是否处于调整中 if (CheckServerMantain(param.costCenterCode)) { wxResult.isMantain = true; return(wxResult); } // 检查充值金额和设置是否符合 wxResult.matched = true; if (!CheckRechargeMatched(param)) { wxResult.matched = false; return(wxResult); } string openid = param.openId; string ordertime = SalesOrder.Common.convertDateTime(DateTime.Now.ToString()); bool isTestUser = (new RechargeFactory()).GetUserInfo(openid).isTestUser; // 本地交易号前三位(用于在商户平台上区分支付场景,回调时手动去除不存数据库) string fcode = wcf.paymentCode; int len = fcode.Length; /***统一下单1***/ WxPayData data = new WxPayData(wcf); data.SetValue("body", param.costCenterCode + "-餐卡充值"); data.SetValue("attach", param.appName); data.SetValue("out_trade_no", fcode + WxPayApi.GenerateOutTradeNo(param.costCenterCode)); //data.SetValue("total_fee", param.total_fee); data.SetValue("total_fee", isTestUser ? 1 : param.total_fee); data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(5).ToString("yyyyMMddHHmmss")); //data.SetValue("goods_tag", "test"); data.SetValue("trade_type", "JSAPI"); data.SetValue("openid", openid); data.SetValue("notify_url", notifyUrl); WriteLog(data.ToJson().ToString()); if (param.total_fee > 0) { WxPayData result = WxPayApi.UnifiedOrder(wcf, data); WriteLog(result.ToJson().ToString()); if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "") { Log.Error(this.GetType().ToString(), "UnifiedOrder response error!"); throw new WxPayException("UnifiedOrder response error!"); } wxResult.prepay_id = result.GetValue("prepay_id").ToString(); wxResult.paySign = result.GetValue("sign").ToString(); wxResult.nonceStr = result.GetValue("nonce_str").ToString(); } /***订单写入本地***/ string st = data.GetValue("out_trade_no").ToString(); WxOrder order = new WxOrder { appName = param.appName, type = param.type, cardId = param.cardId, out_trade_no = st.Substring(len, st.Length - len), openid = data.GetValue("openid").ToString(), attach = data.GetValue("attach").ToString(), coupons = param.coupons == null || !param.coupons.Any() ? null : param.coupons.SelectMany(q => q).Where(q => !string.IsNullOrWhiteSpace(q)).GroupBy(q => q) .Select(q => new Coupon { price = int.Parse(q.Key), qty = q.Count() }).ToList(), total_fee = int.Parse(data.GetValue("total_fee").ToString()), time_start = data.GetValue("time_start").ToString(), time_expire = data.GetValue("time_expire").ToString() }; WxOrderFactory wof = new WxOrderFactory(); /***本地没有写成功的话直接返回NULL***/ if (wof.CreatePayOrder(order) <= 0) { return(null); } return(wxResult); } catch (Exception e) { throw e; } }