使用PHP和JavaScript判断请求是否来自微信内浏览器

时间:2022-10-07 10:25:54

 微信浏览器的HTTP_USER_AGENT

在iPhone下,返回

?
1
Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176 MicroMessenger/4.3.2)

在Android下,返回

?
1
Mozilla/5.0 (Linux; U; Android 2.3.6; zh-cn; GT-S5660 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MicroMessenger/4.5.255)

不难发现微信浏览器为 MicroMessenger ,并且有版本号,也可以判断手机类型为iPhone还是Android

如果要做盗链

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if(strpos($_SERVER["HTTP_USER_AGENT"],"MicroMessenger"))
  echo "Welcome to wechat word";
else
  echo "http/1.1 401 Unauthorized";
 
public function is_weixin(){
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
 return true;
}
 return false;
}   
if($this->is_weixin()){
 }else{
 echo "请使用微信访问本网址。";
}


js判断

?
1
2
3
4
5
6
7
8
function is_weixin(){
  var ua = navigator.userAgent.toLowerCase();
  if(ua.match(/MicroMessenger/i)=="micromessenger") {
    return true;
   } else {
    return false;
  }
}

当在手机端判断到微信浏览器之后,可以使用微信的分享js脚本对其进行处理,大家可以参考微信的官方文档,这里提供一个案例,了解下大概流程和思路
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script type="text/javascript" src="/jslib/wx_share.js"></script>
    <script>
      //分享链接时给其重写分享的标题、缩略图、链接、简介等
      var imgUrl = '<?php echo base_url('/images/per.png'); ?>';
      var lineLink = 'http://www.baidu.com/';
      var shareTitle = '我来给你送钱了';
      var descContent = '折射率,你知道是啥?';
      var timeline_title = 'timeline_title';
      var appid = '';
    </script>
    <script>
      function onBridgeReady() {
        WeixinJSBridge.call('showOptionMenu');
      }
    </script>
    <script>
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      } else {
        onBridgeReady();
      }
    </script>
</head>