12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using Bowin.Common.Cache;
- using Bowin.Common.DES;
- using Bowin.Common.ServiceToken;
- using Bowin.Common.Utility;
- using Bowin.Common.WebModels;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Newtonsoft.Json;
- using OrderSystem.Entity.ViewModel;
- using OrderSystem.Services.SystemSetting;
- using System.Net.Http;
- namespace OrderSystem.Web.Controllers
- {
- [Route("api/[controller]/[action]")]
- [Authorize]
- public class WxController : ControllerBase
- {
- private readonly IHttpClientFactory _clientFactory;
- public WxController(IHttpClientFactory clientFactory)
- {
- _clientFactory = clientFactory;
- }
- [AllowAnonymous]
- [HttpGet]
- public ResultMessage GetOauthUrlForBase()
- {
- string url = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={ Configuration.Current.WxConfig.AppId}&redirect_uri={Configuration.Current.WxConfig.RedirectURI}/{Configuration.Current.AppSettings.H5Version}/index.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
- return ResultMessage.Success(url);
- }
- [AllowAnonymous]
- [HttpGet]
- public ResultMessage GetOpenID(string code)
- {
- string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={ Configuration.Current.WxConfig.AppId}&secret={Configuration.Current.WxConfig.AppSecret}&code={code}&grant_type=authorization_code";
- var client = _clientFactory.CreateClient();
- var httpResponse = client.PostAsync(url, null).Result;
- if (httpResponse.IsSuccessStatusCode)
- {
- var jsonData = httpResponse.Content.ReadAsStringAsync().Result;
- var error = JsonConvert.DeserializeObject<WxMpError>(jsonData);
- if (error != null && !string.IsNullOrEmpty(error.errcode))
- return ResultMessage.GetError($"获取openID接口返回错误!错误代码:{error.errcode},错误信息:{error.errmsg}");
- var data = JsonConvert.DeserializeObject<WxMpOAuth2AccessToken>(jsonData);
- return ResultMessage.Success(data.openid);
- }
- else
- {
- return ResultMessage.GetError("获取openID接口请求错误!错误代码:" + httpResponse.StatusCode);
- }
-
- }
- public class WxMpOAuth2AccessToken
- {
- public string access_token { get; set; }
- public int expires_in { get; set; }
- public string refresh_token { get; set; }
- public string openid { get; set; }
- public string scope { get; set; }
- public string unionid { get; set; }
- }
- public class WxMpError
- {
- public string errcode { get; set; }
- public string errmsg { get; set; }
- }
- }
- }
|