微信公衆號,判斷當前用戶是否關注了該公衆號

一、微信公衆平臺配置

參考文章:https://segmentfault.com/a/1190000015268145

1. 獲取appid, appsecret,添加白名單

登錄微信公衆平臺,進入基本配置。開發中需要用到兩個參數,appId和appSecret(appSecret只展示一次,需保存下來,否則需要重置獲取)。
獲取access_token時需要添加IP白名單。
 

2. 添加網頁授權

進入公衆號設置=》功能設置=》網頁授權域名

點擊設置,input框中輸入授權回調頁的域名參考第1點(只能填寫一個),下載第3點中的txt文檔,上傳至服務器的根目錄。

二、php後端實現

微信開放接口全局返回碼說明參考:https://mp.weixin.qq.com/wiki...

1. 獲取全局token

此token有效期爲2小時,可以暫存起來,過期後需要重新獲取。
PS: 項目中必須走同一個接口,否則容易互刷導致過期。

public static function getToken($appid, $appsecret){
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
    return Curl::callWebServer($url);
}
 
正確返回結果:
    {
        "access_token": "ACCESS_TOKEN",
        "expires_in": 7200
    }
    返回結果參數說明:
    參數              說明
    access_token      獲取到的全局token
    expires_in        憑證有效時間,單位:秒
    
錯誤返回結果:
    {"errcode": 40013, "errmsg": "invalid appid"}
    返回結果參數說明:
    返回碼    說明
    -1       系統繁忙,此時請開發者稍候再試
    0        請求成功
    40001    AppSecret錯誤或者AppSecret不屬於這個公衆號,請開發者確認        AppSecret的正確性
    40002    請確保grant_type字段值爲client_credential
    40164    調用接口的IP地址不在白名單中,請在接口IP白名單中進行設置。(小程序及小遊戲調用不要求IP地址在白名單內。)

2. 獲取用戶關聯公衆號的openid

分兩步,先要獲取到用戶對公衆號的授權碼,然後拿這個碼去獲取臨時access_token和openid。

獲取用戶授權碼

public static function getCode($appId, $redirect_uri, $state=1, $scope='snsapi_base', $response_type='code'){
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.$redirect_uri.'&response_type='.$response_type.'&scope='.$scope.'&state='.$state.'#wechat_redirect';
    header('Location: '.$url, true, 301);
}
 
正確返回結果:
    返回code碼,並且跳轉回調頁面$redirect_uri
    
錯誤返回結果:
    {"errcode": 10003, "errmsg": "redirect_uri域名與後臺配置不一致"}
    返回結果參數說明:
    返回碼    說明
    10003    redirect_uri域名與後臺配置不一致
    10004    此公衆號被封禁
    10005    此公衆號並沒有這些scope的權限
    10006    必須關注此測試號
    10009    操作太頻繁了,請稍後重試
    10010    scope不能爲空
    10011    redirect_uri不能爲空
    10012    appid不能爲空
    10013    state不能爲空
    10015    公衆號未授權第三方平臺,請檢查授權狀態
    10016    不支持微信開放平臺的Appid,請使用公衆號Appid

通過getCode獲取到的code換取網頁授權的access_token和openid

public static function getAccessToken($code, $appid, $appsecret, $grant_type='authorization_code'){
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type='.$grant_type.'';
    return Curl::callWebServer($url);
}
   
正確返回結果:
    { 
        "access_token": "ACCESS_TOKEN",
        "expires_in": 7200,
        "refresh_token": "REFRESH_TOKEN",
        "openid": "OPENID",
        "scope": "SCOPE"
    }
    返回參數說明
    參數            描述
    access_token    網頁授權接口調用憑證,注意:此access_token與基礎支持的access_token不同
    expires_in    access_token接口調用憑證超時時間,單位(秒)
    refresh_token    用戶刷新access_token
    openid    用戶唯一標識,請注意,在未關注公衆號時,用戶訪問公衆號的網頁,也會產生一個用戶和公衆號唯一的OpenID
    scope    用戶授權的作用域,使用逗號(,)分隔
    
錯誤返回結果:
    {"errcode":40029, "errmsg":"invalid code"}

3. 獲取用戶信息

使用第2步中獲取的openId和第1步中獲取的token去獲取用戶信息

public static function getUserInfo($openId, $token){
    $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token.'&openid='.$openId.'&lang=zh_CN';
    return Curl::callWebServer($queryUrl, '', 'GET');
}
正確返回結果:
    {
        "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_SCENEPROFILE LINK 圖文頁內名稱點擊,ADD_SCENE_PROFILE_ITEM 圖文頁右上角菜單,ADD_SCENE_PAID 支付後關注,ADD_SCENE_OTHERS 其他
        qr_scene        二維碼掃碼場景(開發者自定義)
        qr_scene_str    二維碼掃碼場景描述(開發者自定義)
 
錯誤結果:
    {"errcode":40013,"errmsg":"invalid appid"}

示例:

/**
	 * 微信公衆號網頁授權,通過掃描充電樁二維碼
	 */
	@RequestMapping(value = "/oauth")
	public void wechatOAuth2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 微信授權回調URL
		String url = request.getScheme() + "://" + request.getServerName() + request.getContextPath()
				+ "/getOAuthUserInfo";
		// 獲取重定向URL
		String wxUrl = this.wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
		// 重定向網頁授權頁面
		response.sendRedirect(wxUrl);
	}

	/**
	 * 通過code獲得基本用戶信息 詳情請見:
	 * http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html
	 *
	 * @param code
	 *            code
	 * @param lang
	 *            zh_CN, zh_TW, en
	 */
	@RequestMapping(value = "/getOAuthUserInfo")
	public void getOAuthUserInfo(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "code") String code) throws Exception {
		try {
			WxMpOAuth2AccessToken accessToken = this.wxMpService.oauth2getAccessToken(code);
			WxMpUser wxMpUser = this.wxMpService.getUserService().userInfo(accessToken.getOpenId());
			// 將用戶信息存入session
			request.getSession().setAttribute(GlobalDeclare.USER_WX_INFO, wxMpUser);
			// 判斷用戶是否關注該公衆號
			if(wxMpUser.getSubscribe()){
				response.sendRedirect(request.getContextPath() + "/jsp/info.html");
			}else{
				response.sendRedirect(request.getContextPath() + "/jsp/qrcode.html");
			}	
		} catch (WxErrorException e) {
			this.logger.error(e.getError().toString());
			response.sendRedirect(request.getContextPath() + "/jsp/qrcode.html");
		}
		// response.sendRedirect(request.getContextPath() + "/jsp/info.html");
	}

完!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章