In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of Author web page authorization developed by Wechat. The article is very detailed and has a certain reference value. Interested friends must finish reading it!
In the development of Wechat, there is often a need to get user avatars and bind WeChat accounts to send messages to users. Then the premise to achieve these is authorization!
1. Configure the domain name of security callback:
Before the official Wechat account requests a user's web page authorization, the developer needs to go to the "Development-API permission-Web service-Web account-Web license to obtain basic user information" configuration option on the official website of the public platform to modify the authorization callback domain name. It is worth noting that the full domain name is directly written here, such as www.liliangel.cn. However, we generally use second-level domain names in the development of H6, such as: h6.liliangel.cn is also in the security callback domain name.
After the Wechat update, the authorization page has also changed. In fact, I am used to the classic green page..
Js:var center = {init: function () {. }, enterWxAuthor: function () {var wxUserInfo = localStorage.getItem ("wxUserInfo"); if (! wxUserInfo) {var code = common.getUrlParameter ('code'); if (code) {common.getWxUserInfo (); center.init () } else {/ / has no Wechat user information and no authorization-- > > requires authorization. Jump to the authorization page _ window.location.href = 'https://open.weixin.qq.com/connect/oauth3/authorize?appid='+ WX_APPID +' & redirect_uri='+ _ window.location.href +'& response_type=code&scope=snsapi_userinfo#wechat_redirect' }} else {center.init ();} $(document) .ready (function () {center.enterWxAuthor ();}
Take scope=snsapi_userinfo as an example. When the page is loaded, enter the authorization method. First, get the wxUserInfo object from the cache. If it has been authorized before, go directly to the initialization method. If not, determine whether the url contains code. If there is a code description, you can enter the page after the authorization page is called back, then you can exchange the user information through code. There is no code, that is, the user enters the page for the first time and guides to authorize the page. Redirect_uri is the current page address.
GetWxUserInfo method: / * obtain basic information of the user after authorization * / getWxUserInfo:function (par) {var code = common.getUrlParameter ("code"); if (par) code = par $.ajax ({async: false, data: {code:code}, type: "GET", url: WX_ROOT + "wechat/authorization" Success: function (json) {if (json) {try {/ / guarantee that the wxUserInfo written is the correct var data = JSON.parse (json) If (data.openid) {localStorage.setItem ('wxUserInfo',json) / / write cache-Wechat user information}} catch (e) {/ / TODO: handle exception});}, 5. Background restful-- / wechat/authorization Exchange for user information according to code / * * Wechat authorization * @ param code expires after one use * * @ return user basic information * @ throws IOException * / @ RequestMapping (value = "/ authorization", method = RequestMethod.GET) public void authorizationWeixin (@ RequestParam String code, HttpServletRequest request) HttpServletResponse response) throws IOException {request.setCharacterEncoding ("UTF-8") Response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); LOGGER.info ("RestFul of authorization parameters code: {}", code); try {String rs = wechatService.getOauthAccessToken (code); out.write (rs); LOGGER.info ("RestFul of authorization is successful.", rs) } catch (Exception e) {LOGGER.error ("RestFul of authorization is error.", e);} finally {out.close ();}}
Here is an authorized access_token, remember: authorized access_token non-global access_token, need to use cache, here I use redis, not to mention the specific configuration later write about the configuration blog, of course, you can also use ehcache, on the configuration of ehcahe in my first blog is detailed.
/ * * token licensed under code can only be used for authorization, unlike global access_token * @ param code * @ return * @ throws IOException * @ throws ClientProtocolException * / public String getOauthAccessToken (String code) throws ClientProtocolException, IOException {String data = redisService.get ("WEIXIN_SQ_ACCESS_TOKEN"); String rs_access_token = null; String rs_openid = null String url = WX_OAUTH_ACCESS_TOKEN_URL + "? appid=" + WX_APPID+ "& secret=" + WX_APPSECRET+ "& code=" + code+ "& grant_type=authorization_code"; if (StringUtils.isEmpty (data)) {synchronized (this) {/ / expired and needs to be refreshed String hs = apiService.doGet (url); JSONObject json = JSONObject.parseObject (hs) String refresh_token = json.getString ("refresh_token"); String refresh_url = "https://api.weixin.qq.com/sns/oauth3/refresh_token?appid="+WX_APPID+"&grant_type=refresh_token&refresh_token="+refresh_token; String r_hs = apiService.doGet (refresh_url); JSONObject r_json = JSONObject.parseObject (r_hs) String r_access_token = r_json.getString ("access_token"); String r_expires_in = r_json.getString ("expires_in"); rs_openid = r_json.getString ("openid"); rs_access_token = r_access_token RedisService.set ("WEIXIN_SQ_ACCESS_TOKEN", r_access_token, Integer.parseInt (r_expires_in)-3600); LOGGER.info ("Set sq access_token to redis is successful.parameters time: {}, realtime", Integer.parseInt (r_expires_in), Integer.parseInt (r_expires_in)-3600) }} else {/ / has not expired String hs = apiService.doGet (url); JSONObject json = JSONObject.parseObject (hs); rs_access_token = json.getString ("access_token"); rs_openid = json.getString ("openid") LOGGER.info ("Get sq access_token from redis is successful.rs_access_token: {}, rs_openid: {}", rs_access_token,rs_openid);} return getOauthUserInfo (rs_access_token,rs_openid) } / * * obtain user information according to authorized token * @ param access_token * @ param openid * @ return * / public String getOauthUserInfo (String access_token,String openid) {String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ access_token +" & openid= "+ openid +" & lang=zh_CN " Try {String hs = apiService.doGet (url); / / Save user information saveWeixinUser (hs); return hs;} catch (IOException e) {LOGGER.error ("RestFul of authorization is error.", e);} return null;}
At that time, I was in a hurry, and the code naming was messy. As you can see, I use a synchronous method. First, I get the key as WEIXIN_SQ_ACCESS_TOKEN from the cache. If the description has not expired, call the API provided by Wechat directly through httpclient, and return the string of user information to the frontend. If it is not available, or it has expired, refresh the access_token according to refresh_token, and then write the cache. Since access_token has a short validity period, to ensure that I set the cache expiration time here, Wechat reduces the cache expiration time by another hour. Looking back at the code, it is found that there is a slight problem with the above logic. Writing in this way will lead to a refresh for the first time to get the access_token or the first time to get the TODO after the cache expires. It will not affect the use for the time being, and then optimize and modify the API.
6: save user information
Usually, after authorization, we save the user information in the database table, with openid as the only primary key, and the foreign key is associated with our own user table, so that no matter what business we need to carry out or do operation data statistics, there is a relationship with the official account of Wechat. It is worth noting that the headimgurl we obtained is a url address provided by Wechat, which may invalidate the original address when the user modifies the avatar, so it is best to save the picture to the local server and then save the local address url!
The value returned by Wechat:
The above is all the contents of this article "sample Analysis of Author Web Page Authorization developed by Wechat". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.