using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using Microsoft.AspNetCore.Http; using Common; using ZcPeng.weixin.PublicAccount; using Newtonsoft.Json; using JCSoft.WX.Framework.Models.ApiRequests; using JCSoft.WX.Framework.Models; using Microsoft.AspNetCore.Authentication.Cookies; using System.Security.Claims; using JCSoft.WX.Framework.Api; using Microsoft.AspNetCore.Authentication; using JCSoft.WX.Framework.Models.ApiResponses; namespace Common.Wechat { public class WechatHelper { /// /// 验证微信签名 /// public static bool CheckSignature(string token, string signature, string timestamp, string nonce) { string[] ArrTmp = { token, timestamp, nonce }; Array.Sort(ArrTmp); string tmpStr = string.Join("", ArrTmp); //tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); //tmpStr = Membership.CreateUser(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { return true; } else { return false; } } public static void ReGetOpenId(HttpContext reqContext,string param = "") { string Appid = Config.WeChatAppKey; string Secret = Config.WeChatAppSecret; string url = GetAbsoluteUri(reqContext.Request);//获取当前url Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); if (reqContext.Session.GetString("openid") == "" || reqContext.Session.GetString("openid") == null) { //先要判断是否是获取code后跳转过来的 if (reqContext.Request.Query["code"].FirstOrDefault()== "" || reqContext.Request.Query["code"].FirstOrDefault() == null) { //Code为空时,先获取Code string GetCodeUrls = GetCodeUrl(url,Appid, ""); log.log("获取openid 前 GetCodeUrls:" + GetCodeUrls); reqContext.Response.Redirect(GetCodeUrls);//先跳转到微信的服务器,取得code后会跳回来这页面的 } else { //Code非空,已经获取了code后跳回来啦,现在重新获取openid string openid = ""; openid = GetOauthAccessOpenId(reqContext.Request.Query["Code"].FirstOrDefault(),Appid, Secret);//重新取得用户的openid reqContext.Session.SetString("openid",openid); log.log("走完获取openid的方法之后,当前Session的值是:" + reqContext.Session.GetString("openid")); } } } #region 重新获取Code的跳转链接(没有用户授权的,只能获取基本信息) /// 重新获取Code,以后面实现带着Code重新跳回目标页面(没有用户授权的,只能获取基本信息(openid)) /// 目标页面 /// public static string GetCodeUrl(string url,string Appid,string param="") { Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); string CodeUrl = ""; //对url进行编码 url = System.Web.HttpUtility.UrlEncode(url+ param); CodeUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Appid + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect");//?action=viewtest log.log("拿到code的url是:" + CodeUrl); return CodeUrl; } #endregion #region 以Code换取用户的openid、access_token /// 根据Code获取用户的openid、access_token public static string GetOauthAccessOpenId(string code,string Appid,string Secret) { Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); string Openid = ""; string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Appid + "&secret=" + Secret + "&code=" + code + "&grant_type=authorization_code"; string result = HttpHelper.HttpGet(url, "application/json"); log.log("拿到的url是:" + url); log.log("获取到的result是" + result); var jsonData = JsonConvert.DeserializeAnonymousType(result, new { access_token = "", openid = "", errcode = 0 }); if (jsonData.errcode != 0) { return ""; } log.log("能否从html里拿到openid=" + jsonData.openid); Openid = jsonData.openid; return Openid; } #endregion public static string GetAbsoluteUri(HttpRequest request) { //TODO:delete test code return new StringBuilder() //.Append(request.Scheme) .Append("https") .Append("://") //.Append(request.Host) //.Append("119.27.191.247") .Append(Config.Host) .Append(request.PathBase) .Append(request.Path) .Append(request.QueryString) .ToString(); } /// /// 这个方法不用了 /// /// /// public static AccountInfo getAccessToken(IApiClient _client ) { var info = AccountInfoCollection.GetAccountInfo(Config.WeChatAppName); if (info == null || info.Token == null || info.Token == "") { var request = new AccessTokenRequest(new AppIdentication(Config.WeChatAppKey, Config.WeChatAppSecret)); var response = _client.Execute(request); bool IsSuccess = !response.IsError; if (!response.IsError) { //加入测试公众号 AccountInfo account = new AccountInfo(Config.WeChatAppName, Config.WeChatAppKey, Config.WeChatAppSecret, response.Access_Token, null,response.Expires_In); AccountInfoCollection.SetAccountInfo(account); //加入正式公众号 //AccountInfoCollection.SetAccountInfo(new AccountInfo("YourId2", "AppId", "AppSecret", "Token", "EncodingAesKey", "非測試")); return account; } else { return null; } } return info; } } }