Table of Contents
1. WeChat public platform configuration
1. Obtain appid, appsecret, add whitelist
2. Add web page authorization
2. PHP backend implementation
1. Obtain global token
2. Obtaining the openid of the public account associated with the user
3. Obtain user information
3. Use
Home WeChat Applet WeChat Development The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.

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 PM
javascript php No public focus on WeChat

Many 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.
The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.

Click to view

The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.
Click to modify
The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.

2. Add web page authorization

Enter the official account settings=》Function settings=》Web page authorized domain name
The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.Click 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.
The code is still easy to use, and you can determine whether the user has followed the official account in just a few steps.

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);
}

正确返回结果:
    {
        "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地址在白名单内。)
Copy after login

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);
}

正确返回结果:
    返回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
Copy after login

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);
}
   
正确返回结果:
    { 
        "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"}
Copy after login

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');
}
正确返回结果:
    {
        "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"}
Copy after login

3. Use

to determine whether you have followed it. Here is the entrance:

public function isConcern($appId, $appSecret) {
    $param = ''; // 如果有参数
    $this->getCode($appId, U('callback', 'param='.$param), 1 ,'snsapi_base');
}
Copy after login

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; // 已关注
    } else {
        $isconcern = 0; // 未关注
    }
    $this->assign('openid', $openId);
    $this->display('page');
}
Copy after login

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:

WeChat public account development WeChat public account determines whether the user has paid attention to php code analysis

PHP determines the character type php Determine whether the user is following the WeChat public account

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles