In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the development of Wechat how to obtain OAuth2.0 web page authorization authentication and access to user information related, the article is very detailed, has a certain reference value, interested friends must finish reading!
Recently, there is a function of user association authorization login between Wechat official account and users of their own website, mainly that users follow the official account and click on the member center, the web page authorization that requires association authorization will pop up: OAuth3.0 web page authorization, and then the user agrees to obtain user information, associate the user with the website, and then the user can log in using Wechat.
What we do this time is to process each return parameter to get the data in the Action layer of Java.
1. Tools used:
1. Ngrok, map your own native machine to the public network to ensure that you can test and develop at any time.
1. Download ngrok at www.tunnel.mobi/
2. Put the file in the Tomcat directory and run ngrok-config ngrok.cfg-subdomain xinzhi 8080 in cmd.
3. The ngrok tool is seen on Mujia.com @ LAOBI.
2. Wechat official account test account, test at any time, first ensure that there are no problems under the test account, and then transplant the official account.
Second, use to send a Http request in Java, then return the JSON parameter, get the JSON parameter, and then process it.
First of all, get to put the official account test number in the properties file so that we can call or change it, for example: url, please use https
Properties code
AppID = wxf00**c3dd2ebfa0 AppSecret = 3cb220755f****506dc35391aa5c03ec url = https://xinzhi.tunnel.mobi
Here url is the address that we map to the public network, which we need to use later. Then you need two utility classes, which are used to get the return value after sending a http request in the Action of Java
The @ Liufeng code used here is about the server request code http://blog.csdn.net/lyq8479/article/details/9841371. Enable yourself to make corresponding changes to meet the needs of this project:
WeixinUtil.java and MyX509TrustManager.java
Java code
Package com.zhtx.common.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ConnectException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory / * Public platform Common Interface tool Class * * @ author xinz * @ date 2015-10-14 * / public class WeixinUtil {private static Logger log = LoggerFactory.getLogger (WeixinUtil.class) / * initiate a https request and get the result * * @ param requestUrl request address * @ param requestMethod request method (GET, POST) * @ data submitted by param outputStr * @ return JSONObject (get the attribute value of the json object through JSONObject.get (key)) * / public static String httpRequest (String requestUrl, String requestMethod) String outputStr) {StringBuffer buffer = new StringBuffer () Try {/ / create the SSLContext object and initialize TrustManager [] tm = {new MyX509TrustManager ()} with the trust manager we specified; SSLContext sslContext = SSLContext.getInstance ("SSL", "SunJSSE"); sslContext.init (null, tm, new java.security.SecureRandom ()) / / get the SSLSocketFactory object SSLSocketFactory ssf = sslContext.getSocketFactory (); URL url = new URL (requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection (); httpUrlConn.setSSLSocketFactory (ssf); httpUrlConn.setDoOutput (true); httpUrlConn.setDoInput (true); httpUrlConn.setUseCaches (false) from the above SSLContext object / / set request method (GET/POST) httpUrlConn.setRequestMethod (requestMethod); if ("GET" .equalsIgnoreCase (requestMethod)) httpUrlConn.connect (); / / when data needs to be submitted, if (null! = outputStr) {OutputStream outputStream = httpUrlConn.getOutputStream () / / pay attention to the encoding format to prevent outputStream.write (outputStr.getBytes ("UTF-8")); outputStream.close ();} / / convert the returned input stream into the string InputStream inputStream = httpUrlConn.getInputStream () InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); String str = null; while ((str = bufferedReader.readLine ())! = null) {buffer.append (str);} bufferedReader.close (); inputStreamReader.close () / / release resource inputStream.close (); inputStream = null; httpUrlConn.disconnect ();} catch (ConnectException ce) {log.error ("Weixin server connection timed out.");} catch (Exception e) {log.error ("https request error: {}", e) } return buffer.toString ();}}
For the https request, we need a certificate trust manager, which needs to be defined by ourselves, but needs to implement the X509TrustManager interface as follows:
Java code
Package com.zhtx.common.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager / * * Certificate Trust Manager (for https requests) * * @ author xinz * @ date 2015-10-14 * / public class MyX509TrustManager implements X509TrustManager {public void checkClientTrusted (X509Certificate [] chain, String authType) throws CertificateException {} public void checkServerTrusted (X509Certificate [] chain, String authType) throws CertificateException {} public X509Certificate [] getAcceptedIssuers () {return null;}}
Wechat returns a POJO class of parameters:
Java code
The unique identification of the private String openid; / / user: the gender of the private String nickname;// user nickname private Integer sex;// user. A value of 1 is male, a value of 2 is female, and a value of 0 is the city where the personal data of the province private String city;// ordinary user is filled in by the unknown private String province;// user. For example, China is CN private String headimgurl. / / user avatar. The last value represents the square avatar size (optional values are 0, 46, 64, 96, 132, 0 represents 640mm 640 square avatar). This is empty if the user does not have an avatar. If the user changes the avatar, the original avatar URL will be invalid. Private String privilege;// user privilege information, json array, such as Wechat Woka user (chinaunicom) private String unionid;//, this field will not appear until the user binds the official account to the Wechat open platform account. For more information, please see: obtaining users' personal Information (UnionID Mechanism) private String access_token
Classes for authorization credential verification:
Java code
Private String errcode; private String errmsg
Exchange code for web page authorization access_token
Java code
Private String access_token; private String expires_in; private String refresh_token; private String openid; private String scope; private String unionid
For Wechat avatar, if you get a url of http, you need to download the image to the server for storage, and then get the relative path:
Java code
/ * use url or http to save the file * @ Title: fileUpload * @ param @ param fileUrl file url, which can be http * @ param @ param path file storage path * @ return void * @ throws xinz * / public static void fileUpload (String fileUrl,String path) {/ / read the file String S1 = fileUrl Java.io.InputStream is = null; / / defines an input stream. BufferedInputStream bis = null;// defines an input stream with buffering. / / write to local BufferedOutputStream bos = null; / / define an output stream with buffering. Try {java.net.URL url = new java.net.URL (S1); / / create a URL object. Is = url.openStream (); / / opens a connection to this URL and returns an InputStream for reading from that connection. Bis = new java.io.BufferedInputStream (is); File file = new File (path); if (! file.exists ()) {/ / Test whether the file or directory represented by this abstract pathname exists. File.createNewFile (); / / create the file or directory represented by this abstract pathname. } bos = new BufferedOutputStream (new FileOutputStream (file)); byte [] b = new byte [1024]; / / create a byte array. While (bis.read (b)! =-1) {/ / data in the input stream continues to loop bos.write (b) if there is any next line (! =-1); / / writes the byte array to the output stream. }} catch (Exception e) {System.out.println (e.toString ());} finally {try {bos.flush (); / / refresh the output stream of this buffer. Bis.close (); / / closes this input stream. } catch (Exception e) {System.out.println (e.toString ());}
Now that the basic work is done, the development code is now developed. Http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html mentions each step in the Wechat development document, and then we follow this step to develop:
1 step 1: the user agrees to the authorization and obtains the code
2 step 2: exchange for web page authorization access_token through code
3 step 3: refresh access_token (if required)
4 step 4: pull user information (scope is required to be snsapi_userinfo)
5 attached: verify whether the authorization certificate (access_token) is valid
Step 1: the user agrees to the authorization and obtains the code
The url here is the url that we prepared earlier in properties.
Java code
/ * * Wechat user authorization * @ Title: wechatOauth * @ param @ param request * @ param @ param response * @ param * @ param @ return * @ return String * @ throws xinz * / @ RequestMapping ("wechatOauth") public String wechatOauth (HttpServletRequest request,HttpServletResponse response,Model model) {/ * 1 first step: the user agrees to authorize Get code * / / first get the parameters such as AppID and AppSecret of Wechat official account String AppID = ZhtxHelper.getApplicationResourcesProp ("sendSms", "AppID") String urlOpen = ZhtxHelper.getApplicationResourcesProp ("sendSms", "url"); / / if the user authorization is successful, jump to this url String loginUrl = "" + urlOpen+ "/ zhtx-wap/weixin/getAccessToken" / / user authorization, obtain code String url = "https://open.weixin.qq.com/connect/oauth3/authorize?" +" appid= "+ AppID+"+" & redirect_uri= "+ loginUrl+"+" & response_type=code "+" & scope=snsapi_userinfo "+" & state=123#wechat_redirect " / / forward redirect return "redirect:" + url+ ";} step 2: exchange for web page authorization access_tokenJava code through code
/ * getAccessToken * @ param * @ param @ param response * @ param @ param model * @ param * @ return String * @ throws xinz * / @ RequestMapping ("getAccessToken") public String getAccessToken (HttpServletRequest request,HttpServletResponse response) via code Model model) {/ / get the returned parameter try {/ / first get the parameters such as AppID and AppSecret of the official account of Wechat String AppID = ZhtxHelper.getApplicationResourcesProp ("sendSms", "AppID") String AppSecret = ZhtxHelper.getApplicationResourcesProp ("sendSms", "AppSecret"); String code = request.getParameter ("code"); String url = null If {/ * 2 step 2: exchange for web authorization access_token * / user authorization through code Get code url = "https://api.weixin.qq.com/sns/oauth3/access_token?" +" appid= "+ AppID+"+" & secret= "+ AppSecret+"+" & code= "+ code+"+" & grant_type=authorization_code " String requestMethod = "GET"; String outputStr = ""; String httpRequest = WeixinUtil.httpRequest (url, requestMethod, outputStr); System.out.println ("access_token= for web license via code" + httpRequest); AccessTokenModel accTok = JSON.parseObject (httpRequest, AccessTokenModel.class) / * 4 step 4: pull user information (if scope is snsapi_userinfo) * / / user authorization Get code String urlUser = "https://api.weixin.qq.com/sns/userinfo?" +" access_token= "+ accTok.getAccess_token () +" + & openid= "+ accTok.getOpenid () +" + "& lang=zh_CN" String httpUser = WeixinUtil.httpRequest (urlUser, requestMethod, outputStr); System.out.println ("pull user information = =" + httpUser); WechatUser wechatUser = JSON.parseObject (httpUser, WechatUser.class); wechatUser.setAccess_token (accTok.getAccess_token ()) / * 5 attached: verify whether access_token is valid * / WechatMsg checkAccessToken = checkAccessToken (wechatUser.getAccess_token (), wechatUser.getOpenid ()); if (checkAccessToken.getErrcode (). Equals ("0")) {CurrentSession.setAttribute ("wechatUser", wechatUser) WechatUser wechatU = new WechatUser (); wechatU.setOpenid (wechatUser.getOpenid ()); List findWechatUser = wechatUserService.findWechatUser (wechatU); if (findWechatUser.size () > 0) {UserRegister userRegister = userService.findUserByOpenid (wechatUser.getOpenid ()) CurrentSession.setAttribute ("user", userRegister); return "redirect:/user/userCenter";} else {return "/ jsp/wechat/wechatregister" }} else {/ / if the access_token fails, call it again and store the access_ token value. The access_token is valid for 2 hours this.wechatOauth (request, response, model) } catch (Exception e) {System.out.println ("= pull user error = ="); e.printStackTrace ();} / forward redirect return "/ jsp/wechat/wechatregister";} step 4: pull the user and bind the Java code to the user of your own website
/ * * Wechat Associated user * @ Title: saveWechatUser * @ param @ param mobilePhone * @ param password * @ param @ param validataCode * @ param @ return * @ return String * @ throws xinz * / @ RequestMapping ("saveWechatUser") public String saveWechatUser (HttpServletResponse response,String mobilePhone,String password) String validataCode) {/ / use the phone number to determine whether the phone is registered or not UserRegister userRegister = userService.findUserByPhone (mobilePhone) WechatUser wechatUser = (WechatUser) CurrentSession.getAttribute ("wechatUser"); WechatUser wechatU = new WechatUser (); wechatU.setOpenid (wechatUser.getOpenid ()); List findWechatUser = wechatUserService.findWechatUser (wechatU); if (findWechatUser.size () > 0 & & userRegister.getOpenid ()! = null) {CurrentSession.setAttribute ("user", userRegister); return "redirect:/user/userCenter" } else {/ / if it is not registered, start registering if (userRegister==null) {Result saveUserInfoApp = userRegisterService.saveUserInfoApp (mobilePhone, password, validataCode,wechatUser); if (saveUserInfoApp.getState ()) = = 1 / Associate Wechat with the user wechatUserService.saveWechatUser (wechatUser) CurrentSession.setAttribute ("user", userRegister); return "redirect:/user/userCenter" }} else if (userRegister.getOpenid () = = null | | userRegister.getOpenid () .equals (")) {/ / otherwise, query the user information, put it in session, associate Wechat, and jump to user Center UserRegister userReg = new UserRegister (); userReg.setId (userRegister.getId ()) / / deposit Wechat openid userReg.setOpenid (wechatUser.getOpenid ()); userService.upUser (userReg); UserInfo user = new UserInfo (); / / deposit Wechat avatar / / picture type String dateStr = DateUtil.format (DateUtil.getCurrentDate (), "yyyyMMdd") + "/" / / Image type String imgType = "JPG"; / / Wechat avatar name String app2DBarNameAndType = UuidUtil.getUUID () + "." + imgType; / / Wechat avatar path String path = ZhtxHelper.getApplicationResourcesProp ("application", "app.img.projectpath") + SysConstant.GOODS2DBARPATH + dateStr File file1 = new File (path); file1.mkdirs (); / / Image full path String imgUrl = SysConstant.GOODS2DBARPATH + dateStr+app2DBarNameAndType; FileUtil.fileUpload (wechatUser.getHeadimgurl (), path); user.setRegisterId (userRegister.getId ()); user.setImageUrl (imgUrl) UserInfoService.updateUserInfo (user); / / deposit Wechat users wechatUserService.saveWechatUser (wechatUser); UserRegister userW = userService.findUserByPhone (mobilePhone); CurrentSession.setAttribute ("user", userW); return "redirect:/user/userCenter" } else {CurrentSession.setAttribute ("user", userRegister); return "redirect:/user/userCenter";}} return "redirect:/user/userCenter";} attached: verify whether the access_token is a valid Java code
/ * verify whether access_token is valid * @ Title: checkAccessToken * @ param @ param access_token Web page authorization API calls credentials. Note: this access_token is different from the basic supported access_token * @ param @ param openid user's unique ID * @ return WechatMsg returns the message entity * @ throws xinz * / public static WechatMsg checkAccessToken (String access_token String openid) {String requestMethod = "GET" String outputStr = ""; String url = "https://api.weixin.qq.com/sns/auth?" +" access_token= "+ access_token+" + "& openid=" + openid+ ""; String httpmsg = WeixinUtil.httpRequest (url, requestMethod, outputStr); System.out.println ("pull user information return message =" + httpmsg) WechatMsg msg = JSON.parseObject (httpmsg, WechatMsg.class); return msg;}
Then on the web side, you need to write an H5 page to associate your website with Wechat users. Here, I use the mobile number, and the user enters the mobile number to make a judgment. If the user has registered, it is directly related. If the user has not registered, associate after registration, and jump to the member center after completion.
The above is all the contents of this article entitled "how to obtain OAuth2.0 web page authorization authentication and obtain user information for Wechat development". 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: 228
*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.