WxController.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Bowin.Common.Cache;
  2. using Bowin.Common.DES;
  3. using Bowin.Common.ServiceToken;
  4. using Bowin.Common.Utility;
  5. using Bowin.Common.WebModels;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Newtonsoft.Json;
  9. using OrderSystem.Entity.ViewModel;
  10. using OrderSystem.Services.SystemSetting;
  11. using System.Net.Http;
  12. namespace OrderSystem.Web.Controllers
  13. {
  14. [Route("api/[controller]/[action]")]
  15. [Authorize]
  16. public class WxController : ControllerBase
  17. {
  18. private readonly IHttpClientFactory _clientFactory;
  19. public WxController(IHttpClientFactory clientFactory)
  20. {
  21. _clientFactory = clientFactory;
  22. }
  23. [AllowAnonymous]
  24. [HttpGet]
  25. public ResultMessage GetOauthUrlForBase()
  26. {
  27. 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";
  28. return ResultMessage.Success(url);
  29. }
  30. [AllowAnonymous]
  31. [HttpGet]
  32. public ResultMessage GetOpenID(string code)
  33. {
  34. 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";
  35. var client = _clientFactory.CreateClient();
  36. var httpResponse = client.PostAsync(url, null).Result;
  37. if (httpResponse.IsSuccessStatusCode)
  38. {
  39. var jsonData = httpResponse.Content.ReadAsStringAsync().Result;
  40. var error = JsonConvert.DeserializeObject<WxMpError>(jsonData);
  41. if (error != null && !string.IsNullOrEmpty(error.errcode))
  42. return ResultMessage.GetError($"获取openID接口返回错误!错误代码:{error.errcode},错误信息:{error.errmsg}");
  43. var data = JsonConvert.DeserializeObject<WxMpOAuth2AccessToken>(jsonData);
  44. return ResultMessage.Success(data.openid);
  45. }
  46. else
  47. {
  48. return ResultMessage.GetError("获取openID接口请求错误!错误代码:" + httpResponse.StatusCode);
  49. }
  50. }
  51. public class WxMpOAuth2AccessToken
  52. {
  53. public string access_token { get; set; }
  54. public int expires_in { get; set; }
  55. public string refresh_token { get; set; }
  56. public string openid { get; set; }
  57. public string scope { get; set; }
  58. public string unionid { get; set; }
  59. }
  60. public class WxMpError
  61. {
  62. public string errcode { get; set; }
  63. public string errmsg { get; set; }
  64. }
  65. }
  66. }