PingAnYeXianSZCG_API 接口代码

WxHelper.cs 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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.CommonAPIs;
  8. using Senparc.Weixin.MP.TenPayLibV3;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Net.Security;
  16. using System.Security.Cryptography.X509Certificates;
  17. using System.Text;
  18. using System.Web;
  19. using System.Xml.Linq;
  20. namespace CallCenterAPI.WechatSDK
  21. {
  22. public static class WxHelper
  23. {
  24. public static string WxId;
  25. public static string AppId;
  26. public static string AppSecret;
  27. public static string WechatMchid;
  28. public static string WechatKey;
  29. public static string WechatPath;
  30. public static string WechatClientIp;
  31. public static string CommonToken;//Common的Token
  32. public static DateTime GetCommonTokenDate;//获取CommonToken的时间
  33. public static int CommonTokenExpiresIn;//有效时间(s)
  34. static WxHelper()
  35. {
  36. AppId = Configs.GetValue("WechatAppid");
  37. AppSecret = Configs.GetValue("WechatAppsecret");
  38. WechatMchid= Configs.GetValue("WechatMchid");
  39. WechatKey = Configs.GetValue("WechatKey");
  40. WechatPath = Configs.GetValue("WechatPath");
  41. WechatClientIp = Configs.GetValue("WechatClientIp");
  42. }
  43. /// <summary>
  44. /// 获取openid
  45. /// </summary>
  46. /// <param name="wxLoginDto"></param>
  47. /// <returns></returns>
  48. public static WxLoginDto GetOpenId(WxLoginDto wxLoginDto)
  49. {
  50. if (string.IsNullOrWhiteSpace(wxLoginDto.Code))
  51. {
  52. var url = OAuthApi.GetAuthorizeUrl(AppId, wxLoginDto.RedirectUrl, "qwertyuidfghjkl", OAuthScope.snsapi_base);
  53. wxLoginDto.RedirectUrl = url;
  54. return wxLoginDto;
  55. }
  56. var access = OAuthApi.GetAccessToken(AppId, AppSecret, wxLoginDto.Code);
  57. wxLoginDto.OpenId = access.openid;
  58. return wxLoginDto;
  59. }
  60. /// <summary>
  61. /// 获取common的token
  62. /// </summary>
  63. /// <returns></returns>
  64. public static string GetCommonToken()
  65. {
  66. double ss = DateTime.Now.Subtract(GetCommonTokenDate).TotalSeconds;
  67. if (ss > CommonTokenExpiresIn)
  68. {
  69. var obj = CommonApi.GetToken(AppId, AppSecret);
  70. if (obj != null && obj.errcode == ReturnCode.请求成功)
  71. {
  72. GetCommonTokenDate = DateTime.Now.AddSeconds(-1);
  73. CommonTokenExpiresIn = obj.expires_in;
  74. CommonToken = obj.access_token;
  75. }
  76. else
  77. {
  78. CommonToken = "";
  79. }
  80. }
  81. return CommonToken;
  82. }
  83. public static bool CheckSignature(string signature, string timestamp, string nonce, string token)
  84. {
  85. bool bl = false;
  86. string accesstoken = GetCommonToken();
  87. if (accesstoken != "")
  88. {
  89. bl = Senparc.Weixin.MP.CheckSignature.Check(signature, timestamp, nonce, token);
  90. }
  91. return bl;
  92. }
  93. #region 多客服
  94. /// <summary>
  95. /// 创建客服会话
  96. /// </summary>
  97. /// <param name="openid"></param>
  98. /// <returns></returns>
  99. public static bool CreateSession(string openid)
  100. {
  101. bool bl = false;
  102. string accesstoken = GetCommonToken();
  103. if (accesstoken != "")
  104. {
  105. CustomApi.SendText(accesstoken, openid, "您好,正在为您接通人工客服,请稍候......");
  106. var zxlist = CustomServiceApi.GetCustomOnlineInfo(accesstoken).kf_online_list;//在线客服列表
  107. if (zxlist.Count > 0)
  108. {
  109. var kf = zxlist.OrderBy(p => p.accepted_case).FirstOrDefault();//获取当前已经接入用户最少的客服
  110. if (kf != null)
  111. {
  112. var obj = CustomServiceApi.CreateSession(accesstoken, openid, kf.kf_account);//创建客服和用户之间的会话
  113. if (obj.errcode == ReturnCode.请求成功)
  114. {
  115. bl = true;
  116. }
  117. else
  118. {
  119. CustomApi.SendText(accesstoken, openid, "接通人工客服异常,请重试");
  120. }
  121. }
  122. else
  123. {
  124. CustomApi.SendText(accesstoken, openid, "人工客服正在忙碌中,请稍候联系");
  125. }
  126. }
  127. }
  128. return bl;
  129. }
  130. /// <summary>
  131. /// 关闭客服会话
  132. /// </summary>
  133. /// <param name="openid"></param>
  134. /// <returns></returns>
  135. public static bool CloseSession(string openid, string kf_account)
  136. {
  137. bool bl = false;
  138. string accesstoken = GetCommonToken();
  139. if (accesstoken != "")
  140. {
  141. var obj = CustomServiceApi.CloseSession(accesstoken, openid, kf_account);
  142. if (obj.errcode == ReturnCode.请求成功)
  143. {
  144. bl = true;
  145. CustomApi.SendText(accesstoken, openid, "已经关闭与人工客服的会话");
  146. }
  147. else
  148. {
  149. CustomApi.SendText(accesstoken, openid, "关闭会话异常,请重试");
  150. }
  151. }
  152. return bl;
  153. }
  154. /// <summary>
  155. /// 获取用户聊天记录
  156. /// </summary>
  157. /// <param name="stime"></param>
  158. /// <param name="etime"></param>
  159. /// <param name="pageSize"></param>
  160. /// <param name="pageIndex"></param>
  161. /// <returns></returns>
  162. public static List<object> GetRecord(DateTime stime, DateTime etime, int pageSize, int pageIndex)
  163. {
  164. List<object> list = new List<object>();
  165. string accesstoken = GetCommonToken();
  166. if (accesstoken != "")
  167. {
  168. var result = CustomServiceApi.GetRecord(accesstoken, stime, etime, pageSize, pageIndex);
  169. if (result.errcode == ReturnCode.请求成功)
  170. {
  171. list = result.recordlist.Select(p =>
  172. {
  173. var binfo = CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault();
  174. var uinfo = UserApi.Info(accesstoken, p.openid);
  175. return new
  176. {
  177. p.openid,
  178. p.opercode,
  179. p.text,
  180. p.worker,
  181. time = GetTime(p.time).ToString("yyyy-MM-dd HH:mm:ss"),
  182. receiver = p.opercode == Opercode.客服收到消息 ? binfo.kf_nick + "(客服)" : uinfo.nickname,
  183. sender = p.opercode == Opercode.客服发送消息 ? binfo.kf_nick + "(客服)" : uinfo.nickname
  184. };
  185. }).ToList<object>();
  186. }
  187. }
  188. return list;
  189. }
  190. /// <summary>
  191. /// 获取聊天记录
  192. /// </summary>
  193. /// <param name="stime"></param>
  194. /// <param name="etime"></param>
  195. /// <param name="pageSize"></param>
  196. /// <param name="pageIndex"></param>
  197. /// <returns></returns>
  198. public static List<object> GetMsgList(DateTime stime, DateTime etime, long msgid, int number)
  199. {
  200. List<object> list = new List<object>();
  201. string accesstoken = GetCommonToken();
  202. if (accesstoken != "")
  203. {
  204. var result = CustomServiceApi.GetMsgList(accesstoken, stime, etime, msgid, number);
  205. if (result.errcode == ReturnCode.请求成功)
  206. {
  207. list = result.recordList.Select(p => new
  208. {
  209. p.openid,
  210. p.opercode,
  211. p.text,
  212. p.worker,
  213. time = p.time.ToString("yyyy-MM-dd HH:mm:ss"),
  214. name = UserApi.Info(accesstoken, p.openid).nickname,
  215. kfname = CustomServiceApi.GetCustomBasicInfo(accesstoken).kf_list.Where(d => d.kf_account == p.worker).FirstOrDefault().kf_nick
  216. }).ToList<object>();
  217. }
  218. }
  219. return list;
  220. }
  221. /// <summary>
  222. /// 获取时间
  223. /// </summary>
  224. /// <param name="dt"></param>
  225. /// <returns></returns>
  226. public static DateTime GetTime(double dt)
  227. {
  228. DateTime time = DateTime.MinValue;
  229. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  230. time = startTime.AddSeconds(dt);
  231. return time;
  232. }
  233. #endregion
  234. #region 企业向用户发红包
  235. public static bool TenPay(decimal amount,string openid)
  236. {
  237. #region 发送红包
  238. bool fals = false; //记录发送红包是否成功
  239. string msg = "";
  240. string xmlResult = null; //现金红包接口返回的xml
  241. string certPath = null; //证书在服务器的物理位置
  242. string data = null; //调用现金红包接口需要的数据
  243. try
  244. {
  245. //创建支付应答对象
  246. CallCenter.Utility.RequestHandler packageReqHandler = new CallCenter.Utility.RequestHandler(null);
  247. //初始化
  248. packageReqHandler.Init();
  249. string nonceStr = TenPayV3Util.GetNoncestr(); //时间戳
  250. //设置package订单参数
  251. packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串,不长于32位
  252. var r = new Random(Guid.NewGuid().GetHashCode());//随机数
  253. var dd = DateTime.Now.ToString("yyyymmdd");//日期yyyymmdd
  254. packageReqHandler.SetParameter("mch_billno", WechatMchid + dd+ r.Next(0, 10));//商户订单号(每个订单号必须唯一)组成:mch_id+yyyymmdd+10位一天内不能重复的数字。接口根据商户订单号支持重入,如出现超时可再调用。
  255. packageReqHandler.SetParameter("mch_id", WechatMchid); //微信支付分配的商户号
  256. packageReqHandler.SetParameter("wxappid", AppId);//微信分配的公众账号ID(企业号corpid即为此appId)。接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。
  257. packageReqHandler.SetParameter("send_name", "叶县政法委");//商户名称
  258. packageReqHandler.SetParameter("re_openid", openid); //用户openid 接受红包的用户用户在wxappid下的openid
  259. packageReqHandler.SetParameter("total_amount", Convert.ToInt32(amount * 100M).ToString(CultureInfo.InvariantCulture));//红包类型
  260. packageReqHandler.SetParameter("total_num", "1");//红包发放总人数
  261. packageReqHandler.SetParameter("wishing", "测试红包"); //红包祝福语
  262. packageReqHandler.SetParameter("client_ip", WechatClientIp);//Ip地址
  263. packageReqHandler.SetParameter("act_name", "测试红包"); //活动名称
  264. packageReqHandler.SetParameter("remark", "测试红包"); //备注
  265. string sign = packageReqHandler.CreateMd5Sign("key", WechatKey);
  266. packageReqHandler.SetParameter("sign", sign); //签名:生成签名方式查看签名算法
  267. data = packageReqHandler.ParseXML();
  268. certPath = WechatPath;
  269. xmlResult = Sendredpack(data, WechatMchid, certPath);
  270. var res = XDocument.Parse(xmlResult);
  271. string return_code = res.Element("xml").Element("return_code").Value;
  272. if ("SUCCESS".Equals(return_code))
  273. {
  274. string result_code = res.Element("xml").Element("result_code").Value;
  275. if ("SUCCESS".Equals(result_code))
  276. {
  277. fals = true;
  278. }
  279. else
  280. {
  281. msg = res.Element("xml").Element("err_code_des").Value;
  282. }
  283. }
  284. else
  285. {
  286. msg = res.Element("xml").Element("return_msg").Value;
  287. }
  288. }
  289. catch (Exception exception)
  290. {
  291. msg = exception.Message;
  292. }
  293. #endregion
  294. return fals;
  295. }
  296. /// <summary>
  297. /// 用于企业向微信用户个人发红包
  298. /// 目前支持向指定微信用户的openid个人发红包
  299. /// </summary>
  300. /// <param name="certPassword">apiclient_cert.p12证书密码即商户号</param>
  301. /// <param name="data">微信支付需要post的xml数据</param>
  302. /// <param name="certPath">apiclient_cert.p12的证书物理位置(例如:E:\projects\文档\微信商户平台证书\商户平台API证书</param>
  303. /// <param name="timeOut"></param>
  304. /// <returns></returns>
  305. public static string Sendredpack(string data, string certPassword, string certPath, int timeOut = Config.TIME_OUT)
  306. {
  307. var urlFormat = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
  308. string cert = HttpContext.Current.Request.PhysicalApplicationPath+ certPath;
  309. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  310. X509Certificate2 cer = new X509Certificate2(cert, certPassword);
  311. var formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
  312. MemoryStream ms = new MemoryStream();
  313. ms.Write(formDataBytes, 0, formDataBytes.Length);
  314. ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
  315. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlFormat);
  316. request.ClientCertificates.Add(cer);
  317. request.Method = "POST";
  318. request.Timeout = timeOut;
  319. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
  320. #region 输入二进制流
  321. if (ms != null)
  322. {
  323. ms.Position = 0;
  324. //直接写入流
  325. Stream requestStream = request.GetRequestStream();
  326. byte[] buffer = new byte[1024];
  327. int bytesRead = 0;
  328. while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
  329. {
  330. requestStream.Write(buffer, 0, bytesRead);
  331. }
  332. ms.Close();//关闭文件访问
  333. }
  334. #endregion
  335. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  336. using (Stream responseStream = response.GetResponseStream())
  337. {
  338. using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
  339. {
  340. string retString = myStreamReader.ReadToEnd();
  341. return retString;
  342. }
  343. }
  344. }
  345. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  346. {
  347. if (errors == SslPolicyErrors.None)
  348. return true;
  349. return false;
  350. }
  351. #endregion
  352. }
  353. }