计算机网络/计算机科学与应用/系统/运维/开发

Thinkphp5.1 获取关注服务号用户的openid

获取关注服务号的用户的openid ,一般用于查找openid用来发送消息模版


<?php
namespace app\index\controller;
use think\Controller;
class Test extends Controller
{
    // 直接写死在这里,不用配置文件!这里是服务号的
    protected $appId = 'wx002f60583b2b4ccc';
    protected $appSecret = '892f79805bed29b4ce2c9a67523b3ad1';
    // 获取 access_token
    private function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($curl);
        curl_close($curl);
        return json_decode($result, true);
    }
    // 获取关注用户的 openid(你要的功能)
    public function getUsers()
    {
        echo "开始获取关注用户OpenID...<br><br>";
        // 1. 获取token
        $tokenRes = $this->getAccessToken();
        if (!isset($tokenRes['access_token'])) {
            echo "错误:";
            dump($tokenRes);
            exit;
        }
        $accessToken = $tokenRes['access_token'];
        // 2. 获取关注列表
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$accessToken;
        $res = file_get_contents($url);
        $res = json_decode($res, true);
        // 3. 输出你要的 OPENID
        echo "===== 关注用户 OpenID 列表 =====<br>";
        if(isset($res['data']['openid'])){
            foreach($res['data']['openid'] as $openid){
                echo $openid . "<br>";
            }
        }else{
            echo "获取失败:";
            dump($res);
        }
    }
}


知识是抵御一切灾祸的盾牌

评论

^