RG3.BS.Dev 6.0.3以上版本
/// <summary>
/// 获取微信相关的用户信息
/// </summary>
/// <param name="ownerId"></param>
/// <param name="sysId"></param>
/// <param name="code"></param>
/// <param name="state"></param>
/// <param name="redirectUrl"></param>
/// <returns></returns>
public async Task<ResultDetail<string>> LoginGetUserByWeChatAsync(string ownerId, string sysId, string code, string state, string redirectUrl = "")
{
//wechat: 来至公众号 wechatpc 来至pc端扫码
string _fromSource = RequestPFUtil.GetUrlOrFormParamValueByName("_fromSource", this._accessor.HttpContext) ?? "unknown";
string dayF = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
_configDev = _configurationBuilderService.GetConfigurationDevProvider(ownerId, sysId, null, _accessor, "tencent");
bool wechatLog = _configDev.GetValue<bool>($"providers:logs:wechat");
ResultDetail<string> result = new ResultDetail<string> { Success = false, Data = null, Error = ErrorCodeConst.TOKEN_22007 };
string guid = Guid.NewGuid().ToString();
string _userInfoUrl = string.Empty;
string _accessTokenUrl = string.Empty;
if (string.IsNullOrEmpty(code))
{
//用户拒绝了授权
result.Success = false;
result.Error.ErrorCode = 222222;
result.Error.ErrorText = "拒绝了授权,无法获取认证信息";
_capBus.Publish("login.services.wechat.error", new
{
step = 1,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
error = result.Error
});
//FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/token/{guid}.json"), JsonUtil.Serialize(new
//{
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// error = result.Error
//}, true));
}
else
{
try
{
//获取token信息
string _token = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:{ownerId}{sysId}:token");
if (string.IsNullOrEmpty(_token))
{
_token = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:{ownerId}:token");
}
string _encodingAESKey = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:{ownerId}{sysId}:appSecret");
if (string.IsNullOrEmpty(_encodingAESKey))
{
_encodingAESKey = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:{ownerId}:appSecret");
}
string _appId = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:{ownerId}{sysId}:appId");
if (string.IsNullOrEmpty(_appId))
{
_appId = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:{ownerId}:appId");
}
string _root = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:url:root");
string _accessToken = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:url:accessToken");
_accessTokenUrl = _accessToken.Replace("{appid}", _appId).Replace("{secret}", _encodingAESKey).Replace("{code}", code).Replace("{root}", _root).Replace("{state}", state);
HttpClient httpClient = _httpClientFactory.CreateClient(HttpClientEnum.TencentWebCat.ToString());
string tokenResult = Encoding.UTF8.GetString(httpClient.GetByteArrayAsync(_accessTokenUrl).Result);
//{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: KKnd6fMre-upqxiA ]"}
Dictionary<string, JsonElement> jobjectToken = JsonUtilText.Deserialize<Dictionary<string, JsonElement>>(tokenResult);
if (jobjectToken.ContainsKey("errcode") && jobjectToken["errcode"].ToString() != "0")
{
//用户拒绝了授权
result.Success = false;
result.Error.ErrorText = jobjectToken["errmsg"].ToString();
//FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/errcode/{guid}.json"), JsonUtil.Serialize(new
//{
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// error = result.Error
//}, true));
_capBus.Publish("login.services.wechat.error", new
{
step = 2,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
error = result.Error
});
return await Task.FromResult<ResultDetail<string>>(result);
}
dynamic tokenData = null;
UserBo userBO = null;
if (_fromSource == "wechatmini")
{
string _openId = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:url:openId");
string _openIdUrl = _openId.Replace("{appid}", _appId).Replace("{secret}", _encodingAESKey).Replace("{code}", code).Replace("{root}", _root).Replace("{state}", state);
HttpClient httpClientOpenId = _httpClientFactory.CreateClient(HttpClientEnum.TencentWebCat.ToString());
string tokenOpenIdResult = Encoding.UTF8.GetString(httpClientOpenId.GetByteArrayAsync(_openIdUrl).Result);
Dictionary<string, JsonElement> jobjectTokenObject = JsonUtilText.Deserialize<Dictionary<string, JsonElement>>(tokenOpenIdResult);
if (jobjectTokenObject.ContainsKey("errcode") && jobjectTokenObject["errcode"].ToString() != "0")
{
//用户拒绝了授权
result.Success = false;
result.Error.ErrorText = jobjectTokenObject["errmsg"].ToString();
//FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/errcode/{guid}.json"), JsonUtil.Serialize(new
//{
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// error = result.Error
//}, true));
_capBus.Publish("login.services.wechat.error", new
{
step = 3,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
error = result.Error
});
return await Task.FromResult<ResultDetail<string>>(result);
}
//会话密钥 session_key 是对用户数据进行 加密签名 的密钥。
//为了应用自身的数据安全,开发者服务器不应该把会话密钥下发到小程序,也不应该对外提供这个密钥。
//临时登录凭证 code 只能使用一次
tokenData = new
{
AccessToken = jobjectToken["access_token"].GetString(),
//ExpiresIn = jobjectToken["expires_in"].GetInt32(),
//RefreshToken = jobjectToken["refresh_token"].GetString(),
OpenId = jobjectTokenObject["openid"].GetString(),
//Scope = jobjectTokenObject["session_key"].GetString(),
UnionId = jobjectTokenObject.ContainsKey("unionid") ? jobjectTokenObject["unionid"].GetString() : null
};
userBO = new UserBo
{
//NikeName = jobjectU["nickname"].GetString(),
//Gender = jobjectU["sex"].GetInt32().ToString(),
//WxOpenId = tokenData.OpenId,
WxAppOpenId = tokenData.OpenId,
WxUnionId = tokenData.UnionId,
OpenId = tokenData.UnionId ?? tokenData.OpenId//用于前端登录
//HeadIcon = jobjectU["headimgurl"].GetString(),
//Province = jobjectU["province"].GetString(),
//City = jobjectU["city"].GetString(),
//Country = jobjectU["country"].GetString()
};
// 获取用户信息
//wx.getSetting({
// success: res => {
// if (res.authSetting['scope.userInfo']) {
// // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
// wx.getUserInfo({
// success: res => {
// // 可以将 res 发送给后台解码出 unionId
// this.globalData.userInfo = res.userInfo
// // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// // 所以此处加入 callback 以防止这种情况
// if (this.userInfoReadyCallback) {
// this.userInfoReadyCallback(res)
// }
// }
// })
// }
// }
}
else
{
tokenData = new
{
step = 4,
AccessToken = jobjectToken["access_token"].GetString(),
ExpiresIn = jobjectToken["expires_in"].GetInt32(),
RefreshToken = jobjectToken["refresh_token"].GetString(),
OpenId = jobjectToken["openid"].GetString(),
Scope = jobjectToken["scope"].GetString(),
UnionId = jobjectToken.ContainsKey("unionid") ? jobjectToken["unionid"].GetString() : null
};
//获取用户需要的信息
string _userInfo = _configDev.GetValue<string>($"dev:tencent:{_fromSource}:url:userInfo").Replace("{root}", _root); ;
_userInfoUrl = _userInfo.Replace("{access_token}", tokenData.AccessToken).Replace("{openid}", tokenData.UnionId ?? tokenData.OpenId).Replace("{state}", state);
HttpClient httpClientU = _httpClientFactory.CreateClient(HttpClientEnum.Tencent.ToString());
Dictionary<string, JsonElement> jobjectU = JsonUtilText.Deserialize<Dictionary<string, JsonElement>>(Encoding.UTF8.GetString(httpClientU.GetByteArrayAsync(_userInfoUrl).Result));
if (jobjectU.ContainsKey("errcode") && jobjectU["errcode"].ToString() != "0")
{
//用户拒绝了授权
result.Success = false;
result.Error.ErrorText = jobjectU["errmsg"].ToString();
//FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/errcode/{guid}.json"), JsonUtil.Serialize(new
//{
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// error = result.Error
//}, true));
_capBus.Publish("login.services.wechat.error", new
{
step = 5,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
error = result.Error
});
return await Task.FromResult<ResultDetail<string>>(result);
}
//if (wechatLog)
//{
// FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/user/{guid}.json"), JsonUtil.Serialize(new
// {
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// tokenUser = jobjectU
// }, true));
//}
_capBus.Publish("login.services.wechat.success", new
{
step = 1,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
tokenUser = jobjectU
});
string headIcon = null;
if (jobjectU.ContainsKey("headimgurl") && !string.IsNullOrEmpty(jobjectU["headimgurl"].ToString()))
{
headIcon = jobjectU["headimgurl"].ToString();
}
if (jobjectU.ContainsKey("avatarUrl") && !string.IsNullOrEmpty(jobjectU["avatarUrl"].ToString()))
{
headIcon = jobjectU["avatarUrl"].ToString();
}
userBO = new UserBo
{
NikeName = jobjectU["nickname"].GetString(),
Gender = jobjectU["sex"].GetInt32().ToString(),
WxOpenId = tokenData.OpenId,
WxUnionId = tokenData.UnionId,
OpenId = tokenData.UnionId ?? tokenData.OpenId,//用于前端登录
HeadIcon = headIcon,
Province = jobjectU["province"].GetString(),
City = jobjectU["city"].GetString(),
Country = jobjectU["country"].GetString()
};
}
//if (wechatLog)
//{
// FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/token/{guid}.json"), JsonUtil.Serialize(new
// {
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// tokenData = tokenData
// }, true));
//}
_capBus.Publish("login.services.wechat.success", new
{
step = 2,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
tokenData = tokenData
});
//通过openId获取用信息
if (!string.IsNullOrEmpty(userBO.Gender))
{
userBO.Gender = userBO.Gender == "1" ? "1" : "0";
}
//if (wechatLog)
//{
// FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/user/{guid}.json"), JsonUtil.Serialize(new
// {
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// userBO = userBO
// }, true));
//}
string outToken = _desRepository.EncryptDefault(ownerId, sysId, JsonUtilText.Serialize(userBO, true, true, false));
_capBus.Publish("login.services.wechat.success", new
{
step = 3,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
tokenData = tokenData,
outToken = outToken
});
result.Data = outToken;
result.Success = true;
result.Error = null;
}
catch (Exception ex)
{
//用户拒绝了授权
result.Success = false;
result.Error.ErrorText = ex.Message;
//FileUtil.CreateFileAndContent(PhyPathUtil.ConvertVirToPhyPath($"~/App_Logs/{_fromSource}/{dayF}/error/{guid}.json"), JsonUtil.Serialize(new
//{
// ownerId = ownerId,
// sysId = sysId,
// code = code,
// state = state,
// redirectUrl = redirectUrl,
// userInfoUrl = _userInfoUrl,
// accessTokenUrl = _accessTokenUrl,
// error = result.Error,
// exception = ex
//}, true));
_capBus.Publish("login.services.wechat.error", new
{
step = 6,
ownerId = ownerId,
sysId = sysId,
code = code,
state = state,
redirectUrl = redirectUrl,
userInfoUrl = _userInfoUrl,
accessTokenUrl = _accessTokenUrl,
error = result.Error,
exception = ex
});
}
}
return await Task.FromResult<ResultDetail<string>>(result);
}
文档更新时间: 2022-04-12 15:52 作者:admin