Author webpage authorization developed by WeChat
Feb 15, 2017 am 11:15 AMIn WeChat development, there are often such needs: obtaining user avatars, binding WeChat ID to send messages to users... Then the prerequisite for achieving these is authorization!
1. Configure the security callback domain name:
Before the WeChat official account requests user webpage authorization, Developers need to first go to the "Development - Interface Permissions - Web Services - Web Accounts - Web Authorization to Obtain Basic User Information" configuration options 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 written directly here. For example: www.liliangel.cn. However, when we develop h5, we generally use second-level domain names, such as h5.liliangel.cn, which is also in the safe callback domain name.
2. User-level authorization and silent authorization
1. Web page authorization initiated with snsapi_base as scope is used to obtain The openid of the user who enters the page is silently authorized and automatically jumps to the callback page. What the user perceives is that they directly enter the callback page.
2. Web page authorization initiated with snsapi_userinfo as the scope is used to obtain the user's basic information. However, this kind of authorization requires manual consent from the user, and since the user has agreed, the basic information of the user can be obtained after authorization without paying attention.
3. The difference between web page authorization access_token and ordinary access_token
1. WeChat web page authorization is implemented through the OAuth2.0 mechanism. After the user authorizes the official account, The official account can obtain a web page authorization-specific interface call credential (web page authorization access_token). Through the web page authorization access_token, the post-authorization interface call can be made, such as obtaining basic user information;
2. Other WeChat interfaces need to be passed The "get access_token" interface in basic support is used to obtain the ordinary access_token call.
4. Guide the user to enter the authorization page to agree to the authorization and obtain the code
After the WeChat update, the authorization page has also changed. In fact, I am used to the green classic 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{ ????????????????????//沒有微信用戶信息,沒有授權-->>?需要授權,跳轉授權頁面 ????????????????????window.location.href?=?'https://open.weixin.qq.com/connect/oauth2/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, the authorization method is entered. First, the wxUserInfo object is obtained from the cache. If there is a description that it has been authorized before, directly enter the initialization method. If not, determine whether the URL contains a code. If there is a code, it indicates that it is the page after entering the callback of the authorization page. Then the code can be exchanged for user information. There is no code, that is, the user enters the page for the first time and is directed to the authorization page. The redirect_uri is the current page address.
getWxUserInfo method:
/** ?????*?授權后獲取用戶的基本信息 ?????*/ ????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?{ ????????????????????????//保證寫入的wxUserInfo是正確的 ????????????????????????var?data?=?JSON.parse(json); ????????????????????????if?(data.openid)?{ ????????????????????????????localStorage.setItem('wxUserInfo',json);//寫緩存--微信用戶信息 ????????????????????????} ????????????????????}?catch?(e)?{ ????????????????????????//?TODO:?handle?exception ????????????????????} ????????????????} ????????????} ????????}); ????},
5.Background restful-- / wechat/authorization, exchange user information according to code
/** ?????*?微信授權 ?????*?@param?code?使用一次后失效 ?????*? ?????*?@return?用戶基本信息 ?????*?@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(); ????????} ????}
There is an authorization access_token here, remember : Authorize access_token non-global access_token, which requires the use of cache. I am using redis here. I will not go into the specific configuration and will write a related configuration blog later. Of course, you can also use ehcache. The ehcahe configuration is described in detail in my first blog.
/** ?????*?根據(jù)code?獲取授權的token?僅限授權時使用,與全局的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)?{????????????????//已過期,需要刷新 ????????????????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/oauth2/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{????????????//還沒有過期 ????????????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); ????} /** ?????*?根據(jù)授權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);???????????? ????????????//保存用戶信息???????????? ????????????saveWeixinUser(hs);???????????? ????????????return?hs; ????????}?catch?(IOException?e)?{ ????????????LOGGER.error("RestFul?of?authorization?is?error.",e); ????????}???????? ????????return?null; ????}
I was in a hurry and the code naming was confusing. As you can see, I used a synchronous method. First, I obtained the key WEIXIN_SQ_ACCESS_TOKEN from the cache. If the obtained instructions are not expired, I directly called the interface provided by WeChat through httpclient and returned the string of user information to the front end. If it is not obtained, it means that it does not exist or has expired. Then refresh the access_token according to the refresh_token and then write the cache. Since the access_token has a short validity period, in order to be safe, I set the cache expiration time here and subtract one hour from the time given by WeChat. Looking back at the code, I found that there is a slight problem with the above logic. Writing it this way will cause the access_token to be refreshed for the first time or after the cache expires. It does not affect the use for the time being. We will make optimization and modification TODO later.
6: Save user information
Normally, after authorization, we will save the user information in the database table, openid is the only primary key, and the foreign key is associated with our own user table. In this way , no matter what business is to be carried out in the future, or whether it is to do operational data statistics, there is a relationship with the WeChat official account. It is worth noting that the headimgurl we obtained is a url address provided by WeChat. When the user modifies the avatar, the original address may become invalid, so it is best to save the image to the local server and then save the local address url. !
Value returned by WeChat:
For more related articles on Author webpage authorization for WeChat development, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
