微信公眾號開發之獲取用戶列表和用戶基本信息(五)


一、獲取用戶列表

公眾號可通過本接口來獲取帳號的關注者列表,關注者列表由一串OpenID(加密后的微信號,每個用戶對每個公眾號的OpenID是唯一的)組成。一次拉取調用最多拉取10000個關注者的OpenID,可以通過多次拉取的方式來滿足需求。

接口調用請求說明

http請求方式: GET(請使用https協議)
https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
參數 是否必須 說明
access_token 調用接口憑證
next_openid 第一個拉取的OPENID,不填默認從頭開始拉取

返回說明

正確時返回JSON數據包:

{
    "total":2,
    "count":2,
    "data":{
    "openid":["OPENID1","OPENID2"]},
    "next_openid":"NEXT_OPENID"
}
參數 說明
total 關注該公眾賬號的總用戶數
count 拉取的OPENID個數,最大值為10000
data 列表數據,OPENID的列表
next_openid 拉取列表的最后一個用戶的OPENID

 我們定義一個方法獲取用戶列表

package com.xu.wemall.components.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.commons.constants.URIConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class WxUserUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    /**
     *獲取帳號的關注者列表
     * @return
     */
    public JSONObject getUserList(String nextOpenid){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null){
            log.info("URL{}",URIConstant.USER_LIST_URL);
            String url = URIConstant.USER_LIST_URL.replace("ACCESS_TOKEN", accessToken);

            if(nextOpenid != null){
                url = URIConstant.USER_LIST_URL + "&next_openid="+ nextOpenid;
            }
            log.info("USER_LIST_URL:{}",url);

            //發起POST請求創建菜單
            JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class);

            return jsonObject;
        }
        return null;
    }

}

在controller中調用這個方法

package com.xu.wemall.controller.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.commons.constants.WXConstant;
import com.xu.wemall.components.weixin.WxUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 類名稱: LoginController
 * 類描述: 與微信對接登陸驗證
 *
 * @author RonnieXu
 * 創建時間:2017年12月5日上午10:52:13
 */
@Slf4j
@RestController
@Api(tags = "微信用戶接口")
@RequestMapping(value = "/wxuser")
public class WxUserController {

    @Autowired
    private WxUserUtil wxUserUtil;

    @Autowired
    private RestTemplate restTemplate;

    @ApiIgnore
    @RequestMapping(value="/login", method = RequestMethod.GET)
    public void wxLogin(HttpServletResponse response) throws IOException {
        //請求獲取code的回調地址
        //用線上環境的域名或者用內網穿透,不能用ip
        String callBack = "http://jialeyuan.nat300.top/wxAuth/callBack";

        //請求地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + WXConstant.TEST_APPID +
                "&redirect_uri=" + URLEncoder.encode(callBack,"utf-8") +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        //重定向
        response.sendRedirect(url);
    }

    // 回調方法
    @ApiIgnore
    @RequestMapping(value ="/callBack", method = RequestMethod.GET)
    public void wxCallBack(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");

        //獲取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + WXConstant.TEST_APPID +
                "&secret=" + WXConstant.TEST_APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        String result = restTemplate.getForObject(url, String.class);

        System.out.println("請求獲取access_token:" + result);
        //返回結果的json對象
        JSONObject resultObject = JSON.parseObject(result);

        //請求獲取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";

        String resultInfo = restTemplate.getForObject(infoUrl, String.class);

        //此時已獲取到userInfo,再根據業務進行處理
        log.info("請求獲取userInfo:{}", resultInfo);

    }

    /**
     * 獲取關注公眾號的用戶列表
     */
    @ApiOperation(value = "獲取關注公眾號的用戶列表")
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="nextOpenid",value="第一個拉取的OPENID,不填默認從頭開始拉取", paramType="query",dataType="String"),
    })
    public JSONObject getUserList(String nextOpenid) {

        JSONObject result = wxUserUtil.getUserList(nextOpenid);
        log.info("user_list:{}", result.toJSONString());
        return result;

    }

}

我們測試一下,看看我們獲取到的關注我們公眾號的用戶列表

 

 

二、獲取用戶詳情

在微信開發過程中,我們有時候需要獲取用戶的一些基礎信息,尤其比如微信公眾號和頭像地址。獲取用戶信息主要是通過以下接口:

接口調用請求說明
http請求方式: GET
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

通過這個接口里的參數 可以看到我們需要先獲得access_token、openid這兩個參數,access_token之前的文章已經說過了,openid是用戶的微信公眾號唯一標識

參數說明

參數 是否必須 說明
access_token 調用接口憑證
openid 普通用戶的標識,對當前公眾號唯一
lang 返回國家地區語言版本,zh_CN 簡體,zh_TW 繁體,en 英語

 

openid在用戶關注我們的公眾號時候就可以獲取到,不過在那里openid叫FromUserName

如果接口響應成功,則返回如下:

返回說明

正常情況下,微信會返回下述JSON數據包給公眾號:

{
    "subscribe": 1, 
    "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", 
    "nickname": "Band", 
    "sex": 1, 
    "language": "zh_CN", 
    "city": "廣州", 
    "province": "廣東", 
    "country": "中國", 
    "headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
    "subscribe_time": 1382694957,
    "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
    "remark": "",
    "groupid": 0,
    "tagid_list":[128,2],
    "subscribe_scene": "ADD_SCENE_QR_CODE",
    "qr_scene": 98765,
    "qr_scene_str": ""
}

 

參數說明

參數 說明
subscribe 用戶是否訂閱該公眾號標識,值為0時,代表此用戶沒有關注該公眾號,拉取不到其余信息。
openid 用戶的標識,對當前公眾號唯一
nickname 用戶的昵稱
sex 用戶的性別,值為1時是男性,值為2時是女性,值為0時是未知
city 用戶所在城市
country 用戶所在國家
province 用戶所在省份
language 用戶的語言,簡體中文為zh_CN
headimgurl 用戶頭像,最后一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),用戶沒有頭像時該項為空。若用戶更換頭像,原有頭像URL將失效。
subscribe_time 用戶關注時間,為時間戳。如果用戶曾多次關注,則取最后關注時間
unionid 只有在用戶將公眾號綁定到微信開放平台帳號后,才會出現該字段。
remark 公眾號運營者對粉絲的備注,公眾號運營者可在微信公眾平台用戶管理界面對粉絲添加備注
groupid 用戶所在的分組ID(兼容舊的用戶分組接口)
tagid_list 用戶被打上的標簽ID列表
subscribe_scene 返回用戶關注的渠道來源,ADD_SCENE_SEARCH 公眾號搜索,ADD_SCENE_ACCOUNT_MIGRATION 公眾號遷移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 掃描二維碼,ADD_SCENE_PROFILE_ LINK 圖文頁內名稱點擊,ADD_SCENE_PROFILE_ITEM 圖文頁右上角菜單,ADD_SCENE_PAID 支付后關注,ADD_SCENE_OTHERS 其他
qr_scene 二維碼掃碼場景(開發者自定義)
qr_scene_str 二維碼掃碼場景描述(開發者自定義)

這里先貼出所有的依賴  

pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xu</groupId> <artifactId>wemall</artifactId> <version>v0.6.1-beta-build20190718</version> <packaging>jar</packaging> <name>wemall</name> <description>this is a wemall project</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <swagger-ui.version>2.9.2</swagger-ui.version> <swagger2.version>2.9.2</swagger2.version> </properties> <dependencies> <!-- spring-boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- 使thymeleaf支持h5標簽 --> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <!-- log related --> <dependency> <!-- exclude掉spring-boot的默認log配置 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--aspectj--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <!-- 表示開發的時候引入,發布的時候不會加載此包 --> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!-- mybatis-plus begin --> <!--mybatis-plus自動的維護了mybatis以及mybatis-spring的依賴,在springboot中這三者不能同時的出現,避免版本的沖突,表示:跳進過這個坑--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.1.0</version> </dependency> <!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger-ui.version}</version> </dependency> <!--排除並新增1.5swagger-annotations和swagger-models 為了解決swagger2中example注解導致的input空字符串異常錯誤--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> </exclusion> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.21</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.21</version> </dependency> <!-- 引入Druid依賴,阿里巴巴所提供的數據源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <!-- 提供mysql驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> <!--jsonwebtoken--> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!--jsonwebtoken--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> <!--熱部署--> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!--redis配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.9</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <!-- alibaba的easyexcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta4</version> </dependency> <!-- pdf實現 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency> <!-- pdf字體包 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <!-- activemq消息隊列 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> <version>2.0.4.RELEASE</version> </dependency> <!--netty--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.16.Final</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.0.31-beta</version> <scope>test</scope> </dependency> <!-- freemarker自定義模板,生成代碼模板時候需要這個--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!--redisson--> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.5.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <includeSystemScope>true</includeSystemScope> <fork>true</fork><!--該配置必須--> <executable>true</executable> <excludeDevtools>false</excludeDevtools> <mainClass>com.xu.wemall.wemallApplication</mainClass> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.4.2</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <encoding>utf-8</encoding> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> 

首先,我們定義一個 微信用戶POJO  

WxUser.java
package com.xu.wemall.entry;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDateTime;

/**
 * <p> * * </p> * * @author RonnieXu * @since 2019-12-19 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("sys_wx_user") @ApiModel(value="微信對象", description="微信對象") public class WxUser extends BaseEntity<WxUser> { private static final long serialVersionUID = 1L; @ApiModelProperty(value="用戶的標識,對當前公眾號唯一") private String openid; @ApiModelProperty(value="用戶的昵稱") private String nickname; @ApiModelProperty(value="用戶的性別,值為1時是男性,值為2時是女性,值為0時是未知") private Integer sex; @ApiModelProperty(value="用戶所在城市") private String city; @ApiModelProperty(value="用戶所在國家") private String country; @ApiModelProperty(value="用戶頭像,最后一個數值代表正方形頭像大小(有0、46、64、96、132數值可選," + "0代表640*640正方形頭像),用戶沒有頭像時該項為空。若用戶更換頭像,原有頭像URL將失效。") private String headimgurl; @ApiModelProperty(value="用戶所在省份") private String province; @ApiModelProperty(value="用戶的語言,簡體中文為zh_CN") private String language; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @TableField(value = "subscribe_time") @ApiModelProperty(value="用戶關注時間,為時間戳。如果用戶曾多次關注,則取最后關注時間") private LocalDateTime subscribe_time; @ApiModelProperty(value="只有在用戶將公眾號綁定到微信開放平台帳號后,才會出現該字段") private String unionid; @ApiModelProperty(value="公眾號運營者對粉絲的備注,公眾號運營者可在微信公眾平台用戶管理界面對粉絲添加備注") private String remark; @ApiModelProperty(value="用戶所在的分組ID(兼容舊的用戶分組接口)") private String groupid; @TableField(value = "tagid_list") @ApiModelProperty(value="用戶被打上的標簽ID列表") private String tagid_list; /** * 返回用戶關注的渠道來源, * ADD_SCENE_SEARCH 公眾號搜索,ADD_SCENE_ACCOUNT_MIGRATION * 公眾號遷移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 掃描二維碼, * ADD_SCENE_PROFILE_ LINK 圖文頁內名稱點擊,ADD_SCENE_PROFILE_ITEM 圖文頁右上角菜單, * ADD_SCENE_PAID 支付后關注,ADD_SCENE_OTHERS 其他 */ @TableField(value = "subscribe_scene") @ApiModelProperty(value="返回用戶關注的渠道來源") private String subscribe_scene; @TableField(value = "qr_scene") @ApiModelProperty(value="二維碼掃碼場景(開發者自定義)") private String qr_scene; @TableField(value = "qr_scene_str") @ApiModelProperty(value="二維碼掃碼場景描述(開發者自定義)") private String qr_scene_str; } 

