.net mvc (二)微信开放平台获取授权地址
程序员文章站
2022-03-26 10:41:10
...
微信开放平台获取授权地址,下面例子是扫码授权:
/// <summary>
/// 获取开放平台授权地址
/// </summary>
public ActionResult Index()
{
string authUrl = string.Empty;
int adminsId = StringHelper.ToInt(CurrentUser.AdminsId);
if (adminsId <= 0)
{
Addlog("获取开放平台授权地址", "微信公众平台授权页面Index:登录用户为0,AdminsId:" + adminsId);
return Redirect("/admins/login");
}
try
{
int result = GetAuthUrl(adminsId, out authUrl);
if (result == -2)
{
return Redirect("/admins/login");
}
}
catch (Exception ex)
{
Addlog("获取开放平台授权地址", "微信公众平台授权页面异常Index,异常信息:" + ex.ToString());
#region 重试授权
if (ex.ToString().Contains("42001") || ex.ToString().Contains("40014")) //access_token超时 不合法的access_token
{
try
{
_wechatPlatFormService.UpdateInvalidComponentAccessToken();//重新刷新第三方平台accessToken
_wechatPlatFormService.UpdateInvalidPreAuthCode();//重新刷新预授权码
int result = GetAuthUrl(adminsId, out authUrl);
if (result == -2)
{
return Redirect("/users/login");
}
}
catch (Exception ex01)
{
Addlog("获取开放平台授权地址", "微信公众平台授权页面重试授权异常Index:重试授权,异常信息:" + ex01.ToString());
}
}
return null;
#endregion 重试授权
}
ViewBag.AuthUrl = authUrl;
return View();
}
private int GetAuthUrl(int adminsId, out string authUrl)
{
authUrl = string.Empty;
WechatPlatForm oPlatFormInfo = _wechatPlatFormService.GetModel();
if (oPlatFormInfo == null
|| String.IsNullOrEmpty(oPlatFormInfo.PlatFormAppId)
|| String.IsNullOrEmpty(oPlatFormInfo.PlatFormAppSecret)
|| String.IsNullOrEmpty(oPlatFormInfo.ComponentVerifyTicket)
|| String.IsNullOrEmpty(oPlatFormInfo.RedirectUri))
{
Addlog("获取开放平台授权地址", "微信公众平台授权页面GetAuthUrl:公众平台信息未填写完整!");
return -1;
}
string platFormAppId = oPlatFormInfo.PlatFormAppId;
string redirectUrl = System.Web.HttpUtility.UrlEncode(oPlatFormInfo.RedirectUri + "?uId=" + adminsId + "&channelCompanyId=123", System.Text.Encoding.UTF8);//如果需要带多个参数,需要单独对redirectUrl编码
string pre_auth_code = _wechatOpenService.GetPreAuthCode();//预授权码,这个可以参考微信接口来获取
if (!String.IsNullOrEmpty(pre_auth_code))
{
//调用接口获取授权地址
authUrl = _wechatOpenService.GetComponentLoginPageUrl(platFormAppId, pre_auth_code, redirectUrl);
Addlog("获取开放平台授权地址", "微信公众平台授权页面GetAuthUrl:授权地址:" + authUrl + ",授权回调地址:" + redirectUrl);
}
else
{
Addlog("获取开放平台授权地址", "微信公众平台授权页面异常GetAuthUrl:AdminsId:" + adminsId + ",pre_auth_code:" + pre_auth_code + "预授权码为空!");
}
return 1;
}
获取到上面授权地址之后,点击跳转到扫码界面,扫描公众号之后,进入到下面界面:
出现上面界面表示授权成功
其中上面获取预授权码时,授权码被一个公众号使用过之后,其它公众号再授权,需要重新通过微信接口获取, 否则会提示:
下一篇: php中whoops是什么?