微信公众号登录,微信公众号注册?

写在前面

在日常开发过程中,我们经常需要实现网页授权登录来获取用户的openId。随着开发的进行,我们可能会遇到多个网页都需要使用用户的openId,但我们不可能每次都编写一个授权登录的接口来适配每个网页。为了减少重复的工作,本文将分享一个公共授权方案,包括未配置安全域名的网页。如果有任何不足之处,请在评论区指出。

我们选择了Java作为开发语言,并使用了Spring Boot框架。

前期配置

我们都知道要想实现微信公众号的网页授权登录,需在公众号管理后台“设置与开发”->“公众号设置”->"功能设置"中设置网页授权域名,如下图所示

微信公众号登录,微信公众号注册?

网页授权域配置

然而,微信官方对于此域名的配置限制为仅可设置两个。但是,如果我们需要跳转到其他域名,也有一种简单的解决方法。接下来,我将为您详细介绍。

授权流程

众所周知,要进行微信网页授权,只需要确保微信公众账号拥有相应的授权作用域(scope参数)权限即可。对于已认证的服务号来说,默认就拥有了scope参数中的snsapi_base和snsapi_userinfo权限。因此,我们只需要引导关注者打开以下页面:

请点击以下链接进行微信授权登录:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

需要特别留意的是,这里的授权登录可能会经历多次转发,从而导致授权码过期的情况。为了解决这个问题,可以在请求中添加参数connect_redirect=1,以告知微信只进行一次跳转。

我们可以在REDIRECT_URI这个地址上实现公共网页的授权登录。当用户确认授权后,微信会将用户转发到这个地址上。我们可以在这个地址上进行相关操作,以实现公共网页的授权登录功能。

关于作用域(scope)的说明,这里不再详细描述。snsapi_base只能获取用户的openid,并且用户在使用过程中是无感知的,也就是说用户不会察觉到有任何操作。而snsapi_userinfo可以获取用户的基本信息,但需要用户手动确认,除非特殊情况(对于已关注公众号的用户,如果用户从公众号的会话或自定义菜单进入本公众号的网页授权页,即使scope为snsapi_userinfo,也是静默授权,用户无感知)。

实现代码

/**

* 公共重定向

* @param url

* @param Request

* @return

*/

@RequestMapping("/common")

public String generateAuthUrl(String url, HttpServletRequest request)

try {

if (url==null || url.isEmpty()) {

return "/error";

}

return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + environment.getProperty("wechat.appId")

+ "&redirect_uri="

+ URLEncoder.encode(

String baseRedirectUrl=environment.getProperty("wechat.baseRedirectUrl");
String encodedUrl=URLEncoder.encode(url, "utf-8");
String authCommonUrl=baseRedirectUrl + "/authcommonurl?url=" + encodedUrl;

return authCommonUrl;

"utf-8")

+ "&response_type=code&scope=snsapi_userinfo&connect_redirect=1&state=join#wechat_redirect";

} catch (Exception e) {

logger.error("重定向发生异常->RedirectController.authCommon:" + ParamsUtils.showParams(request), e);

logger.error("重定向发生异常->RedirectController.authCommon:" + ParamsUtils.showParams(request), e);是一段用于记录日志的代码。它的作用是在发生重定向异常时,将异常信息和请求参数记录下来。

为了更好地理解这段代码,我们可以将其重新表达如下:

在RedirectController.authCommon方法中,发生了重定向异常。异常信息和请求参数已被记录在日志中。

请注意,这段代码的前后意思没有改变,只是进行了重新表达。

return "/error";

}

}

我们可以注意到,我们将redirect_uri设置为一个公共的接口地址,用于获取用户信息。然后,我们可以在该地址上传入我们需要最终跳转的URL。如果我们需要传递其他参数,我们可以直接将它们添加到URL中。重要的是,我们需要确保redirect_uri在网页授权的安全域名下,而URL可以是任意域名。

重定向URL地址以获取用户信息

/**

* 授权回调转发

* @param url

* @param code

* @param request

* @return

*/

@SuppressWarnings({ "unchecked" }) annotation is used to suppress unchecked warnings in Java. It is used to indicate that the programmer is aware of the potential risks of using unchecked operations or types, but has made a conscious decision to ignore them.

By using this annotation, the compiler will not generate warnings for unchecked operations or types in the annotated code. This can be useful in situations where the programmer is confident that the code is safe and does not need to be checked for unchecked operations or types.

However, it is important to note that using this annotation should be done with caution. It should only be used when the programmer is certain that the code is safe and will not cause any issues. Ignoring unchecked warnings without proper understanding can lead to runtime errors or unexpected behavior in the code.

