国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. Configure the security callback domain name:
2. User-level authorization and silent authorization
3. The difference between web page authorization access_token and ordinary access_token
4. Guide the user to enter the authorization page to agree to the authorization and obtain the code
js:
getWxUserInfo method:
5.Background restful-- / wechat/authorization, exchange user information according to code
6: Save user information
Home WeChat Applet WeChat Development Author webpage authorization developed by WeChat

Author webpage authorization developed by WeChat

Feb 15, 2017 am 11:15 AM
java WeChat public account development

In 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:

微信開發(fā)之Author網(wǎng)頁授權(quán)

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

微信開發(fā)之Author網(wǎng)頁授權(quán)

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{
????????????????????//沒有微信用戶信息,沒有授權(quán)-->>?需要授權(quán),跳轉(zhuǎn)授權(quán)頁面
????????????????????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:


/**
?????*?授權(quán)后獲取用戶的基本信息
?????*/
????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


  /**
?????*?微信授權(quán)
?????*?@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?獲取授權(quán)的token?僅限授權(quán)時使用,與全局的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ù)授權(quán)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:

微信開發(fā)之Author網(wǎng)頁授權(quán)

For more related articles on Author webpage authorization for WeChat development, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

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.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

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

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

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

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

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

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles