This article mainly introduces the twelfth step of Java WeChat public platform development in detail. The acquisition of WeChat user information has a certain reference value. Interested friends can refer to the previous
The article talks about a series of WeChat development articles, including token acquisition, menu creation, etc. In this article, we will describe how to obtain WeChat user information in the development of WeChat public platform. In the previous article, we talked about WeChat users and WeChat The connection between public accounts can be related through Openid, so here we use openid to obtain user WeChat information and implement a simple scenario application: when a new WeChat user follows our WeChat public platform, we automatically reply with a picture and text message, and then the title in the graphic message is: [Dear: XXX, hello! 】, and the picture in the graphic message is the user's WeChat avatar, as shown below:
For documents on obtaining WeChat user information, we can refer to: mp.weixin.qq .com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html .
(1) Implementation of obtaining user WeChat messages
After a follower interacts with a public account, the public account can obtain the follower’s OpenID (encrypted For WeChat, each user's OpenID for each official account is unique. For different official accounts, the same user's openid is different). Public accounts can obtain basic user information based on OpenID through this interface, including nickname, avatar, gender, city, language and time of attention.
http request method: GET api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
at Here I wrote a method class GetUseInfo.java. In the method, we only need to pass in openid to return (nickname, image, gender [other parameters can be obtained by yourself]). The code is implemented as follows:
package com.cuiyongzhi.wechat.common; import java.util.HashMap; import com.cuiyongzhi.web.util.GlobalConstants; import com.cuiyongzhi.wechat.util.HttpUtils; import net.sf.json.JSONObject; /** * ClassName: GetUseInfo * @Description: 获取微信用户信息 * @author dapengniao * @date 2016年3月18日 下午2:00:52 */ public class GetUseInfo { /** * @Description: 通过openid获取用户微信信息 * @param @param openid * @param @return * @param @throws Exception * @author dapengniao * @date 2016年3月18日 下午2:01:30 */ public static HashMap<String, String> Openid_userinfo(String openid) throws Exception { HashMap<String, String> params = new HashMap<String, String>(); params.put("access_token", GlobalConstants.getInterfaceUrl("access_token")); //定时器中获取到的token params.put("openid", openid); //需要获取的用户的openid params.put("lang", "zh_CN"); String subscribers = HttpUtils.sendGet( GlobalConstants.getInterfaceUrl("OpenidUserinfoUrl"), params); System.out.println(subscribers); params.clear(); //这里返回参数只取了昵称、头像、和性别 params.put("nickname", JSONObject.fromObject(subscribers).getString("nickname")); //昵称 params.put("headimgurl", JSONObject.fromObject(subscribers).getString("headimgurl")); //图像 params.put("sex", JSONObject.fromObject(subscribers).getString("sex")); //性别 return params; } }
(2)Follow and replyImage and text message implementation
It is said in the first part [After followers interact with the official account to generate messages, the official account can Obtain the follower's OpenID]. In our scenario, the event to obtain the follower's openid is the user's attention event. At the same time, we also passively reply to the follower's graphic message in the following event (the graphic message For the implementation of reply, please refer to: Java WeChat Public Platform Development (5) Implementation of Text and Graphic Message Reply), the implementation process:
Obtain the openid through the follow event, and call the user information interface to obtain the follower related interface ;
Set the title and picture of the graphic message in the passive reply to the follow event, and reply to the follower;
The simple code is implemented as follows:
//对图文消息 NewsMessage newmsg=new NewsMessage(); newmsg.setToUserName(openid); newmsg.setFromUserName(mpid); newmsg.setCreateTime(new Date().getTime()); newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS); if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // 关注事件 System.out.println("==============这是关注事件!"); try { HashMap<String, String> userinfo=GetUseInfo.Openid_userinfo(openid); Article article=new Article(); article.setDescription("欢迎来到崔用志的个人博客:菜鸟程序员成长之路!"); //图文消息的描述 article.setPicUrl(userinfo.get("headimgurl")); //图文消息图片地址 article.setTitle("尊敬的:"+userinfo.get("nickname")+",你好!"); //图文消息标题 article.setUrl("http://www.cuiyongzhi.com"); //图文url链接 List<Article> list=new ArrayList<Article>(); list.add(article); //这里发送的是单图文,如果需要发送多图文则在这里list中加入多个Article即可! newmsg.setArticleCount(list.size()); newmsg.setArticles(list); return MessageUtil.newsMessageToXml(newmsg); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("====代码有问题额☺!"); logger.error(e,e); } }
Finally, we can take a look at our results, here In order to see the effect very intuitively, I unfollowed and then followed again, as shown below:
[Related recommendations]
3. Comprehensive analysis of Java annotations
The above is the detailed content of Java uses openid to obtain user micro information. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

SublimeText3 Linux new version
SublimeText3 Linux latest version
