PingAnYeXianSZCG_API 接口代码

WxHelper.cs 16KB

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