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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

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.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Explain strict types (declare(strict_types=1);) in PHP. Explain strict types (declare(strict_types=1);) in PHP. Apr 07, 2025 am 12:05 AM

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values ​​to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

See all articles