判断用户是否已关注公众号

背景
业务场景是:判断当前登录用户是否已经关注指定的官方微信公众号,没有就指引用户关注。

微信公众号官方文档:https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html

详细步骤

一.公众号后台配置

  1. 获取appid, appsecret,添加白名单
    登录微信公众平台,进入基本配置。开发中需要用到两个参数,appId和appSecret(appSecret只展示一次,需保存下来,否则需要重置获取)。获取access_token时需要添加IP白名单。
  2. 添加网页授权

二.后台实现思路

  1. 获取公众号的access_token
    https请求方式: GET
    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
参数 说明
grant_type $ 获取access_token填写client_credential
appid 第三方用户唯一凭证
secret 第三方用户唯一凭证密钥,即appsecret

返回说明
正常情况下,微信会返回下述JSON数据包给公众号:
{“access_token”:“ACCESS_TOKEN”,“expires_in”:7200}

参数说明

参数 说明
access_token 获取到的凭证
expires_in 凭证有效时间,单位:秒

错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):
{“errcode”:40013,“errmsg”:“invalid appid”}

返回错误码参考官方文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

  1. 获取用户的openid
    在关注者与公众号产生消息交互后,公众号可获得关注者的OpenID(说明:OpenID就是加密后的微信号,每个用户对每个公众号的OpenID是唯一的。对于不同公众号,同一用户的openid不同)。
    用户同意授权,获取code通过code来获取openid
    https请求方式: GET
    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
参数 说明
appid 第三方用户唯一凭证
secret 第三方用户唯一凭证密钥,即appsecret
code code
grant_type authorization_code
  1. 根据前两个步骤获得的信息(access_token和openId),调用微信接口获取用户基本信息
    https请求方式: GET
    https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

返回说明
正常情况下,微信会返回下述JSON数据包给公众号:

  {
    
    
        "subscribe": 1, 
        "openid": "xxxxxx", 
        "nickname": "Band", 
        "sex": 1, 
        "language": "zh_CN", 
        "city": "深圳", 
        "province": "广东", 
        "country": "中国",   "headimgurl":"",
        "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      用户头像,最后一个数值代表正方形头像大小(有0466496132数值可选,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_SCENEPROFILE LINK 图文页内名称点击,ADD_SCENE_PROFILE_ITEM 图文页右上角菜单,ADD_SCENE_PAID 支付后关注,ADD_SCENE_OTHERS 其他
        qr_scene        二维码扫码场景(开发者自定义)
        qr_scene_str    二维码扫码场景描述(开发者自定义)
 
错误结果:
    {
    
    "errcode":40013,"errmsg":"invalid appid"}

详情查看官方文档-获取用户基本信息 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839

三.java后台实现

获取openid参考:

实体
@Data
public class WeiXinOauth2Token {
    
    
	private String accessToken;
	private int expiresIn;
	private String refeshToken;
	private String openId;
	private String scope;
}

String userListUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
/**
	 * 通过网页授权code获取微信openid
	 * @param appId
	 * @param appSecret
	 * @param code
	 * @return
	 */
	public static WeiXinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
    
    
        WeiXinOauth2Token wat = new WeiXinOauth2Token();
        String requestUrl = oauth2WebUrl.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
    
    
                try {
    
    
                        wat = new WeiXinOauth2Token();
                        wat.setAccessToken(jsonObject.getString("access_token"));
                        wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                        wat.setRefeshToken(jsonObject.getString("refresh_token"));
                        wat.setOpenId(jsonObject.getString("openid"));
                        wat.setScope(jsonObject.getString("scope"));
                } catch (Exception e) {
    
    
                        wat = null;
                        String errorCode = jsonObject.getString("errcode");
                        String errorMsg = jsonObject.getString("errmsg");
                        log.error("获取网页授权凭证失败 errcode:"+errorCode+",errMsg:"+errorMsg);
                }

        }
        return wat;
	}

工具类
/**
     * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
    
    
            JSONObject jsonObject = null;
            try {
    
    
                    // 创建SSLContext对象,并使用我们指定的信任管理器初始化
                    TrustManager[] tm = {
    
     new MyX509TrustManager() };
                    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                    sslContext.init(null, tm, new java.security.SecureRandom());
                    // 从上述SSLContext对象中得到SSLSocketFactory对象
                    SSLSocketFactory ssf = sslContext.getSocketFactory();
                    URL url = new URL(requestUrl);
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setSSLSocketFactory(ssf);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    // 设置请求方式(GET/POST)
                    conn.setRequestMethod(requestMethod);
                    //conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
                    // 当outputStr不为null时向输出流写数据
                    if (null != outputStr) {
    
    
                            OutputStream outputStream = conn.getOutputStream();
                            // 注意编码格式
                            outputStream.write(outputStr.getBytes("UTF-8"));
                            outputStream.close();
                    }
                    // 从输入流读取返回内容
                    InputStream inputStream = conn.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String str = null;
                    StringBuffer buffer = new StringBuffer();
                    while ((str = bufferedReader.readLine()) != null) {
    
    
                            buffer.append(str);
                    }
                    // 释放资源
                    bufferedReader.close();
                    inputStreamReader.close();
                    inputStream.close();
                    inputStream = null;
                    conn.disconnect();
                    jsonObject = JSONObject.parseObject(buffer.toString());
            } catch (ConnectException ce) {
    
    
                    log.error("连接超时:{}", ce);
            } catch (Exception e) {
    
    
                    log.error("https请求异常:{}", e);
            }
            return jsonObject;
	}

猜你喜欢

转载自blog.csdn.net/m0_46269902/article/details/106660974