private UpdateBaseInfoModel GetUpdateBaseInfo() { var model = new UpdateBaseInfoModel(); try { var baseSetting = _baseSettingService.GetLast(); if (baseSetting == null) { throw new MyException(MyException.GetMyResponse(HttpStatusCode.NotImplemented, new StringContent("baseSetting is null"), "baseSetting is null")); } if (string.IsNullOrEmpty(baseSetting.AppId) || string.IsNullOrEmpty(baseSetting.AppSecret)) { throw new MyException(MyException.GetMyResponse(HttpStatusCode.NotImplemented, new StringContent("未设置appId或appSecret"), "未设置appId或appSecret")); } else { if (!baseSetting.AccessTokenExpireTime.HasValue || baseSetting.AccessTokenExpireTime.Value < DateTime.Now) { var result = RequestUtilityHelper.HttpGet( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + baseSetting.AppId + "&secret=" + baseSetting.AppSecret, encoding: Encoding.UTF8, timeOut: 30000); var returnResult = JsonConvert.DeserializeObject <AccessTokenHttpResultModel>(result); if (returnResult.errcode != null) { throw new MyException(MyException.GetMyResponse(HttpStatusCode.NotImplemented, new StringContent(returnResult.errmsg), returnResult.errmsg)); } baseSetting.AccessToken = returnResult.access_token; baseSetting.AccessTokenExpireTime = DateTime.Now.AddHours(2).AddMinutes(-2); _baseSettingService.Update(baseSetting); } model.AppId = baseSetting.AppId; model.AppSecret = baseSetting.AppSecret; model.AccessToken = baseSetting.AccessToken; model.AccessTokenExpireTime = baseSetting.AccessTokenExpireTime == null ? "2018-01-01 00:00:00" : baseSetting.AccessTokenExpireTime.Value.ToString("yyyy-MM-dd HH:mm:ss"); model.IsSuccess = true; model.ReturnMsg = "调用成功"; } } catch (Exception ex) { model.IsSuccess = false; model.ReturnMsg = ex.Message; } return(model); }
private OpenIdModel GetOpenIdMethod(string code) { var model = new OpenIdModel(); var updateBaseInfoModel = GetUpdateBaseInfo(); if (updateBaseInfoModel.IsSuccess) { model.IsSuccess = updateBaseInfoModel.IsSuccess; model.ReturnMsg = updateBaseInfoModel.ReturnMsg; var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + updateBaseInfoModel.AppId + "&secret=" + updateBaseInfoModel.AppSecret + "&js_code=" + code + "&grant_type=authorization_code"; try { var result = RequestUtilityHelper.HttpGet(url, encoding: Encoding.UTF8, timeOut: 30000); var returnResult = System.Web.Helpers.Json.Decode <OpenIdModelResultModel>(result); if (string.IsNullOrEmpty(returnResult.errcode)) { model.OpenId = returnResult.openid; model.SessionKey = returnResult.session_key; model.UnionId = returnResult.unionid; model.IsSuccess = true; model.ReturnMsg = "调用成功"; } else { SetErrorOpenIdModel(model, "错误码:" + returnResult.errcode + ",错误信息:" + returnResult.errmsg); } } catch (Exception ex) { SetErrorOpenIdModel(model, ex.Message); } } else { SetErrorOpenIdModel(model, updateBaseInfoModel.ReturnMsg); } return(model); }