微信開發常需識別請求是否來自微信內置瀏覽器,以調用 JSSDK、授權登錄或阻止非法訪問。核心在於檢測 User-Agent 中的 MicroMessenger 標識。
| 平台 | User-Agent 片段 |
|---|---|
| iOS | Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 ... MicroMessenger/4.3.2 |
| Android | Mozilla/5.0 (Linux; U; Android 2.3.6; zh-cn; GT-S5660 Build/GINGERBREAD) AppleWebKit/533.1 ... MicroMessenger/4.5.255 |
關鍵特徵:包含 "MicroMessenger" 字符串及版本號,可同時判斷設備類型(iPhone/Android)。
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');
}
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';
}
$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");
$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'];
$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
openid 或 unionid 為唯一鍵,關聯本地用戶表,設置登錄態。適用於用戶已關注公眾號的場景(如菜單點擊、掃碼事件、客服消息),無需網頁授權跳轉。
// 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 等。
yourdomain.com。snsapi_base 靜默獲取 openid;snsapi_userinfo 彈窗授權獲取詳細信息。