Therefore, it is recommended to use this annotation sparingly and only when necessary. It is always a good practice to understand the risks associated with unchecked operations or types and handle them appropriately in the code.

@RequestMapping(value="/commonurl")

public String authenticate(String url, String code, HttpServletRequest request) {

The code initializes an HttpSession object by calling the getSession() method on the request object.

try {

if (url==null || url.isEmpty()) {

return "/error";

}

if (code==null || code.isEmpty()) {

return "/error";

}

// 首先检查session中是否存储了用户信息,如果存在,则跳过下面的获取用户信息的步骤,如果不存在,则继续执行获取用户信息的方法。

String sessionId=getSessionId(session);

CacheObject<JSONObject> cache=MapCacheManager.getInstance().getCache(sessionId);

In the given code, a cache object of type `CacheObject<JSONObject>` is being retrieved from the cache manager using the session ID.

JSONObject userInfoJO=null;
if (cache !=null) {
userInfoJO=cache.getObject();
} else {
userInfoJO=null;
}

if (userInfoJO==null || StringUtils.isEmpty(userInfoJO.optString("nickname", ""))) {// 里面为整个网页登录授权过程

// 调用获取访问令牌的接口,以获取访问令牌。

String json=HttpsUtil.sendHttpGetRequest(getAccessTokenUrl(code), "UTF-8");

JSONObject jsonObject=null;

try {

jsonObject=JSONObject.parseObject(json);

} catch (Exception e) {

logger.error("转换json异常,获取授权accesstoken失败。错误信息:NotStaticAuthReturnController.authHd:" + json, e);

}

if (jsonObject.has("access_token")==false) {

return "/error";

}

String accessToken=jsonObject.optString("access_token", "");

String openid=jsonObject.optString("openid", "default");

// 得到获取用户信息的链接

// 用户信息查询接口 查询用户信息

String userInfoJson=HttpsUtil.sendGetRequest(getUserinfoUrl(access_token, openid), "UTF-8");

try {

userInfoJO=JSONObject.parse(userInfoJson);

} catch (JSONException e) {

userInfoJO=new JSONObject();

logger.error("转换用户信息为JSON时发生异常->NotStaticAuthReturnController.authcommon:" + userInfoJson, e);

}

if (!userInfoJO.has("nickname")) {

return "/error";

}

userInfoJO.put("nickname", EmojiFilter.filterEmoji(userInfoJO.optString("nickname", "")));

cache=new CacheObject<>();

cache.setExpires_in(7200L);

cache.setObject(userInfoJO);

CacheManager.getInstance().putCache(sessionId, cache);

}

// System.out.println("用户信息:" + userInfoJO.toString());//用于测试,输出用户信息

String user_openid=userInfoJO.optString("openid", "");

if (user_openid==null || user_openid.isEmpty()) {

return "/error";

}

返回 "重定向:" + url + (url.contains("?") ? "&" : "?") + "openId=" + user_openid;

} catch (Exception e) {

e.printStackTrace();

logger.error("微信授权异常->NotStaticAuthReturnController.authCommonurl:" + ParamsUtils.showParams(request), e);

logger.error("微信授权异常->NotStaticAuthReturnController.authCommonurl:" + ParamsUtils.showParams(request), e);是一个用于记录错误日志的代码。它的作用是在发生微信授权异常时,将异常信息和相关参数记录下来,以便后续排查和处理问题。

在这段代码中,使用了logger.error()方法来记录错误日志。该方法接受一个字符串作为参数,用于描述错误的具体信息。在这里,字符串的内容包括了"微信授权异常->NotStaticAuthReturnController.authCommonurl:"、ParamsUtils.showParams(request)和异常对象e的信息。

ParamsUtils.showParams(request)是一个用于展示请求参数的方法。它接受一个HttpServletRequest对象作为参数,并返回一个字符串,该字符串包含了请求参数的详细信息。

最后,异常对象e是通过catch语句捕获到的异常。它包含了发生异常时的具体信息,如异常类型、异常消息等。

通过将异常信息和相关参数记录下来,开发人员可以更方便地定位和解决问题,提高系统的稳定性和可靠性。

return "/error";

}

}

在这里,我们使用了snsapi_userinfo作用域来获取用户的基本信息。如果不需要这些信息,只需根据需求删除相应的代码即可。

如果您对我的回答有任何问题或者有任何改进的建议,请在评论区提出。如果您对我的回答满意,希望您能给我一个赞!非常感谢!

祝愿大家身体健康,每天都能心情愉快!

创业项目群,学习操作 18个小项目,添加 微信:80709525  备注:小项目

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 sumchina520@foxmail.com 举报,一经查实,本站将立刻删除。
如若转载,请注明出处:https://www.ya58.com/25255.html