定義一個component
WeiXinUserUtil.java
package com.xu.wemall.components.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.commons.constants.URIConstant;
import com.xu.wemall.entry.WxUser;
import com.xu.wemall.pojo.menu.Button;
import com.xu.wemall.pojo.menu.ComplexButton;
import com.xu.wemall.pojo.menu.Menu;
import com.xu.wemall.pojo.menu.ViewButton;
import com.xu.wemall.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class WeiXinUserUtil {

    @Autowired
    private IWxUserService iWxUserService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    public JSONObject handdleWeixinUserInfo(String openId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null){
            log.info("URL{}",URIConstant.OPENID_USERINFO_URL);
            String url = URIConstant.OPENID_USERINFO_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("OPENID",openId);
            log.info("OPENID_USERINFO_URL:{}",url);

            //發起POST請求創建菜單
            JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class);

            //表示訂閱了該公眾號
            if(jsonObject.getIntValue("subscribe") == 1){
                //保存
                WxUser wxUser = JSONObject.parseObject(jsonObject.toJSONString(),WxUser.class);
                boolean result = iWxUserService.saveOrUpdate(wxUser);
            }

            return jsonObject;
        }
        return null;
    }

}

最后看看我們的controller中代碼,如果我們調用成功就可以獲取到用戶的相關信息,我們就持續化到自己數據庫

WeiXinController.java
package com.xu.wemall.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.commons.utils.CheckUtil;
import com.xu.wemall.commons.utils.UploadUtil;
import com.xu.wemall.components.weixin.MessageUtil;
import com.xu.wemall.components.weixin.WeiXinUserUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 類名稱: LoginController
 * 類描述: 與微信對接登陸驗證
 *
 * @author yuanjun
 * 創建時間:2017年12月5日上午10:52:13
 */
@Slf4j
@RestController
@Api(tags = "接入驗證接口")
@RequestMapping(value = "/weChart")
public class WeiXinController {

    @Autowired
    private WeiXinUserUtil weiXinUserUtil;

    @Autowired
    private UploadUtil uploadUtil;

    @Autowired
    private MessageUtil messageUtil;

    @RequestMapping(value = "/connect", method = RequestMethod.GET)
    public String connect(@RequestParam(value = "signature") String signature,
                          @RequestParam(value = "timestamp") String timestamp,
                          @RequestParam(value = "nonce") String nonce,
                          @RequestParam(value = "echostr") String echostr) {

        log.info("-----開始校驗簽名-----");
        PrintWriter out = null;
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            log.info("-----簽名校驗通過-----");
            return echostr;
        } else {
            log.info("-----校驗簽名失敗-----");
            return null;
        }

    }

    @RequestMapping(value = "connect", method = RequestMethod.POST)
    public String dopost(HttpServletRequest request, HttpServletResponse response) throws Exception {

        response.setCharacterEncoding("utf-8");

        //將微信請求xml轉為map格式,獲取所需的參數
        Map<String, String> map = MessageUtil.parseXml(request); String ToUserName = map.get("ToUserName"); String FromUserName = map.get("FromUserName"); String MsgType = map.get("MsgType"); String Content = map.get("Content"); String Event = map.get("Event"); if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(MsgType)){ if(MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(Event)){ String xmlString = messageUtil.subscribeForText(ToUserName,FromUserName); //關注了公眾號,調用接口獲得用戶的詳細信息並保存到后台 JSONObject jsonObject = weiXinUserUtil.handdleWeixinUserInfo(FromUserName); log.info("獲取用戶的詳細信息:{}",jsonObject.toJSONString()); return xmlString; }else if(MessageUtil.EVENT_TYPE_UNSUBSCRIBE.equals(Event)){ String xmlString = messageUtil.unsubscribeForText(ToUserName,FromUserName); return xmlString; } } //處理文本類型,實現輸入1,回復相應的封裝的內容 if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(MsgType)) { String xmlString = messageUtil.replyForText(ToUserName,FromUserName,"你發送的是:" + Content); log.info(xmlString); return xmlString; } if (MessageUtil.REQ_MESSAGE_TYPE_IMAGE.equals(MsgType)) { String filePath = "C:\\Users\\RonnieXu\\Pictures\\2.jpg"; String xmlString = messageUtil.replyForImage(ToUserName,FromUserName,filePath); return xmlString; } return null; } } 

當有用戶關注該公眾號的時候,我們就能利用接口獲取用戶信息了,

獲取用戶的信息就到這里了,其他相關的內容請參考微信公眾號開發文檔獲取更多的內容,謝謝各位客官捧場。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM