


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 憑證有效時間,單位:秒 錯誤返回結(jié)果: {"errcode": 40013, "errmsg": "invalid appid"} 返回結(jié)果參數(shù)說明: 返回碼 說明 -1 系統(tǒng)繁忙,此時請開發(fā)者稍候再試 0 請求成功 40001 AppSecret錯誤或者AppSecret不屬于這個公眾號,請開發(fā)者確認 AppSecret的正確性 40002 請確保grant_type字段值為client_credential 40164 調(diào)用接口的IP地址不在白名單中,請在接口IP白名單中進行設(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 錯誤返回結(jié)果: {"errcode": 10003, "errmsg": "redirect_uri域名與后臺配置不一致"} 返回結(jié)果參數(shù)說明: 返回碼 說明 10003 redirect_uri域名與后臺配置不一致 10004 此公眾號被封禁 10005 此公眾號并沒有這些scope的權(quán)限 10006 必須關(guān)注此測試號 10009 操作太頻繁了,請稍后重試 10010 scope不能為空 10011 redirect_uri不能為空 10012 appid不能為空 10013 state不能為空 10015 公眾號未授權(quán)第三方平臺,請檢查授權(quán)狀態(tài) 10016 不支持微信開放平臺的Appid,請使用公眾號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)用憑證超時時間,單位(秒) refresh_token 用戶刷新access_token openid 用戶唯一標(biāo)識,請注意,在未關(guān)注公眾號時,用戶訪問公眾號的網(wǎng)頁,也會產(chǎn)生一個用戶和公眾號唯一的OpenID scope 用戶授權(quán)的作用域,使用逗號(,)分隔 錯誤返回結(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": "中國", "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 用戶是否訂閱該公眾號標(biāo)識,值為0時,代表此用戶沒有關(guān)注該公眾號,拉取不到其余信息。 openid 用戶的標(biāo)識,對當(dāng)前公眾號唯一 nickname 用戶的昵稱 sex 用戶的性別,值為1時是男性,值為2時是女性,值為0時是未知 city 用戶所在城市 country 用戶所在國家 province 用戶所在省份 language 用戶的語言,簡體中文為zh_CN headimgurl 用戶頭像,最后一個數(shù)值代表正方形頭像大?。ㄓ?、46、64、96、132數(shù)值可選,0代表640*640正方形頭像),用戶沒有頭像時該項為空。若用戶更換頭像,原有頭像URL將失效。 subscribe_time 用戶關(guān)注時間,為時間戳。如果用戶曾多次關(guān)注,則取最后關(guān)注時間 unionid 只有在用戶將公眾號綁定到微信開放平臺帳號后,才會出現(xiàn)該字段。 remark 公眾號運營者對粉絲的備注,公眾號運營者可在微信公眾平臺用戶管理界面對粉絲添加備注 groupid 用戶所在的分組ID(兼容舊的用戶分組接口) tagid_list 用戶被打上的標(biāo)簽ID列表 subscribe_scene 返回用戶關(guān)注的渠道來源,ADD_SCENE_SEARCH 公眾號搜索,ADD_SCENE_ACCOUNT_MIGRATION 公眾號遷移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 掃描二維碼,ADD_SCENEPROFILE LINK 圖文頁內(nèi)名稱點擊,ADD_SCENE_PROFILE_ITEM 圖文頁右上角菜單,ADD_SCENE_PAID 支付后關(guān)注,ADD_SCENE_OTHERS 其他 qr_scene 二維碼掃碼場景(開發(fā)者自定義) qr_scene_str 二維碼掃碼場景描述(開發(fā)者自定義) 錯誤結(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)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.
