Brak opisu

WxHelper.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using CallCenter.Utility;
  2. using CallCenterAPI.WechatSDK.Models;
  3. using Senparc.Weixin;
  4. using Senparc.Weixin.MP;
  5. using Senparc.Weixin.MP.AdvancedAPIs;
  6. using Senparc.Weixin.MP.AdvancedAPIs.CustomService;
  7. using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
  8. using Senparc.Weixin.MP.CommonAPIs;
  9. using Senparc.Weixin.MP.Containers;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace CallCenterAPI.WechatSDK
  16. {
  17. public static class WxHelper
  18. {
  19. public static string WxId;
  20. public static string AppId;
  21. public static string AppSecret;
  22. public static string RedirectUrl;
  23. public static string MessageUrl;
  24. public static string TemplateId;
  25. public static string CommonToken;//Common的Token
  26. public static DateTime GetCommonTokenDate;//获取CommonToken的时间
  27. public static int CommonTokenExpiresIn;//有效时间(s)
  28. static WxHelper()
  29. {
  30. AppId = Configs.GetValue("WechatAppid");
  31. AppSecret = Configs.GetValue("WechatAppsecret");
  32. MessageUrl = Configs.GetValue("MessageUrl");
  33. TemplateId = Configs.GetValue("TemplateId");
  34. //根据appId判断获取
  35. if (!AccessTokenContainer.CheckRegistered(AppId)) //检查是否已经注册
  36. {
  37. AccessTokenContainer.Register(AppId, AppSecret); //如果没有注册则进行注册
  38. }
  39. }
  40. /// <summary>
  41. /// 获取openid
  42. /// </summary>
  43. /// <param name="wxLoginDto"></param>
  44. /// <returns></returns>
  45. public static WxLoginDto GetOpenId(WxLoginDto wxLoginDto)
  46. {
  47. if (string.IsNullOrWhiteSpace(wxLoginDto.Code))
  48. {
  49. var url = OAuthApi.GetAuthorizeUrl(AppId, wxLoginDto.RedirectUrl, "qwertyuidfghjkl", OAuthScope.snsapi_base);
  50. wxLoginDto.RedirectUrl = url;
  51. return wxLoginDto;
  52. }
  53. var access = OAuthApi.GetAccessToken(AppId, AppSecret, wxLoginDto.Code);
  54. wxLoginDto.OpenId = access.openid;
  55. return wxLoginDto;
  56. }
  57. /// <summary>
  58. /// 获取common的token
  59. /// </summary>
  60. /// <returns></returns>
  61. public static string GetCommonToken()
  62. {
  63. double ss = DateTime.Now.Subtract(GetCommonTokenDate).TotalSeconds;
  64. if (ss > CommonTokenExpiresIn)
  65. {
  66. var obj = CommonApi.GetToken(AppId, AppSecret);
  67. if (obj != null && obj.errcode == ReturnCode.请求成功)
  68. {
  69. GetCommonTokenDate = DateTime.Now.AddSeconds(-1);
  70. CommonTokenExpiresIn = obj.expires_in;
  71. CommonToken = obj.access_token;
  72. }
  73. else
  74. {
  75. CommonToken = "";
  76. }
  77. }
  78. return CommonToken;
  79. }
  80. public static bool CheckSignature(string signature, string timestamp, string nonce, string token)
  81. {
  82. bool bl = false;
  83. string accesstoken = GetCommonToken();
  84. if (accesstoken != "")
  85. {
  86. bl = Senparc.Weixin.MP.CheckSignature.Check(signature, timestamp, nonce, token);
  87. }
  88. return bl;
  89. }
  90. #region 多客服
  91. /// <summary>
  92. /// 创建客服会话
  93. /// </summary>
  94. /// <param name="openid"></param>
  95. /// <returns></returns>
  96. public static bool CreateSession(string openid)
  97. {
  98. bool bl = false;
  99. string accesstoken = GetCommonToken();
  100. if (accesstoken != "")
  101. {
  102. CustomApi.SendText(accesstoken, openid, "您好,正在为您接通人工客服,请稍候......");
  103. var zxlist = CustomServiceApi.GetCustomOnlineInfo(accesstoken).kf_online_list;//在线客服列表
  104. if (zxlist.Count > 0)
  105. {
  106. var kf = zxlist.OrderBy(p => p.accepted_case).FirstOrDefault();//获取当前已经接入用户最少的客服
  107. if (kf != null)
  108. {
  109. var obj = CustomServiceApi.CreateSession(accesstoken, openid, kf.kf_account);//创建客服和用户之间的会话
  110. if (obj.errcode == ReturnCode.请求成功)
  111. {
  112. bl = true;
  113. }
  114. else
  115. {
  116. CustomApi.SendText(accesstoken, openid, "接通人工客服异常,请重试");
  117. }
  118. }
  119. else
  120. {
  121. CustomApi.SendText(accesstoken, openid, "人工客服正在忙碌中,请稍候联系");
  122. }
  123. }
  124. }
  125. return bl;
  126. }
  127. /// <summary>
  128. /// 关闭客服会话
  129. /// </summary>
  130. /// <param name="openid"></param>
  131. /// <returns></returns>
  132. public static bool CloseSession(string openid, string kf_account)
  133. {
  134. bool bl = false;
  135. string accesstoken = GetCommonToken();
  136. if (accesstoken != "")
  137. {
  138. var obj = CustomServiceApi.CloseSession(accesstoken, openid, kf_account);
  139. if (obj.errcode == ReturnCode.请求成功)
  140. {
  141. bl = true;
  142. CustomApi.SendText(accesstoken, openid, "已经关闭与人工客服的会话");
  143. }
  144. else
  145. {
  146. CustomApi.SendText(accesstoken, openid, "关闭会话异常,请重试");
  147. }
  148. }
  149. return bl;
  150. }
  151. /// <summary>
  152. /// 获取用户聊天记录
  153. /// </summary>
  154. /// <param name="stime"></param>
  155. /// <param name="etime"></param>
  156. /// <param name="pageSize"></param>
  157. /// <param name="pageIndex"></param>
  158. /// <returns></returns>
  159. public static List<object> GetRecord(DateTime stime, DateTime etime, int pageSize, int pageIndex)
  160. {
  161. List<object> list = new List<object>();
  162. string accesstoken = GetCommonToken();
  163. if (accesstoken != "")
  164. {
  165. var result = CustomServiceApi.GetRecord(accesstoken, stime, etime, pageSize, pageIndex);
  166. if (result.errcode == ReturnCode.请求成功)
  167. {
  168. list = result.recordlist.Select(p => new
  169. {
  170. p.openid,
  171. p.text,
  172. time = GetTime(p.time).ToString("yyyy-MM-dd HH:mm:ss"),
  173. receiver = p.opercode == Opercode.客服收到消息 ? CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick + "(客服)" : UserApi.Info(accesstoken, p.openid).nickname,
  174. sender = p.opercode == Opercode.客服发送消息 ? CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick + "(客服)" : UserApi.Info(accesstoken, p.openid).nickname
  175. }).ToList<object>();
  176. }
  177. }
  178. return list;
  179. }
  180. /// <summary>
  181. /// 获取聊天记录
  182. /// </summary>
  183. /// <param name="stime"></param>
  184. /// <param name="etime"></param>
  185. /// <param name="pageSize"></param>
  186. /// <param name="pageIndex"></param>
  187. /// <returns></returns>
  188. public static List<object> GetMsgList(DateTime stime, DateTime etime, long msgid, int number)
  189. {
  190. List<object> list = new List<object>();
  191. string accesstoken = GetCommonToken();
  192. if (accesstoken != "")
  193. {
  194. var result = CustomServiceApi.GetMsgList(accesstoken, stime, etime, msgid, number);
  195. if (result.errcode == ReturnCode.请求成功)
  196. {
  197. list = result.recordList.Select(p => new
  198. {
  199. p.openid,
  200. p.opercode,
  201. p.text,
  202. p.worker,
  203. time = p.time.ToString("yyyy-MM-dd HH:mm:ss"),
  204. name = UserApi.Info(accesstoken, p.openid).nickname,
  205. kfname = CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick
  206. }).ToList<object>();
  207. }
  208. }
  209. return list;
  210. }
  211. /// <summary>
  212. /// 获取时间
  213. /// </summary>
  214. /// <param name="dt"></param>
  215. /// <returns></returns>
  216. public static DateTime GetTime(double dt)
  217. {
  218. DateTime time = DateTime.MinValue;
  219. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  220. time = startTime.AddSeconds(dt);
  221. return time;
  222. }
  223. #endregion
  224. #region 微信方法
  225. /// <summary>
  226. /// 发送微信模板消息
  227. /// </summary>
  228. /// <param name="wocode">工单编号</param>
  229. /// <param name="title">标题</param>
  230. /// <param name="content">内容</param>
  231. /// <param name="url">链接地址</param>
  232. /// <param name="openid">接收方</param>
  233. /// <param name="templateid">模板id</param>
  234. public static object SendWechatMsg1(string wocode, string title, string wotype,string state, string content, string orderid, string openid, string templateid = "")
  235. {
  236. var url = "id=" + orderid + "&type=" + state;
  237. var obj = new
  238. {
  239. first = new { value = title, color = "#173177" },
  240. keyword1 = new { value = wotype },
  241. keyword2 = new { value = wocode },
  242. remark = new { value = content }
  243. };
  244. //{ { first.DATA} }
  245. //工单类型:{ { keyword1.DATA} }
  246. //工单编号:{ { keyword2.DATA} }
  247. //{ { remark.DATA} }
  248. var sendResult = SendTemplateMsg(openid, url, obj, templateid);
  249. return sendResult;
  250. }
  251. public static object SendWechatMsg(string wocode, string title, string statename, string content, string tel, string url, string openid, string templateid = "")
  252. {
  253. url = "id=" + url;
  254. var obj = new
  255. {
  256. first = new { value = title, color = "#173177" },
  257. keyword1 = new { value = wocode },
  258. keyword2 = new { value = statename },
  259. keyword3 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
  260. keyword4 = new { value = tel },
  261. remark = new { value = content }
  262. };
  263. //var obj = new
  264. //{
  265. // first = new { value = title, color = "#173177" },
  266. // keyword1 = new { value = wocode },
  267. // keyword2 = new { value = statename },
  268. // keyword3 = new { value = tel },
  269. // remark = new { value = content }
  270. //};
  271. var sendResult = SendTemplateMsg(openid, url, obj, templateid);
  272. return sendResult;
  273. }
  274. /// <summary>
  275. /// 发送模板消息【需要安全验证】
  276. /// </summary>
  277. /// <param name="openid"></param>
  278. /// <param name="url"></param>
  279. /// <param name="jsondata"></param>
  280. /// <param name="templateid"></param>
  281. /// <returns></returns>
  282. public static object SendTemplateMsg(string openid, string url, object jsondata, string templateid)
  283. {
  284. var log = LogFactory.GetLogger("发送模板消息1");
  285. try
  286. {
  287. //string accesstoken = GetCommonToken();
  288. if (string.IsNullOrEmpty(templateid))
  289. {
  290. templateid = TemplateId;
  291. }
  292. if (MessageUrl.IndexOf("?") != -1)
  293. {
  294. url = MessageUrl + "&" + url;
  295. }
  296. else
  297. {
  298. url = MessageUrl + "?" + url;
  299. }
  300. //var result = TemplateApi.SendTemplateMessageAsync(AppId, openid, templateid, url, jsondata.ToJObject());
  301. SendTemplateMessageResult sendResult = TemplateApi.SendTemplateMessage(AppId, openid, templateid, url, jsondata);
  302. //return AppId + "||||" + openid + "||||" + templateid + "||||" + url + "||||" ;
  303. object result = sendResult;
  304. //log.Error("发送模板消息1:" + sendResult + "||||:" + AppId + "||||" + openid + "||||" + templateid + "||||" + url + "||||" + jsondata.ToJson());
  305. return result;
  306. }
  307. catch (Exception ex)
  308. {
  309. log.Error("发送模板消息:如果你只是拿到了用户的openid,但该用户没有关注公众号,发送时会抛出下面的错误:" + ex.Message);
  310. return "请求接口失败";
  311. }
  312. }
  313. #endregion
  314. }
  315. }