• 微信开发(二)自己的代码


    代码说明

    1.实现了调用了图灵的聊天机器人接口,实现了部分功能回复文本消息图文消息,不能接收图片消息

    2.关注事件回复欢迎关注

    3.获取关注人员的信息

    4.memcache缓存

    5.网页授权的两种方式

    6.创建自定义菜单

    6.curl发送请求

    7.jssdk预览本机图片

    主要有四个文件

    1.接收微信服务器消息的页面wx_sample.php

    <?php
        require "./config.php";
        require "./wxApi.class.php";
    
        $echostr = $_GET['echostr'];
    
        $weixin = new wxApi(APPID, APPSECRET);
    
        $weixin->valid();
        
        //接收处理微信服务器转发的xml数据包
        $post = $HTTP_RAW_POST_DATA;
    
        $weixin->chat($post);

    2.配置文件config.php

    <?php
    define("TOKEN", "xxx");
    define("APPID", "xxxxxxxxxxx");
    define("APPSECRET", "xxxxxxxxxxxx");

    3.微信网页授权的页面weixin.php

    <?php
    require "./config.php";
    require "./wxApi.class.php";
    
    $echostr = $_GET['echostr'];
    
    $weixin = new wxApi(APPID, APPSECRET);
    
    $signPackage = $weixin->jssdk_signture();
    var_dump($signPackage);
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
        <title></title>
        <link rel="stylesheet" href="./weui/dist/style/weui.min.css">
    </head>
    <body>
    <button id="dog" class="weui_btn weui_btn_primary">img</button>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script type="text/javascript">
          wx.config({
                debug: true,
                appId: '<?php echo $signPackage["appId"];?>',
                timestamp: <?php echo $signPackage["timestamp"];?>,
                nonceStr: '<?php echo $signPackage["nonceStr"];?>',
                signature: '<?php echo $signPackage["signature"];?>',
                jsApiList: ['chooseImage'
                  // 所有要调用的 API 都要加到这个列表中
                ]
              });
        wx.ready(function () {
        // 在这里调用 API
            var img = document.getElementById('dog');
            img.onclick = function(){
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                    success: function (res) {
                        var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                    }
                });
            }
          });
    </script>
    </body>
    </html>

    4.类文件 wxApi.class.php

      1 <?php
      2 class wxApi
      3 {
      4     public $appid;
      5     public $appsecret;
      6     private $access_token;
      7     public function init_access_token()
      8     {
      9         $this->access_token = $this->get_access_token();
     10     }
     11     public function __construct($appid='',$appsecret='')
     12     {
     13         $this->appid = $appid;
     14         $this->appsecret = $appsecret;
     15         $this->init_access_token();
     16     }
     17     public function valid(){
     18         if($this->checkSignature())
     19         {
     20             echo $_GET['echostr'];
     21         }
     22         else
     23         {
     24             echo "Error";
     25         }
     26     }
     27     //检验微信加密签名
     28     private function checkSignature()
     29     {
     30         $signature = $_GET['signature'];
     31         $timestamp = $_GET['timestamp'];
     32         $nonce = $_GET['nonce'];
     33 
     34         //加密
     35         //1.将token,timestamp,nonce三个参数进行字典排序
     36 
     37         $tmpArr = array(TOKEN, $timestamp, $nonce);
     38         sort($tmpArr, SORT_STRING);
     39 
     40         //2.将三个参数字符串拼接成为一个字符串进行sha1加密
     41 
     42         $tmpStr = implode($tmpArr);
     43         $tmpStr = sha1($tmpStr);
     44 
     45         //3.将开发者获得的加密后的字符串与signature对比
     46 
     47         if($tmpStr == $signature){
     48             echo true;
     49         }else{
     50             echo false;
     51         }
     52     }
     53     //获取接口调用凭证access_token
     54     public function get_access_token()
     55     {
     56         if(!$this->memcache_get('access_token')){
     57             $this->create_access_token();
     58         }
     59         return $this->memcache_get('access_token');
     60     }
     61     //生成access_token
     62     public function create_access_token()
     63     {
     64         $uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
     65         $data = $this->curl_get($uri);
     66         $access_token = $data['access_token'];
     67         $this->memcache_set('access_token', $access_token);
     68     }
     69     //缓存数据到memcache
     70     public function memcache_set($key, $value)
     71     {
     72         $mmc = new Memcache;
     73         $mmc->connect();
     74         $mmc->set($key, $value, 0, 7200);
     75     }
     76     //获得memcache的数据
     77     public function memcache_get($key)
     78     {
     79         $mmc = new Memcache;
     80         $mmc->connect();
     81         return $mmc->get($key);
     82     }
     83     //清空memcache数据
     84     public function memcache_flush()
     85     {
     86         $mmc = new Memcache;
     87         $mmc->connect();
     88         return $mmc->flush();
     89     }
     90 
     91     //发送curl get请求
     92     public function curl_get($uri='')
     93     {
     94         $ch = curl_init ();
     95         curl_setopt ( $ch, CURLOPT_URL, $uri );
     96         curl_setopt ( $ch, CURLOPT_HEADER, 0 );
     97         curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
     98         $return = curl_exec($ch);
     99         curl_close ( $ch );
    100         $return = json_decode($return, true);
    101         return $return;
    102     }
    103     //发送post请求
    104     public function curl_post($url, $post)
    105     {
    106         $ch = curl_init ();
    107         curl_setopt ( $ch, CURLOPT_URL, $url );
    108         curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    109         curl_setopt($ch, CURLOPT_POST, 1);
    110         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    111 
    112         curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    113         $return = curl_exec($ch);
    114         curl_close ( $ch );
    115         return $return;
    116     }
    117     //接收传递的数据
    118     public function receive($post)
    119     {
    120         //处理xml数据包
    121         $xmlobj = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
    122 
    123         $data['toUserName'] = $xmlobj->ToUserName;
    124         $data['fromUserName'] = $xmlobj->FromUserName;
    125         $data['msgType'] = $xmlobj->MsgType;
    126         $data['Content'] = $xmlobj->Content;
    127 
    128         return $data;
    129     }
    130 
    131     //发送数据
    132     public function send($content)
    133     {
    134         //发送get
    135         $uri = "http://www.tuling123.com/openapi/api?" . "key=d92dd28bbcb446a8a127beb6eae611ee&info=" . $content;
    136         return $this->curl_get($uri);
    137     }
    138     public function chat($post)
    139     {
    140         $data = $this->receive($post);
    141 
    142         $msgType = $data['msgType'];
    143 
    144         switch($msgType){
    145             case 'text':
    146                 $this->chat_chat($data);
    147                 break;
    148             case 'event':
    149                 $this->event($data);
    150                 break;
    151         }          
    152     }
    153     //聊天消息
    154     public function chat_chat($data)
    155     {
    156         $content = $data['Content'];
    157 
    158         $return = $this->send($content);
    159 
    160         $fromUserName = $data['fromUserName'];
    161         $toUserName = $data['toUserName'];
    162         $msgType = $data['msgType'];
    163         
    164 
    165         $content = $return['text'];
    166         $code = $return['code'];
    167 
    168         switch($code){
    169             case 100000:
    170                 $reply = "<xml>
    171                     <ToUserName><![CDATA[%s]]></ToUserName>
    172                     <FromUserName><![CDATA[%s]]></FromUserName>
    173                     <CreateTime>%s</CreateTime>
    174                     <MsgType><![CDATA[%s]]></MsgType>
    175                     <Content><![CDATA[%s]]></Content>
    176                     </xml>";
    177                 echo sprintf($reply, $fromUserName, $toUserName, time(), $msgType, $content);
    178                 break;
    179             case 200000:
    180                 $reply = "<xml>
    181                             <ToUserName><![CDATA[%s]]></ToUserName>
    182                             <FromUserName><![CDATA[%s]]></FromUserName>
    183                             <CreateTime>%s</CreateTime>
    184                             <MsgType><![CDATA[news]]></MsgType>
    185                             <ArticleCount>1</ArticleCount>
    186                             <Articles>
    187                                 <item>
    188                                     <Title><![CDATA[%s]]></Title> 
    189                                     <Description><![CDATA[%s]]></Description>
    190                                     <PicUrl><![CDATA[%s]]></PicUrl>
    191                                     <Url><![CDATA[%s]]></Url>
    192                                 </item>
    193                             </Articles>
    194                           </xml>";
    195                 $title = $return['text'];
    196                 $Description = '';
    197                 $PicUrl = 'http://1.catrazy.applinzi.com/img/t01f69da5a3069ac3b3.jpg';
    198                 $Url = $return['url'];
    199                 echo sprintf($reply, $fromUserName, $toUserName, time(), $title, $Description, $PicUrl, $Url);
    200                 break;
    201             case 302000:
    202                 $reply = "<xml>
    203                             <ToUserName><![CDATA[%s]]></ToUserName>
    204                             <FromUserName><![CDATA[%s]]></FromUserName>
    205                             <CreateTime>%s</CreateTime>
    206                             <MsgType><![CDATA[news]]></MsgType>
    207                             <ArticleCount>1</ArticleCount>
    208                             <Articles>
    209                                 <item>
    210                                     <Title><![CDATA[%s]]></Title> 
    211                                     <Description><![CDATA[%s]]></Description>
    212                                     <PicUrl><![CDATA[%s]]></PicUrl>
    213                                     <Url><![CDATA[%s]]></Url>
    214                                 </item>
    215                             </Articles>
    216                           </xml>";
    217                 $num = ceil(rand(0,10));
    218                 $title = $return['text'];
    219                 $Description = $return['list'][$num]['article'];
    220                 $PicUrl = $return['list'][$num]['icon'];
    221                 $Url = $return['list'][$num]['detailurl'];
    222                 echo sprintf($reply, $fromUserName, $toUserName, time(), $title, $Description, $PicUrl, $Url);
    223                 break;
    224             case 308000:
    225                 $reply = "<xml>
    226                             <ToUserName><![CDATA[%s]]></ToUserName>
    227                             <FromUserName><![CDATA[%s]]></FromUserName>
    228                             <CreateTime>%s</CreateTime>
    229                             <MsgType><![CDATA[news]]></MsgType>
    230                             <ArticleCount>1</ArticleCount>
    231                             <Articles>
    232                                 <item>
    233                                     <Title><![CDATA[%s]]></Title> 
    234                                     <Description><![CDATA[%s]]></Description>
    235                                     <PicUrl><![CDATA[%s]]></PicUrl>
    236                                     <Url><![CDATA[%s]]></Url>
    237                                 </item>
    238                             </Articles>
    239                           </xml>";
    240                 $num = ceil(rand(0,10));
    241                 $title = $return['text'];
    242                 $Description = $return['list'][$num]['article'];
    243                 $Url = $return['list'][$num]['detailurl'];
    244                 $str = file_get_contents($Url);
    245                 $preg = '/<imgs+src=.*>/';
    246                 preg_match($preg, $str, $match);
    247                 $PicUrl = $match[0];
    248                 echo sprintf($reply, $fromUserName, $toUserName, time(), $title, $Description, $PicUrl, $Url);
    249                 break;
    250         } 
    251     }
    252     //事件推送消息(关注事件)
    253     public function event($data)
    254     {
    255         $fromUserName = $data['fromUserName'];
    256         $toUserName = $data['toUserName'];
    257         $content = "欢迎关注";
    258         $reply = "<xml>
    259                     <ToUserName><![CDATA[%s]]></ToUserName>
    260                     <FromUserName><![CDATA[%s]]></FromUserName>
    261                     <CreateTime>%s</CreateTime>
    262                     <MsgType><![CDATA[text]]></MsgType>
    263                     <Content><![CDATA[%s]]></Content>
    264                     </xml>";
    265                 echo sprintf($reply, $fromUserName, $toUserName, time(),$content);
    266     }
    267     //创建自定义菜单
    268     public function create_menu()
    269     {
    270         $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->get_access_token()}";
    271         $post = '{
    272             "button":[
    273                 {
    274                     "name":"菜单",
    275                     "sub_button":[
    276                         {
    277                             "name":"关于我们",
    278                             "type":"view",
    279                             "url":"http://www.soso.com/"
    280                         },
    281                         {
    282                             "name":"搜索",
    283                             "type":"view",
    284                             "url":"http://www.soso.com/"
    285                         }
    286                     ]
    287 
    288                 },
    289                 {
    290                     "name":"哈哈哈",
    291                     "type":"view",
    292                     "url":"http://1.catrazy.applinzi.com/weixin.php"
    293                 }
    294             ]
    295         }';
    296 
    297         echo $this->curl_post($url, $post);
    298     }
    299     //获取用户列表
    300     public function get_user_list()
    301     {
    302         $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . $this->access_token;
    303         $data = $this->curl_get($url);
    304         // echo '<pre>';
    305         // var_dump($data);
    306         $openids = $data['data']['openid'];
    307         // var_dump($openids);
    308         return $openids;
    309     }
    310     //获取用户所有的基本信息
    311     public function get_user_info()
    312     {
    313         $access_token = $this->access_token;
    314         $openids = $this->get_user_list();
    315         foreach($openids as $openid){
    316             $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
    317             $user_info[] = $this->curl_get($url); 
    318         }
    319         return $user_info;
    320     }
    321     //base型授权
    322     public function snsapi_base($redirect_uri)
    323     {
    324         // 1.准备scope为scope_base的网页授权页面url
    325         $snsapi_base_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    326         // 2. 静默授权 获取code
    327 
    328         //页面将跳转至redirect_uri/?code=CODE&state=STATE
    329         if(!isset($_GET['code'])){
    330             header("Location:{$snsapi_base_url}");
    331         }
    332 
    333         // 3.通过code换区页面授权access_token
    334         $code = $_GET['code'];
    335 
    336         $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
    337         $return = $this->curl_get($url);
    338         $key = "token";
    339         $value = $return['openid'];
    340         $this->memcache_set($key, $value);
    341         return $return;        
    342     }
    343     //userinfo型授权
    344     public function snsapi_userinfo($redirect_uri)
    345     {
    346         $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
    347         if(!isset($_GET['code'])){
    348             header("Location:{$url}");
    349         }
    350         $code = $_GET['code'];
    351 
    352         $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
    353         $return = $this->curl_get($url);
    354 
    355         $token = $return['access_token'];
    356         $openid = $return['openid'];
    357 
    358         $url_info = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$openid}&lang=zh_CN";
    359         return $this->curl_get($url_info);
    360     }
    361     //获取jsapi
    362     public function get_jsapi()
    363     {
    364         $jsapi_ticket = $this->memcache_get('jsapi_ticket');
    365         if(!$jsapi_ticket){
    366             $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$this->access_token}&type=jsapi";
    367             $data = $this->curl_get($url);
    368             $this->memcache_set('jsapi_ticket', $data['ticket']);
    369         }
    370         return $jsapi_ticket;        
    371     }
    372     //获取jssdk签名
    373     public function jssdk_signture()
    374     {
    375         $jsapiTicket = $this->get_jsapi();
    376 
    377         // 注意 URL 一定要动态获取,不能 hardcode.
    378         $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    379         $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    380 
    381         $timestamp = time();
    382         $nonceStr = "hkasfhkh";
    383 
    384         // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    385         $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    386 
    387         $signature = sha1($string);
    388 
    389         $signPackage = array(
    390           "appId"     => $this->appid,
    391           "nonceStr"  => $nonceStr,
    392           "timestamp" => $timestamp,
    393           "url"       => $url,
    394           "signature" => $signature,
    395           "rawString" => $string
    396         );
    397         return $signPackage; 
    398     }
    399 }
  • 相关阅读:
    socket套接字
    网络编程
    元类,反射
    元类的多态、内置函数、魔法函数
    接口和抽象类
    面对对象之精髓——封装
    面对对象之继承、组合等
    Ubuntu 与 VM命令
    VM虚拟机修改 [ ubuntu ] sources 源 巴巴云镜像安装 python
    创建进程
  • 原文地址:https://www.cnblogs.com/catcrazy/p/6407952.html
Copyright © 2020-2023  润新知