Micro-credit development, often have such a demand: Get the user avatar, binding micro-signal to the user to send information. So the prerequisite for achieving these is authorization!
1. Configure the security callback domain name:
Before the user's website authorization is requested by the micro-credit public number, developers need to first to the public platform in the "Development-interface permissions-Web services-Web account-Web Access authorization to obtain user information," The configuration options, modify the authorization callback domain name, it is noteworthy that this is the direct write full domain name, such as: www.liliangel.cn. However, we develop H5 is generally used in the class two domain name, such as: H5.liliangel.cn also in the security callback domain name.
2. User-level authorization and silent authorization
1, the snsapi_base for the scope of the launch of the Web page authorization, is used to obtain access to the page of the user's OpenID, and is silent authorization and automatically jump to the callback page. What the user perceives is a direct entry into the callback page.
2, the Snsapi_userinfo for the scope of the launch of the Web page authorization, is used to obtain the user's basic information. However, this authorization requires the user to manually agree, and because the user agreed, so no concern, you can obtain the user's basic information after authorization.
3. The difference between Web page authorization Access_token and ordinary Access_token
1, micro-letter page authorization is achieved through the OAuth2.0 mechanism, after the user authorized to the public number, the public number can obtain a Web page authorization-specific interface call credentials (Web page authorization Access_token), through the Web page authorization Access_token can be authorized after the interface calls, such as access to user basic information;
2, other micro-communication interface, need to get through the basic support of the "Get Access_token" interface to obtain the normal Access_token call.
4. Guide the user to enter the authorization page consent authorization, get code
After the micro-mail update, the authorization page has also changed. Actually accustomed to the green that 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{
//No micro-credit user information, no authorization-->> need authorization, jump authorization page
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, the page load time to enter the authorization method, first from the cache to obtain Wxuserinfo objects, if there is a description has been authorized before, directly into the initialization method. If not, to determine whether the URL contains code, a code description is to enter the authorization page callback after the page, then the code in exchange for user information. No code, that is, the first time the user entered the page, to guide the authorization page, Redirect_uri for the current page address.
Getwxuserinfo Method:
/**
* Authorization to obtain the user's basic information * *
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 {
//Guaranteed write Wxuserinfo is the correct
var data = Json.parse (JSON );
if (Data.openid) {
localstorage.setitem (' Wxuserinfo ', JSON);//write Cache-Micro-user information
}
catch (e) {
/TODO : Handle Exception}}}
);
5. Backstage restful--/wechat/authorization, in exchange for the user information according to the code
/** *
Micro-Letter Authorization
* @param code used once after failure
* *
@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 ();
}
There is an authorization Access_token, remember: authorization Access_token not global Access_token, need to use cache, here I use the Redis, the specific configuration does not say behind write related configuration blog, of course, can also use Ehcache, The Ehcahe configuration is described in detail in my first blog post.
/** * is used only for authorization token according to code acquisition authorization, different from global Access_token * @param code * @return * @throws IOException * @throw S clientprotocolexception */public string Getoauthaccesstoken (string code) throws Clientprotocolexception, ioexcept
ion{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) {//has expired, the String hs = apiservice.doget (URL) needs to be refreshed;
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{//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) {Str ing 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, the code naming is rather messy. You can see that I used a synchronized method, first from the cache to get key for Weixin_sq_access_token, if the description has not expired, directly through the httpclient call the interface provided by the micro-letter, return the user information string to the front end. If not, the description is not or has expired, then according to Refresh_token refresh Access_token, and then write cache, because the Access_token has a shorter validity period, in order to insure me here set the cache expiration time micro-letter give time minus one hours. Looking back at the code found that the logic above a little bit of a problem, this will cause the first acquisition or cache failure after the first acquisition of Access_token will go to refresh, temporarily do not affect the use of the following do the optimization of TODO.
6: Save user information
In general, after the authorization we will save the user Information database table, OpenID is the only primary key, foreign key associated with our own user table, this way, no matter what business to carry out, or do operation data statistics, have a relationship with the micro-letter public number. It is noteworthy that the headimgurl we have obtained is a URL address provided by the micro-letter, which may cause the original address to fail when the user modifies the avatar, so it is best to save the picture to the local server and save the local address url!
The value returned by the micro-letter:
Reference Links:
Micro-Credit Public platform Official document: Https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN
On-Line interface debugging tool: Http://mp.weixin.qq.com/debug
No public number benefits: Test Account Application Http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
Above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!