ConsumersController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. JsonData jsonObj = JsonMapper.ToObject(result);
  52. string openid = jsonObj["openid"].ToString();
  53. string session_key = jsonObj["session_key"].ToString();
  54. string mobile = getPhoneNumber(encryptedData, iv, session_key)["Mobile"];
  55. if (mobile == "err")
  56. {
  57. Obj.Add("ConsumerId", "");
  58. return new AppResultJson() { Status = "-1", Info = "授权失败,请重试", Data = Obj };
  59. }
  60. int ConsumerId = 0;
  61. Consumers check = maindb.Consumers.FirstOrDefault(m => m.WechatOpenId == openid);
  62. if (check == null)
  63. {
  64. check = maindb.Consumers.Add(new Consumers()
  65. {
  66. CreateDate = DateTime.Now,
  67. NickName = filterEmoji(nickName),
  68. HeadPhoto = avatarUrl,
  69. Mobile = mobile,
  70. WechatOpenId = openid,
  71. }).Entity;
  72. maindb.SaveChanges();
  73. ConsumerId = check.Id;
  74. maindb.ConsumerOpenIds.Add(new ConsumerOpenIds()
  75. {
  76. OpenId = openid,
  77. ConsumerId = ConsumerId,
  78. });
  79. maindb.SaveChanges();
  80. }
  81. else
  82. {
  83. check.NickName = filterEmoji(nickName);
  84. check.HeadPhoto = avatarUrl;
  85. check.Mobile = mobile;
  86. ConsumerId = check.Id;
  87. maindb.SaveChanges();
  88. }
  89. Obj.Add("ConsumerId", ConsumerId); //消费者Id
  90. return new AppResultJson() { Status = "1", Info = "", Data = Obj };
  91. }
  92. public Dictionary<string, string> getPhoneNumber(string encryptedData, string iv, string session_key)
  93. {
  94. Dictionary<string, string> Obj = new Dictionary<string, string>();
  95. try
  96. {
  97. byte[] encryData = Convert.FromBase64String(encryptedData);
  98. RijndaelManaged rijndaelCipher = new RijndaelManaged();
  99. rijndaelCipher.Key = Convert.FromBase64String(session_key);
  100. rijndaelCipher.IV = Convert.FromBase64String(iv);
  101. rijndaelCipher.Mode = CipherMode.CBC;
  102. rijndaelCipher.Padding = PaddingMode.PKCS7;
  103. ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
  104. byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
  105. string result = Encoding.Default.GetString(plainText);
  106. dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
  107. string phoneNumber = model.phoneNumber;
  108. //return model.phoneNumber;
  109. if (string.IsNullOrEmpty(phoneNumber))
  110. {
  111. phoneNumber = "";
  112. }
  113. Obj.Add("Mobile", phoneNumber);
  114. }
  115. catch(Exception ex)
  116. {
  117. Obj.Add("Mobile", "err");
  118. function.WriteLog(DateTime.Now.ToString(), "微信小程序获取手机号异常");
  119. function.WriteLog(encryptedData, "微信小程序获取手机号异常");
  120. function.WriteLog(iv, "微信小程序获取手机号异常");
  121. function.WriteLog(session_key, "微信小程序获取手机号异常");
  122. function.WriteLog(ex.ToString(), "微信小程序获取手机号异常");
  123. function.WriteLog("\r\n\r\n", "微信小程序获取手机号异常");
  124. }
  125. return Obj;
  126. }
  127. public string filterEmoji(string str)
  128. {
  129. string origin = str;
  130. try
  131. {
  132. //关键代码
  133. foreach (var a in str)
  134. {
  135. byte[] bts = System.Text.Encoding.UTF32.GetBytes(a.ToString());
  136. if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
  137. {
  138. str = str.Replace(a.ToString(), "");
  139. }
  140. }
  141. }
  142. catch
  143. {
  144. str = origin;
  145. }
  146. return str;
  147. }
  148. #endregion
  149. #region 消费者-支付宝通过code获取openid
  150. [Authorize]
  151. public JsonResult AlipayMiniOpenId(string value)
  152. {
  153. if (string.IsNullOrEmpty(value))
  154. {
  155. System.IO.StreamReader sr = new System.IO.StreamReader(Request.Body);
  156. value = sr.ReadToEnd();
  157. value = value.Split('=')[1];
  158. }
  159. value = DesDecrypt(value);
  160. JsonData data = JsonMapper.ToObject(value);
  161. AppResultJson result = AlipayMiniOpenIdDo(value);
  162. return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
  163. }
  164. public AppResultJson AlipayMiniOpenIdDo(string value)
  165. {
  166. JsonData data = JsonMapper.ToObject(value);
  167. string code = data["code"].ToString(); //微信小程序获取的code
  168. // string nickName = data["nickName"].ToString(); //昵称
  169. // string avatarUrl = data["avatarUrl"].ToString(); //头像地址
  170. string encryptedData = data["encryptedData"].ToString(); //微信小程序获取手机号的数据包
  171. // string iv = data["iv"].ToString(); //微信小程序获取手机号的IV
  172. Dictionary<string, object> Obj = new Dictionary<string, object>();
  173. string UserIdString = new AlipayFunction(_accessor.HttpContext).GetAlipayUserId(code);
  174. string AlipayUserId = UserIdString.Split('|')[0];
  175. string mobile = new AlipayFunction(_accessor.HttpContext).GetAlipayMobile(encryptedData);
  176. if (mobile.StartsWith("success|"))
  177. {
  178. mobile = mobile.Split('|')[1];
  179. }
  180. int ConsumerId = 0;
  181. ConsumerOpenIds check = ConsumerOpenIdsDbconn.Instance.Get(AlipayUserId);
  182. if (check == null)
  183. {
  184. // ConsumerId = PublicFunction.MakeConsumerId();
  185. Consumers consumer = new Consumers()
  186. {
  187. Id = ConsumerId,
  188. CreateDate = DateTime.Now,
  189. NickName = "码牌用户" + function.get_Random(6),
  190. // HeadPhoto = avatarUrl,
  191. Mobile = mobile,
  192. AlipayUserId = AlipayUserId,
  193. };
  194. check = new ConsumerOpenIds()
  195. {
  196. OpenId = AlipayUserId,
  197. ConsumerId = ConsumerId,
  198. };
  199. }
  200. else
  201. {
  202. Consumers consumer = ConsumersDbconn.Instance.Get(check.ConsumerId);
  203. // consumer.NickName = filterEmoji(nickName);
  204. // consumer.HeadPhoto = avatarUrl;
  205. consumer.Mobile = mobile;
  206. ConsumerId = check.ConsumerId;
  207. }
  208. Obj.Add("ConsumerId", ConsumerId); //消费者Id
  209. return new AppResultJson() { Status = "1", Info = "", Data = Obj };
  210. }
  211. #endregion
  212. #region 消费者-消费者详情
  213. [Authorize]
  214. public JsonResult Detail(string value)
  215. {
  216. value = DesDecrypt(value);
  217. JsonData data = JsonMapper.ToObject(value);
  218. Dictionary<string, object> Obj = DetailDo(value);
  219. return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
  220. }
  221. public Dictionary<string, object> DetailDo(string value)
  222. {
  223. JsonData data = JsonMapper.ToObject(value);
  224. Dictionary<string, object> Obj = new Dictionary<string, object>();
  225. Consumers query = new Consumers();
  226. int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
  227. query = ConsumersDbconn.Instance.Get(Id) ?? new Consumers();
  228. Obj.Add("NickName", query.NickName); //昵称
  229. Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
  230. Obj.Add("Mobile", query.Mobile); //手机号
  231. string TotalDividend = new ConsumerProfitService().Sum("GetMoney", " and ConsumerId=" + Id)["GetMoney"];
  232. Obj.Add("TotalDividend", TotalDividend); //累计分红
  233. Obj.Add("TotalIntegral", query.TotalIntegral); //累计积分
  234. Obj.Add("CurIntgegral", query.CurIntgegral); //当前积分
  235. Obj.Add("CreateDate", query.CreateDate); //创建时间
  236. return Obj;
  237. }
  238. #endregion
  239. #region 检查签名是否合法,合法返回1,不合法返回提示信息
  240. /// <summary>
  241. /// 检查签名是否合法,合法返回1,不合法返回提示信息
  242. /// </summary>
  243. /// <param name="value">请求的参数(json字符串)</param>
  244. /// <param name="signField">要签名的字段</param>
  245. /// <returns></returns>
  246. private string CheckSign(string value, string[] signField)
  247. {
  248. JsonData json = JsonMapper.ToObject(value);
  249. Dictionary<string, string> dic = new Dictionary<string, string>();
  250. for (int i = 0; i < signField.Length; i++)
  251. {
  252. dic.Add(signField[i], json[signField[i]].ToString());
  253. }
  254. string sign = json["sign"].ToString(); //客户端签名字符串
  255. return new Sign().sign(dic, sign);
  256. }
  257. #endregion
  258. }
  259. }