首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 與 JavaScript 判斷微信內置瀏覽器:User-Agent 特徵與實戰代碼

     編輯:PHP 綜合知識

微信開發常需識別請求是否來自微信內置瀏覽器,以調用 JSSDK、授權登錄或阻止非法訪問。核心在於檢測 User-Agent 中的 MicroMessenger 標識。

User-Agent 特徵分析

平台User-Agent 片段
iOSMozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 ... MicroMessenger/4.3.2
AndroidMozilla/5.0 (Linux; U; Android 2.3.6; zh-cn; GT-S5660 Build/GINGERBREAD) AppleWebKit/533.1 ... MicroMessenger/4.5.255

關鍵特徵:包含 "MicroMessenger" 字符串及版本號,可同時判斷設備類型(iPhone/Android)。

PHP 端判斷

function isWeixin() {
    if (empty($_SERVER['HTTP_USER_AGENT'])) return false;
    return stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
}

// 使用示例
if (isWeixin()) {
    // 微信環境:可調用 JSSDK、靜默授權等
    $appId = 'your_appid';
    $redirectUrl = urlencode('https://yourdomain.com/callback');
    $scope = 'snsapi_userinfo'; // 或 snsapi_base
    $authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirectUrl&response_type=code&scope=$scope&state=STATE#wechat_redirect";
    header("Location: $authUrl");
    exit;
} else {
    // 非微信環境:引導用戶在微信中打開
    echo '請在微信中打開此鏈接。';
    // 或返回 401
    // header('HTTP/1.1 401 Unauthorized');
}

JavaScript 端判斷

function isWeixin() {
    var ua = navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == 'micromessenger';
}

// 頁面加載時判斷
if (isWeixin()) {
    // 隱藏「請在微信中打開」提示層
    document.getElementById('non-weixin-tips').style.display = 'none';
    // 初始化 JSSDK 配置
    wx.config({ /* ... */ });
} else {
    document.getElementById('non-weixin-tips').style.display = 'block';
}

完整業務流程:獲取用戶基本信息(OAuth2 授權碼模式)

  1. 配置授權回調域:公眾平台 → 開發者中心 → 網頁授權獲取用戶基本信息 → 修改回調域。
  2. 引導授權獲取 code:
    $authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=" . urlencode($callback) . "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
    header("Location: $authUrl");
  3. 回調頁面換取 access_token & openid:
    $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
    $token = json_decode(file_get_contents($tokenUrl), true);
    $accessToken = $token['access_token'];
    $openid = $token['openid'];
  4. 拉取用戶信息:
    $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid&lang=zh_CN";
    $userInfo = json_decode(file_get_contents($infoUrl), true);
    // $userInfo 包含:nickname, headimgurl, sex, city, province, country, privilege[], unionid
  5. 業務綁定/登錄:以 openid 或 unionid 為唯一鍵,關聯本地用戶表,設置登錄態。

替代方案:基於 access_token (客戶端憑證) 獲取關注者信息

適用於用戶已關注公眾號的場景(如菜單點擊、掃碼事件、客服消息),無需網頁授權跳轉。

// 1. 獲取全局 access_token (需緩存 7200 秒)
$tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
$accessToken = json_decode(file_get_contents($tokenUrl), true)['access_token'];

// 2. 從消息 XML 中獲取 FromUserName (即 openid)
$postObj = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA);
$openid = (string)$postObj->FromUserName;

// 3. 獲取用戶詳情
$infoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openid&lang=zh_CN";
$userInfo = json_decode(file_get_contents($infoUrl), true);

返回字段含 subscribe (是否關注)、subscribe_time、nickname、headimgurl 等。

前端 JSSDK 分享配置示例


常見坑點提示

  • User-Agent 可偽造:敏感操作(支付、寫入)務必配合服務端 OAuth2 驗證,不可僅靠 UA 判斷。
  • 授權回調域必須精確匹配:不帶協議/端口/路徑,如 yourdomain.com。
  • access_token 必須緩存:頻繁請求會觸發限流,建議 Redis/文件緩存 7000 秒。
  • scope 區別:snsapi_base 靜默獲取 openid;snsapi_userinfo 彈窗授權獲取詳細信息。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved