WechatHelper.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11. using Microsoft.AspNetCore.Http;
  12. using Common;
  13. using ZcPeng.weixin.PublicAccount;
  14. using Newtonsoft.Json;
  15. using JCSoft.WX.Framework.Models.ApiRequests;
  16. using JCSoft.WX.Framework.Models;
  17. using Microsoft.AspNetCore.Authentication.Cookies;
  18. using System.Security.Claims;
  19. using JCSoft.WX.Framework.Api;
  20. using Microsoft.AspNetCore.Authentication;
  21. using JCSoft.WX.Framework.Models.ApiResponses;
  22. namespace Common.Wechat
  23. {
  24. public class WechatHelper
  25. {
  26. /// <summary>
  27. /// 验证微信签名
  28. /// </summary>
  29. public static bool CheckSignature(string token, string signature, string timestamp, string nonce)
  30. {
  31. string[] ArrTmp = { token, timestamp, nonce };
  32. Array.Sort(ArrTmp);
  33. string tmpStr = string.Join("", ArrTmp);
  34. //tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
  35. //tmpStr = Membership.CreateUser(tmpStr, "SHA1");
  36. tmpStr = tmpStr.ToLower();
  37. if (tmpStr == signature)
  38. {
  39. return true;
  40. }
  41. else
  42. {
  43. return false;
  44. }
  45. }
  46. public static void ReGetOpenId(HttpContext reqContext,string param = "")
  47. {
  48. string Appid = Config.WeChatAppKey;
  49. string Secret = Config.WeChatAppSecret;
  50. string url = GetAbsoluteUri(reqContext.Request);//获取当前url
  51. Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
  52. if (reqContext.Session.GetString("openid") == "" || reqContext.Session.GetString("openid") == null)
  53. {
  54. //先要判断是否是获取code后跳转过来的
  55. if (reqContext.Request.Query["code"].FirstOrDefault()== ""
  56. || reqContext.Request.Query["code"].FirstOrDefault() == null)
  57. {
  58. //Code为空时,先获取Code
  59. string GetCodeUrls = GetCodeUrl(url,Appid, "");
  60. log.log("获取openid 前 GetCodeUrls:" + GetCodeUrls);
  61. reqContext.Response.Redirect(GetCodeUrls);//先跳转到微信的服务器,取得code后会跳回来这页面的
  62. }
  63. else
  64. {
  65. //Code非空,已经获取了code后跳回来啦,现在重新获取openid
  66. string openid = "";
  67. openid = GetOauthAccessOpenId(reqContext.Request.Query["Code"].FirstOrDefault(),Appid, Secret);//重新取得用户的openid
  68. reqContext.Session.SetString("openid",openid);
  69. log.log("走完获取openid的方法之后,当前Session的值是:" + reqContext.Session.GetString("openid"));
  70. }
  71. }
  72. }
  73. #region 重新获取Code的跳转链接(没有用户授权的,只能获取基本信息)
  74. /// <summary>重新获取Code,以后面实现带着Code重新跳回目标页面(没有用户授权的,只能获取基本信息(openid))</summary>
  75. /// <param name="url">目标页面</param>
  76. /// <returns></returns>
  77. public static string GetCodeUrl(string url,string Appid,string param="")
  78. {
  79. Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
  80. string CodeUrl = "";
  81. //对url进行编码
  82. url = System.Web.HttpUtility.UrlEncode(url+ param);
  83. CodeUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Appid + "&redirect_uri=" + url
  84. + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect");//?action=viewtest
  85. log.log("拿到code的url是:" + CodeUrl);
  86. return CodeUrl;
  87. }
  88. #endregion
  89. #region 以Code换取用户的openid、access_token
  90. /// <summary>根据Code获取用户的openid、access_token</summary>
  91. public static string GetOauthAccessOpenId(string code,string Appid,string Secret)
  92. {
  93. Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
  94. string Openid = "";
  95. string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Appid + "&secret=" + Secret + "&code=" + code + "&grant_type=authorization_code";
  96. string result = HttpHelper.HttpGet(url, "application/json");
  97. log.log("拿到的url是:" + url);
  98. log.log("获取到的result是" + result);
  99. var jsonData = JsonConvert.DeserializeAnonymousType(result, new { access_token = "", openid = "", errcode = 0 });
  100. if (jsonData.errcode != 0)
  101. {
  102. return "";
  103. }
  104. log.log("能否从html里拿到openid=" + jsonData.openid);
  105. Openid = jsonData.openid;
  106. return Openid;
  107. }
  108. #endregion
  109. public static string GetAbsoluteUri(HttpRequest request)
  110. {
  111. //TODO:delete test code
  112. return new StringBuilder()
  113. //.Append(request.Scheme)
  114. .Append("https")
  115. .Append("://")
  116. //.Append(request.Host)
  117. //.Append("119.27.191.247")
  118. .Append(Config.Host)
  119. .Append(request.PathBase)
  120. .Append(request.Path)
  121. .Append(request.QueryString)
  122. .ToString();
  123. }
  124. /// <summary>
  125. /// 这个方法不用了
  126. /// </summary>
  127. /// <param name="_client"></param>
  128. /// <returns></returns>
  129. public static AccountInfo getAccessToken(IApiClient _client )
  130. {
  131. var info = AccountInfoCollection.GetAccountInfo(Config.WeChatAppName);
  132. if (info == null || info.Token == null || info.Token == "") {
  133. var request = new AccessTokenRequest(new AppIdentication(Config.WeChatAppKey, Config.WeChatAppSecret));
  134. var response = _client.Execute(request);
  135. bool IsSuccess = !response.IsError;
  136. if (!response.IsError)
  137. {
  138. //加入测试公众号
  139. AccountInfo account = new AccountInfo(Config.WeChatAppName, Config.WeChatAppKey, Config.WeChatAppSecret, response.Access_Token, null,response.Expires_In);
  140. AccountInfoCollection.SetAccountInfo(account);
  141. //加入正式公众号
  142. //AccountInfoCollection.SetAccountInfo(new AccountInfo("YourId2", "AppId", "AppSecret", "Token", "EncodingAesKey", "非測試"));
  143. return account;
  144. }
  145. else
  146. {
  147. return null;
  148. }
  149. }
  150. return info;
  151. }
  152. }
  153. }