PHP获取QQ昵称和头像API

2 min read

返回数据

{
  "code": 200,
  "msg": "success",
  "data": {
    "qq": "123456",
    "name": "腾讯视频",
    "img": "https://q1.qlogo.cn/g?b=qq&k=ib0ts0Uexd5Rcic68bVuREwg&kti=Y7bM6AAAAAI&s=140",
    "mail": "123456@qq.com"
  }
}

接口源码

<?php
// title: 获取QQ昵称和头像API
// update: 2024-05-03
// author: iami233
header('Access-Control-Allow-Origin:*');
header('Content-type: application/json');

header('content-type: application/json;charset=utf8');

$qq = $_REQUEST['qq'] ?? null;
if (!$qq || !is_numeric($qq)) {
    sendResponse(201, '参数错误');
    exit;
}

// 从QQ空间获取 Cookie 即可,分别填入uin、skey、p_skey
$uin = '';
$skey = '';
$p_skey = '';
$cookie = "uin=$uin;skey=$skey;p_skey=$p_skey;";

$url = 'https://r.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?g_tk=' . getbkn($skey) . '&uins=' . $qq;
$response = getCurl($url, ["Cookie: $cookie"]);

$data = json_decode(substr(mb_convert_encoding($response, "UTF-8", "GBK"), 17, -1), true);

if ($data) {
    $server = rand(1, 4);
    $txUrl = "https://q$server.qlogo.cn/headimg_dl?dst_uin=$qq&spec=640";
    $json = [
        'code' => 200,
        "msg" => "success",
        "data" => [
            'qq' => $qq,
            'name' => $data[$qq][6],
            "img" => $txUrl,
            'mail' => $qq.'@qq.com',
        ]
    ];
    sendResponse(200, 'success', $json['data']);
} else {
    sendResponse(201, '接口错误,请联系管理员');
}

function getbkn($skey) {
    $hash = 5381;
    $len = strlen($skey);
    for ($i = 0; $i < $len; $i++) {
        $hash += ($hash << 5) + ord($skey[$i]);
    }
    return $hash & 0x7FFFFFFF;
}

function getCurl($url, $header = []) {
    $con = curl_init($url);
    curl_setopt_array($con, [
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_TIMEOUT => 5000
    ]);
    $result = curl_exec($con);
    curl_close($con);
    return $result;
}

function sendResponse($code, $msg, $data = null) {
    $response = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    echo json_encode($response, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
    exit;
}