


The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.
Jul 25, 2018 pm 03:04 PMMany of today’s activities guide users to follow public accounts in order to participate in activities. How to judge whether users have followed public accounts is actually very simple. Follow this article and you will no longer have to worry. The php code in this article is very simple. Explained in detail.
1. WeChat public platform configuration
1. Obtain appid, appsecret, add whitelist
Log in to WeChat public platform and enter basic configuration. Two parameters need to be used in development, appId and appSecret (appSecret is only displayed once and needs to be saved, otherwise it needs to be reset and obtained).
You need to add an IP whitelist when obtaining access_token.
Click to view
Click to modify
2. Add web page authorization
Enter the official account settings=》Function settings=》Web page authorized domain nameClick settings, enter the domain name of the authorization callback page in the input box, refer to point 1 (only one can be filled in), download the txt in point 3 Documents are uploaded to the root directory of the server.
2. PHP backend implementation
1. Obtain global token
This token is valid for 2 hours and can be temporarily stored. It is required after expiration Reacquire.
PS: The project must use the same interface, otherwise it will easily lead to expiration due to mutual brushing.
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); } 正確返回結(jié)果: { "access_token": "ACCESS_TOKEN", "expires_in": 7200 } 返回結(jié)果參數(shù)說明: 參數(shù) 說明 access_token 獲取到的全局token expires_in 憑證有效時(shí)間,單位:秒 錯(cuò)誤返回結(jié)果: {"errcode": 40013, "errmsg": "invalid appid"} 返回結(jié)果參數(shù)說明: 返回碼 說明 -1 系統(tǒng)繁忙,此時(shí)請(qǐng)開發(fā)者稍候再試 0 請(qǐng)求成功 40001 AppSecret錯(cuò)誤或者AppSecret不屬于這個(gè)公眾號(hào),請(qǐng)開發(fā)者確認(rèn) AppSecret的正確性 40002 請(qǐng)確保grant_type字段值為client_credential 40164 調(diào)用接口的IP地址不在白名單中,請(qǐng)?jiān)诮涌贗P白名單中進(jìn)行設(shè)置。(小程序及小游戲調(diào)用不要求IP地址在白名單內(nèi)。)
2. Obtaining the openid of the public account associated with the user
is a two-step process. First, obtain the user's authorization code for the public account, and then use this code to obtain the temporary access_token and openid.
Get user authorization code
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); } 正確返回結(jié)果: 返回code碼,并且跳轉(zhuǎn)回調(diào)頁面$redirect_uri 錯(cuò)誤返回結(jié)果: {"errcode": 10003, "errmsg": "redirect_uri域名與后臺(tái)配置不一致"} 返回結(jié)果參數(shù)說明: 返回碼 說明 10003 redirect_uri域名與后臺(tái)配置不一致 10004 此公眾號(hào)被封禁 10005 此公眾號(hào)并沒有這些scope的權(quán)限 10006 必須關(guān)注此測(cè)試號(hào) 10009 操作太頻繁了,請(qǐng)稍后重試 10010 scope不能為空 10011 redirect_uri不能為空 10012 appid不能為空 10013 state不能為空 10015 公眾號(hào)未授權(quán)第三方平臺(tái),請(qǐng)檢查授權(quán)狀態(tài) 10016 不支持微信開放平臺(tái)的Appid,請(qǐng)使用公眾號(hào)Appid
The code obtained through getCode is exchanged for the access_token and openid authorized by the webpage
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); } 正確返回結(jié)果: { "access_token": "ACCESS_TOKEN", "expires_in": 7200, "refresh_token": "REFRESH_TOKEN", "openid": "OPENID", "scope": "SCOPE" } 返回參數(shù)說明 參數(shù) 描述 access_token 網(wǎng)頁授權(quán)接口調(diào)用憑證,注意:此access_token與基礎(chǔ)支持的access_token不同 expires_in access_token接口調(diào)用憑證超時(shí)時(shí)間,單位(秒) refresh_token 用戶刷新access_token openid 用戶唯一標(biāo)識(shí),請(qǐng)注意,在未關(guān)注公眾號(hào)時(shí),用戶訪問公眾號(hào)的網(wǎng)頁,也會(huì)產(chǎn)生一個(gè)用戶和公眾號(hào)唯一的OpenID scope 用戶授權(quán)的作用域,使用逗號(hào)(,)分隔 錯(cuò)誤返回結(jié)果: {"errcode":40029, "errmsg":"invalid code"}
3. Obtain user information
Use the first Use the openId obtained in step 2 and the token obtained in step 1 to obtain user information
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'); } 正確返回結(jié)果: { "subscribe": 1, "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", "nickname": "Band", "sex": 1, "language": "zh_CN", "city": "廣州", "province": "廣東", "country": "中國(guó)", "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": "" } 返回參數(shù)說明: 參數(shù) 說明 subscribe 用戶是否訂閱該公眾號(hào)標(biāo)識(shí),值為0時(shí),代表此用戶沒有關(guān)注該公眾號(hào),拉取不到其余信息。 openid 用戶的標(biāo)識(shí),對(duì)當(dāng)前公眾號(hào)唯一 nickname 用戶的昵稱 sex 用戶的性別,值為1時(shí)是男性,值為2時(shí)是女性,值為0時(shí)是未知 city 用戶所在城市 country 用戶所在國(guó)家 province 用戶所在省份 language 用戶的語言,簡(jiǎn)體中文為zh_CN headimgurl 用戶頭像,最后一個(gè)數(shù)值代表正方形頭像大小(有0、46、64、96、132數(shù)值可選,0代表640*640正方形頭像),用戶沒有頭像時(shí)該項(xiàng)為空。若用戶更換頭像,原有頭像URL將失效。 subscribe_time 用戶關(guān)注時(shí)間,為時(shí)間戳。如果用戶曾多次關(guān)注,則取最后關(guān)注時(shí)間 unionid 只有在用戶將公眾號(hào)綁定到微信開放平臺(tái)帳號(hào)后,才會(huì)出現(xiàn)該字段。 remark 公眾號(hào)運(yùn)營(yíng)者對(duì)粉絲的備注,公眾號(hào)運(yùn)營(yíng)者可在微信公眾平臺(tái)用戶管理界面對(duì)粉絲添加備注 groupid 用戶所在的分組ID(兼容舊的用戶分組接口) tagid_list 用戶被打上的標(biāo)簽ID列表 subscribe_scene 返回用戶關(guān)注的渠道來源,ADD_SCENE_SEARCH 公眾號(hào)搜索,ADD_SCENE_ACCOUNT_MIGRATION 公眾號(hào)遷移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 掃描二維碼,ADD_SCENEPROFILE LINK 圖文頁內(nèi)名稱點(diǎn)擊,ADD_SCENE_PROFILE_ITEM 圖文頁右上角菜單,ADD_SCENE_PAID 支付后關(guān)注,ADD_SCENE_OTHERS 其他 qr_scene 二維碼掃碼場(chǎng)景(開發(fā)者自定義) qr_scene_str 二維碼掃碼場(chǎng)景描述(開發(fā)者自定義) 錯(cuò)誤結(jié)果: {"errcode":40013,"errmsg":"invalid appid"}
3. Use
to determine whether you have followed it. Here is the entrance:
public function isConcern($appId, $appSecret) { $param = ''; // 如果有參數(shù) $this->getCode($appId, U('callback', 'param='.$param), 1 ,'snsapi_base'); }
Callback after authorization
public function callback(){ $isconcern = 0; $code = $this->_get('code'); $param = $this->_get('param'); $appId = C('appId'); // config中配置 $appSecret = C('appSecret'); $accessTokenInfo = $this->getAccessToken($code, $appId, $appSecret); $openId = $accessTokenInfo['openid']; $accessToken = $accessTokenInfo['access_token']; $token = $this->getToken($appId, $appSecret); $userInfo = $this->getUserInfo($openId, $token['access_token']); if($userInfo['subscribe'] == 1){ $this->assign('userInfo', $userInfo); $isconcern = 1; // 已關(guān)注 } else { $isconcern = 0; // 未關(guān)注 } $this->assign('openid', $openId); $this->display('page'); }
At this time, userInfo and isconcern can be obtained on the page. When isconcern is 1, it means that the official account has been followed, otherwise it has not been followed.
Related recommendations:
Video: Following and canceling the public account-0 Introduction to basic WeChat development
The above is the detailed content of The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

Yes, but there are restrictions. ① You can log in to the same account on both iPhone and Android phones, but logging in to the latest device will cause the earliest session to be offline; ② You can log in at the same time on the mobile phone and the computer desktop, but the functions are not synchronized; ③ Although using third-party tools or dual-app functions can enable logging in between two mobile phones, it is unofficially supported and may violate regulations; ④ Alternative solutions include using web version/desktop version to match the main phone, or transferring chat records through cloud backup and file tools. Some Android machines can also use "dual applications" to run two account instances.

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors
