国产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網頁授權

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網頁授權

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:

微信開發(fā)之Author網頁授權

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)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

What is the 'static' keyword in Java? What is the 'static' keyword in Java? Jul 13, 2025 am 02:51 AM

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

See all articles