新乡民调(来自息县民调) - 主标

WxHelper.cs 17KB

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