/// <summary> /// 生成签名 /// </summary> /// <param name="appId"></param> /// <param name="secretKey"></param> /// <param name="noncestr"></param> /// <param name="timestamp">时间戳</param> /// <param name="pageUrl">h5页面地址</param> /// <param name="account">微信账户配置</param> /// <returns></returns> private static ContractResult <string> GetJsApiTicket(string appId, string secretKey, string noncestr, long timestamp, string pageUrl) { ContractResult <string> result = new ContractResult <string>(); var ticketResult = GetJsApiTicket(appId, secretKey); if (ticketResult.ErrorCode != "0") { result.SetError(ticketResult.ErrorCode, ticketResult.ErrorMessage); return(result); } var dictParam = new SortedDictionary <string, string> { { "url", pageUrl }, { "noncestr", noncestr }, { "timestamp", $"{timestamp}" }, { "jsapi_ticket", ticketResult.Data } }; var source = ""; foreach (var pair in dictParam) { source += pair.Key + "=" + pair.Value + "&"; } source = source.TrimEnd('&'); result.Data = source.Encode(); return(result); }
/// <summary> /// 在Action执行之前调用 /// </summary> /// <param name="context"></param> /// <returns></returns> public void OnActionExecuting(ActionExecutingContext context) { var query = context.HttpContext.Request.Query; string nonce = query["nonce"]; //随机数 string timestamp = query["timestamp"]; //时间戳 string signature = query["signature"]; //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数 string openId = query.ContainsKey("openid") ? $"{query["openid"]}" : ""; //用户的标识,对当前公众号唯一 string echostr = query.ContainsKey("echostr") ? $"{query["echostr"]}" : ""; //随机字符串 WeChatAccount account = ((BaseController)context.Controller).Account; //微信账户信息配置 if (!SignatureVerifyUtil.CheckSignature(signature, timestamp, nonce, account.Token)) { ContractResult result = new ContractResult(); result.SetError(ErrorCodeType.CheckSignFail); context.Result = new JsonResult(result); _log.Debug($"【微信签名校验】请求参数=》signature:{signature},timestamp:{timestamp},nonce:{nonce},echostr:{echostr},appid:{account.AppId},openid:{openId}"); return; } if (context.HttpContext.Request.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(echostr)) { ContentResult result = new ContentResult() { Content = echostr }; context.Result = result; return; } }
/// <summary> /// 在Action执行之前调用 /// </summary> /// <param name="context"></param> /// <returns></returns> public void OnActionExecuting(ActionExecutingContext context) { ContractResult result = new ContractResult(); var baseController = ((BaseOAuthController)context.Controller); if (baseController.UserTicket != null) { baseController.UserTicket = AccessTokenUtil.RefreshToken(baseController.Account.AppId, baseController.UserTicket); return; } string codeKey = context.HttpContext.Request.Query.Keys.FirstOrDefault(key => key.ToLower() == "code"); if (!string.IsNullOrEmpty(codeKey)) { string secretKey = baseController.Account.SecretKey; string code = context.HttpContext.Request.Query[codeKey]; baseController.UserTicket = AccessTokenUtil.GetOAuthToken(baseController.Account.AppId, code, baseController.Account.SecretKey); } else { string authorizeUrl = WeChatSettingsUtil.Settings.AuthorizeUrl; string urlKey = context.HttpContext.Request.Query.Keys.FirstOrDefault(key => key.ToLower() == "url"); if (string.IsNullOrEmpty(urlKey)) { result.SetError(ErrorCodeType.InvalidUrl); context.Result = new JsonResult(result); return; } string redirect_uri = context.HttpContext.Request.Query[urlKey]; string location = $"{authorizeUrl}?appid={baseController.Account.AppId}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; context.Result = new RedirectResult(location);//302重定向跳转 } }
/// <summary> /// 发生异常时调用 /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { Exception ex = context.Exception; context.ExceptionHandled = true; var result = new ContractResult(); result.SetError(ErrorCodeType.Exception); context.Result = new JsonResult(result); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; _log.Error($"【全局异常】发生未经处理的全局异常:{ex}"); }
/// <summary> /// 获取jsapi_ticket /// </summary> /// <param name="account">微信账户配置</param> /// <returns></returns> private static ContractResult <string> GetJsApiTicket(string appId, string secretKey) { ContractResult <string> result = new ContractResult <string>(); var tokenResult = AccessTokenUtil.GetAccessToken(appId, secretKey); if (tokenResult.ErrorCode != "0") { result.SetError(tokenResult.ErrorCode, tokenResult.ErrorMessage); return(result); } var apiUrl = $"{WeChatSettingsUtil.Settings.JSAPITicketApiUrl}&access_token={tokenResult.Data}"; JsApiTicketMpResult response = HttpClientUtil.GetResponse <JsApiTicketMpResult>(apiUrl); if (response.ErrorCode != 0) { result.SetError($"{response.ErrorCode}", response.ErrorMessage); return(result); } result.Data = response.Ticket; return(result); }
/// <summary> /// 在Action执行之前调用 /// </summary> /// <param name="context"></param> /// <returns></returns> public void OnActionExecuting(ActionExecutingContext context) { ContractResult result = new ContractResult(); IQueryCollection query = context.HttpContext.Request.Query; string appIdKey = query.Keys.FirstOrDefault(key => key.ToLower() == "appid"); string openIdKey = query.Keys.FirstOrDefault(key => key.ToLower() == "openid"); if (string.IsNullOrWhiteSpace(appIdKey)) { result.SetError(ErrorCodeType.NoAppId); context.Result = new JsonResult(result); _log.Debug($"【全局配置过滤器】请求参数:{JsonConvert.SerializeObject(query)}"); return; } if (string.IsNullOrWhiteSpace(openIdKey)) { result.SetError(ErrorCodeType.NoOpenId); context.Result = new JsonResult(result); _log.Debug($"【全局配置过滤器】请求参数:{JsonConvert.SerializeObject(query)}"); return; } var baseController = ((BaseController)context.Controller); baseController.AppId = query[appIdKey]; //公众号Id baseController.OpenId = query[openIdKey]; //用户的标识,对当前公众号唯一 baseController.Account = WeChatSettingsUtil.GetAccountConfig(baseController.AppId); if (baseController.Account == null) { result.SetError(ErrorCodeType.ConfigErr); context.Result = new JsonResult(result); _log.Debug($"【全局配置过滤器】请求参数:{JsonConvert.SerializeObject(query)}"); return; } }
/// <summary> /// 获取签名 /// </summary> /// <param name="appId"></param> /// <param name="secretKey"></param> /// <param name="pageUrl">h5页面地址</param> /// <returns></returns> public static ContractResult <WeChatSignatureResult> GetJsApiTicket(string appId, string secretKey, string pageUrl) { long timestamp = DateTime.Now.ToUnixTimeForSeconds(); string noncestr = random.GenString(32, true, false, true, false, ""); ContractResult <WeChatSignatureResult> result = new ContractResult <WeChatSignatureResult>(); var signatureResult = GetJsApiTicket(appId, secretKey, noncestr, timestamp, pageUrl); if (signatureResult.ErrorCode != "0") { result.SetError(signatureResult.ErrorCode, signatureResult.ErrorMessage); return(result); } result.Data = new WeChatSignatureResult() { NonceStr = noncestr, Timestamp = timestamp, AppId = appId, Signature = signatureResult.Data }; return(result); }
/// <summary> /// 获取普通授权Token信息 /// </summary> /// <param name="appId"></param> /// <param name="appSecret">开发者密码</param> /// <returns></returns> public static ContractResult <string> GetAccessToken(string appId, string secretKey) { ContractResult <string> result = new ContractResult <string>(); var dictParam = new Dictionary <string, string> { { "secret", secretKey }, { "appid", $"{appId}" }, { "grant_type", "client_credential" } }; string accessTokenUrl = WeChatSettingsUtil.Settings.AccessTokenUrl; AccessTokenMpResult response = HttpClientUtil.GetResponse <AccessTokenMpResult>(accessTokenUrl, dictParam); if (response.ErrorCode != "0") { result.SetError(response.ErrorCode, response.ErrorMessage); return(result); } result.Data = response.Access_Token; return(result); }