判断用户是否已关注公众号
生活随笔
收集整理的這篇文章主要介紹了
判断用户是否已关注公众号
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
業務場景是:判斷當前登錄用戶是否已經關注指定的官方微信公眾號,沒有就指引用戶關注。
微信公眾號官方文檔:https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
詳細步驟
一.公眾號后臺配置
登錄微信公眾平臺,進入基本配置。開發中需要用到兩個參數,appId和appSecret(appSecret只展示一次,需保存下來,否則需要重置獲取)。獲取access_token時需要添加IP白名單。
二.后臺實現思路
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
在關注者與公眾號產生消息交互后,公眾號可獲得關注者的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 |
https請求方式: GET
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
返回說明
正常情況下,微信會返回下述JSON數據包給公眾號:
詳情查看官方文檔-獲取用戶基本信息 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;}總結
以上是生活随笔為你收集整理的判断用户是否已关注公众号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 木兰花
- 下一篇: 荧光染料 ICG-HSA 吲哚菁绿修饰人