ConsumersController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using Microsoft.AspNetCore.Authorization;
  9. using System.Web;
  10. using MySystem.MainModels;
  11. using LitJson;
  12. using Library;
  13. using System.Security.Cryptography;
  14. using System.Text;
  15. using Aop.Api;
  16. using Aop.Api.Request;
  17. using Aop.Api.Response;
  18. using System.Collections;
  19. using Aop.Api.Util;
  20. namespace MySystem.Areas.Api.Controllers.v1
  21. {
  22. [Area("Api")]
  23. [Route("Api/v1/[controller]/[action]")]
  24. public class ConsumersController : BaseController
  25. {
  26. public ConsumersController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
  27. {
  28. }
  29. #region 消费者-微信小程序通过code获取openid
  30. [Authorize]
  31. public JsonResult WeChatMiniOpenId(string value)
  32. {
  33. value = DesDecrypt(value);
  34. JsonData data = JsonMapper.ToObject(value);
  35. AppResultJson result = WeChatMiniOpenIdDo(value);
  36. return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
  37. }
  38. public AppResultJson WeChatMiniOpenIdDo(string value)
  39. {
  40. JsonData data = JsonMapper.ToObject(value);
  41. string code = data["code"].ToString(); //微信小程序获取的code
  42. string nickName = data["nickName"].ToString(); //昵称
  43. string avatarUrl = data["avatarUrl"].ToString(); //头像地址
  44. string encryptedData = data["encryptedData"].ToString(); //微信小程序获取手机号的数据包
  45. string iv = data["iv"].ToString(); //微信小程序获取手机号的IV
  46. Dictionary<string, object> Obj = new Dictionary<string, object>();
  47. // PublicAccountSet set = RedisDbconn.Instance.Get<PublicAccountSet>("PublicAccountSet") ?? new PublicAccountSet();
  48. string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + new WeChatFunction().AppId + "&secret=" + new WeChatFunction().AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
  49. function.WriteLog(url, "微信小程序通过code获取openid");
  50. string result = function.GetWebRequest(url);
  51. function.WriteLog(result + "\n", "微信小程序通过code获取openid");
  52. JsonData jsonObj = JsonMapper.ToObject(result);
  53. string openid = jsonObj["openid"].ToString();
  54. string session_key = jsonObj["session_key"].ToString();
  55. string mobile = getPhoneNumber(encryptedData, iv, session_key)["Mobile"];
  56. if (mobile == "err")
  57. {
  58. Obj.Add("ConsumerId", "");
  59. return new AppResultJson() { Status = "-1", Info = "授权失败,请重试", Data = Obj };
  60. }
  61. int ConsumerId = 0;
  62. Consumers check = maindb.Consumers.FirstOrDefault(m => m.WechatOpenId == openid);
  63. if (check == null)
  64. {
  65. check = maindb.Consumers.Add(new Consumers()
  66. {
  67. CreateDate = DateTime.Now,
  68. NickName = filterEmoji(nickName),
  69. HeadPhoto = avatarUrl,
  70. Mobile = mobile,
  71. WechatOpenId = openid,
  72. }).Entity;
  73. maindb.SaveChanges();
  74. ConsumerId = check.Id;
  75. maindb.ConsumerOpenIds.Add(new ConsumerOpenIds()
  76. {
  77. OpenId = openid,
  78. ConsumerId = ConsumerId,
  79. });
  80. maindb.SaveChanges();
  81. }
  82. else
  83. {
  84. check.NickName = filterEmoji(nickName);
  85. check.HeadPhoto = avatarUrl;
  86. check.Mobile = mobile;
  87. ConsumerId = check.Id;
  88. maindb.SaveChanges();
  89. }
  90. Obj.Add("ConsumerId", ConsumerId); //消费者Id
  91. return new AppResultJson() { Status = "1", Info = "", Data = Obj };
  92. }
  93. public Dictionary<string, string> getPhoneNumber(string encryptedData, string iv, string session_key)
  94. {
  95. Dictionary<string, string> Obj = new Dictionary<string, string>();
  96. try
  97. {
  98. byte[] encryData = Convert.FromBase64String(encryptedData);
  99. RijndaelManaged rijndaelCipher = new RijndaelManaged();
  100. rijndaelCipher.Key = Convert.FromBase64String(session_key);
  101. rijndaelCipher.IV = Convert.FromBase64String(iv);
  102. rijndaelCipher.Mode = CipherMode.CBC;
  103. rijndaelCipher.Padding = PaddingMode.PKCS7;
  104. ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
  105. byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
  106. string result = Encoding.Default.GetString(plainText);
  107. dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
  108. string phoneNumber = model.phoneNumber;
  109. //return model.phoneNumber;
  110. if (string.IsNullOrEmpty(phoneNumber))
  111. {
  112. phoneNumber = "";
  113. }
  114. Obj.Add("Mobile", phoneNumber);
  115. }
  116. catch(Exception ex)
  117. {
  118. Obj.Add("Mobile", "err");
  119. function.WriteLog(DateTime.Now.ToString(), "微信小程序获取手机号异常");
  120. function.WriteLog(encryptedData, "微信小程序获取手机号异常");
  121. function.WriteLog(iv, "微信小程序获取手机号异常");
  122. function.WriteLog(session_key, "微信小程序获取手机号异常");
  123. function.WriteLog(ex.ToString(), "微信小程序获取手机号异常");
  124. function.WriteLog("\r\n\r\n", "微信小程序获取手机号异常");
  125. }
  126. return Obj;
  127. }
  128. public string filterEmoji(string str)
  129. {
  130. string origin = str;
  131. try
  132. {
  133. //关键代码
  134. foreach (var a in str)
  135. {
  136. byte[] bts = System.Text.Encoding.UTF32.GetBytes(a.ToString());
  137. if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
  138. {
  139. str = str.Replace(a.ToString(), "");
  140. }
  141. }
  142. }
  143. catch
  144. {
  145. str = origin;
  146. }
  147. return str;
  148. }
  149. #endregion
  150. #region 消费者-支付宝通过code获取openid
  151. [Authorize]
  152. public JsonResult AlipayMiniOpenId(string value)
  153. {
  154. if (string.IsNullOrEmpty(value))
  155. {
  156. System.IO.StreamReader sr = new System.IO.StreamReader(Request.Body);
  157. value = sr.ReadToEnd();
  158. value = value.Split('=')[1];
  159. }
  160. value = DesDecrypt(value);
  161. JsonData data = JsonMapper.ToObject(value);
  162. AppResultJson result = AlipayMiniOpenIdDo(value);
  163. return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
  164. }
  165. public AppResultJson AlipayMiniOpenIdDo(string value)
  166. {
  167. JsonData data = JsonMapper.ToObject(value);
  168. string code = data["code"].ToString(); //微信小程序获取的code
  169. // string nickName = data["nickName"].ToString(); //昵称
  170. // string avatarUrl = data["avatarUrl"].ToString(); //头像地址
  171. string encryptedData = data["encryptedData"].ToString(); //微信小程序获取手机号的数据包
  172. // string iv = data["iv"].ToString(); //微信小程序获取手机号的IV
  173. Dictionary<string, object> Obj = new Dictionary<string, object>();
  174. string openid = new AlipayFunction(_accessor.HttpContext).GetAlipayUserId(code);
  175. // string AlipayOpenId = UserIdString.Split('|')[0];
  176. string mobile = new AlipayFunction(_accessor.HttpContext).GetAlipayMobile(encryptedData);
  177. if (mobile.StartsWith("success|"))
  178. {
  179. mobile = mobile.Split('|')[1];
  180. }
  181. int ConsumerId = 0;
  182. Consumers check = maindb.Consumers.FirstOrDefault(m => m.AlipayUserId == openid);
  183. if (check == null)
  184. {
  185. check = maindb.Consumers.Add(new Consumers()
  186. {
  187. CreateDate = DateTime.Now,
  188. // NickName = filterEmoji(nickName),
  189. // HeadPhoto = avatarUrl,
  190. // Mobile = mobile,
  191. AlipayUserId = openid,
  192. }).Entity;
  193. maindb.SaveChanges();
  194. ConsumerId = check.Id;
  195. maindb.ConsumerOpenIds.Add(new ConsumerOpenIds()
  196. {
  197. OpenId = openid,
  198. ConsumerId = ConsumerId,
  199. });
  200. maindb.SaveChanges();
  201. }
  202. else
  203. {
  204. // check.NickName = filterEmoji(nickName);
  205. // check.HeadPhoto = avatarUrl;
  206. // check.Mobile = mobile;
  207. ConsumerId = check.Id;
  208. maindb.SaveChanges();
  209. }
  210. Obj.Add("ConsumerId", ConsumerId); //消费者Id
  211. return new AppResultJson() { Status = "1", Info = "", Data = Obj };
  212. }
  213. #endregion
  214. #region 消费者-消费者详情
  215. [Authorize]
  216. public JsonResult Detail(string value)
  217. {
  218. value = DesDecrypt(value);
  219. JsonData data = JsonMapper.ToObject(value);
  220. Dictionary<string, object> Obj = DetailDo(value);
  221. return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
  222. }
  223. public Dictionary<string, object> DetailDo(string value)
  224. {
  225. JsonData data = JsonMapper.ToObject(value);
  226. Dictionary<string, object> Obj = new Dictionary<string, object>();
  227. Consumers query = new Consumers();
  228. int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
  229. query = ConsumersDbconn.Instance.Get(Id) ?? new Consumers();
  230. Obj.Add("NickName", query.NickName); //昵称
  231. Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
  232. Obj.Add("Mobile", query.Mobile); //手机号
  233. string TotalDividend = new ConsumerProfitService().Sum("GetMoney", " and ConsumerId=" + Id)["GetMoney"];
  234. Obj.Add("TotalDividend", TotalDividend); //累计分红
  235. Obj.Add("TotalIntegral", query.TotalIntegral); //累计积分
  236. Obj.Add("CurIntgegral", query.CurIntgegral); //当前积分
  237. Obj.Add("CreateDate", query.CreateDate); //创建时间
  238. return Obj;
  239. }
  240. #endregion
  241. #region 检查签名是否合法,合法返回1,不合法返回提示信息
  242. /// <summary>
  243. /// 检查签名是否合法,合法返回1,不合法返回提示信息
  244. /// </summary>
  245. /// <param name="value">请求的参数(json字符串)</param>
  246. /// <param name="signField">要签名的字段</param>
  247. /// <returns></returns>
  248. private string CheckSign(string value, string[] signField)
  249. {
  250. JsonData json = JsonMapper.ToObject(value);
  251. Dictionary<string, string> dic = new Dictionary<string, string>();
  252. for (int i = 0; i < signField.Length; i++)
  253. {
  254. dic.Add(signField[i], json[signField[i]].ToString());
  255. }
  256. string sign = json["sign"].ToString(); //客户端签名字符串
  257. return new Sign().sign(dic, sign);
  258. }
  259. #endregion
  260. }
  261. }