微信功能大全

<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
header("content-type:text/html;charset=utf-8");

/**
 * Site controller
 */
class WeiController extends Controller
{      
        public $enableCsrfValidation = false;

        //微信验证
        public  function actionInit()
        {
            if (!empty($_GET['echostr'])) {
               // $_GET['echostr']
               $signature= $_GET["signature"];

               
               $timestamp= $_GET["timestamp"];
               $nonce=  $_GET["nonce"];
               $token= '1234567890';
               
               file_put_contents('./a.php',$_GET);

               $tmpArr = array($token, $timestamp,$nonce);

               sort($tmpArr, SORT_STRING);

               $tArr=implode($tmpArr);

               $arr=sha1($tArr);
               // echo $arr;die;

               if ( $arr == $signature )
               {
                   echo $_GET['echostr'];die;
               }
            }

          //消息接收
          
           $poststr=file_get_contents("php://input");
           // $poststr=$GLOBALS['HTTP_RAW_POST_DATA'];
           file_put_contents("msg/"."in".time().".txt",$poststr);
           //对象转化为数组
           $postobj=(array)simplexml_load_string($poststr,'SimpleXMLElement', LIBXML_NOCDATA);
           $type=$postobj['MsgType'];
           //事件消息
           if ($type=="event") {
                   //关注
                   if ($postobj['Event']=='subscribe') {
                       $this->actionWW($postobj,'欢迎你关注此公众号');
                   }
                   //赞一下
                   if ($postobj['Event']=='CLICK') {
                       if ($postobj['EventKey']=='V1001_GOOD') {
                            $this->actionWW($postobj,'谢谢你的赞  亲');
                       }                  
                   }
                   //扫码带提示
                   if ($postobj['Event']=='scancode_waitmsg') {
                       $this->actionWW($postobj,'你已经关注过了 亲');
                   }
           }
           //文本回复
           if ($type=="text") {
                   //地理位置文本回复
                   $content=substr($postobj['Content'],6);
                   // if ($content) {
                   //     $command = \Yii::$app->db->createCommand("SELECT * FROM w_j where open=".'"'.$postobj['FromUserName'].'"');
                //       $posts = $command->queryOne();
                   //     $str=$this->actionPlace($content,$posts["wj"]);                       
                   //     $this->actionWW($postobj,$str);
                   // }
                   if ($content) {
                       $command = \Yii::$app->db->createCommand("SELECT * FROM w_j where open=".'"'.$postobj['FromUserName'].'"');
                      $posts = $command->queryOne();
                       $str=$this->actionPlace($content,$posts["wj"]);

                       $this->actionTuwen($postobj,$str);
                   }

                   if ($postobj['Content']=='图文') {
                       $this->actionTuwen($postobj,'小木人','第一个图文');
                   }
                   if ($postobj['Content']=='语音')
                   {
                      $Media=$this->actionLinshi();
                      $this->actionVoice($postobj,$Media);
                   }            
                $this->actionWW($postobj,'焦焦');             
           }
           //地理位置入库
           if ($type='location') {

             $content=$postobj['Location_X'].",".$postobj['Location_Y'];
             $openid=$postobj['FromUserName'];
             
             $command = \Yii::$app->db->createCommand('SELECT * FROM w_j where open="'.$openid.'"');
               $posts = $command->queryOne();

             if ($posts) {
                 \Yii::$app->db->createCommand()->update('w_j', ['wj'=>$content],["open" => $openid])->execute();
             }else{
                 \Yii::$app->db->createCommand()->insert('w_j',['open'=>$openid,'wj'=>$content])->execute();
             }
           }
           
           //图片回复
           if ($type=='image') {
                echo "<xml>
                <ToUserName><![CDATA[".$postobj['FromUserName']."]]></ToUserName>
                <FromUserName><![CDATA[".$postobj['ToUserName']."]]></FromUserName>
                <CreateTime>".time()."</CreateTime>
                <MsgType><![CDATA[image]]></MsgType>
                <Image>
                <MediaId><![CDATA[".$postobj['MediaId']."]]></MediaId>
                </Image>
                </xml>";
           }
        }
        //圆形区域检索来实现附近搜索功能
        public function actionPlace($query,$location)
        {   
            // $query="酒店";
            // $location="39.90323654556414,116.3977227917131";
            
            $url="http://api.map.baidu.com/place/v2/search";

            $data=[
                "q"=>$query,
                "output"=>'json',
                "scope"=>2,
                "filter"=>'sort_name:distance',
                "ak"=>'kDZeKxXNphkWiBc75qMxsKd1vVbvNBS7',
                "page_size"=>4,
                "location"=>$location,
                "radius"=>2000,
            ];
            $res=file_get_contents($url."?".http_build_query($data));
            $arr=json_decode($res,true);
            // echo $res;die;

            // var_dump($arr);die;

            // $str="";
            // foreach ($arr['results'] as $k => $v) {
            //     $str.=$v["name"]."距离您".$v['detail_info']['distance']."米"."\r\n";
            // }
            // return $str;
            return $arr;
        }
        //关注和文本
        public  function actionWW($postobj,$content){
                $time=time();
                $str="<xml>
                <ToUserName><![CDATA[".$postobj['FromUserName']."]]></ToUserName>
                <FromUserName><![CDATA[".$postobj['ToUserName']."]]></FromUserName>
                <CreateTime>".$time."</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[".$content."]]></Content>
                </xml>";
                echo $str;
        }
        //图文
        public function actionTuwen($postobj,$data)
        {
                
                $time=time();
                $str="<xml>
                    <ToUserName><![CDATA[".$postobj['FromUserName']."]]></ToUserName>
                    <FromUserName><![CDATA[".$postobj['ToUserName']."]]></FromUserName>
                    <CreateTime>".$time."</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>4</ArticleCount>
                    <Articles>";
                foreach ($data['results'] as $k => $v) {
                    $str.="<item>
                    <Title><![CDATA[".$v['name'].">>>距离您".$v['detail_info']['distance']."米]]></Title>
                    <Description><![CDATA[好吧]]></Description>
                    <PicUrl><![CDATA[http://jmj.free.ngrok.cc/Month10/weixin/frontend/web/1.jpg]]></PicUrl>
                    <Url><![CDATA[".$v['detail_info']['detail_url']."]]></Url>
                    </item>";
                }    
                    $str.="</Articles>
                    </xml>";
                
                echo $str;
                    

                // $PicUrl="http://www.weixin.com/frontend/web/2.jpg";
                // $PicUrl1="http://www.weixin.com/frontend/web/1.jpg";
          //       $Url="www.baidu.com";
          //       $Url1="http://www.autohome.com.cn/beijing/";    
          //       $str1=sprintf($str,$PicUrl,$Url,$PicUrl1,$Url1);
                // echo $str1;

        }
        //语音
        public function actionVoice($postobj,$Media)
        {
                $voice="<xml>
                <ToUserName><![CDATA[".$postobj['FromUserName']."]]></ToUserName>
                <FromUserName><![CDATA[".$postobj['ToUserName']."]]></FromUserName>
                <CreateTime>".time()."</CreateTime>
                <MsgType><![CDATA[voice]]></MsgType>
                <Voice>
                <MediaId><![CDATA[".$Media."]]></MediaId>
                </Voice>
                </xml>";
                echo $voice;
        }  

/***************************************自定义菜单创建*****************************************************/

        public function actionMenu()
        {
                // 获取token
                $access_token=$this->actionAccess_token();
                //接口调用请求说明  (请使用https协议)
                $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;

                $filedata='{
                "button":[
                {    
                "name":"工具",
                "sub_button":[
                {
                "type": "scancode_waitmsg",
                "name": "扫码带提示",
                "key": "rselfmenu_0_0",
                "sub_button": [ ]
                },
                {
                "type": "scancode_push",
                "name": "扫码推事件",
                "key": "rselfmenu_0_1",
                "sub_button": [ ]
                },
                {
                "type": "pic_sysphoto",
                "name": "系统拍照发图",
                "key": "pic_sysphoto",
                "sub_button": [ ]
                },
                {
                "type": "pic_photo_or_album",
                "name": "拍照或者相册发图",
                "key": "photo",
                "sub_button": [ ]
                },
                {
                "type": "location_select",
                "name": "位置",
                "key": "location",
                "sub_button": [ ]
                }
                ]
                },
                {
                "name":"关注",
                "sub_button":[
                {    
                "type":"view",
                "name":"搜索",
                "url":"http://www.baidu.com/",
                "sub_button": [ ]
                },
                {    
                "type":"view",
                "name":"微信登录",
                "url":"http://jmj.free.ngrok.cc/Month10/weixin/frontend/web/index.php?r=wei/add",
                "sub_button": [ ]
                },
                {
                "type":"click",
                "name":"赞一下我们",
                "key":"V1001_GOOD",
                "sub_button": [ ]
                }]
                },
                {
                "name":"分享",
                "sub_button":[
                {    
                "type":"view",
                "name":"分享到朋友圈",
                "url":"http://jmj.free.ngrok.cc/Month10/weixin/frontend/web/index.php?r=wei/one",
                "sub_button": [ ]
                }]
                }]
                }';
                $menu=$this->https_request($url, $filedata);
                echo $menu;

        }
/*************************************个性化菜单**********************************************************/
        public function actionMenu_g()
        {
            // 获取token
            $access_token=$this->actionAccess_token();
            //接口调用请求说明  (请使用https协议)
            $url="https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$access_token;

            $filedata='{
                        "button":[
                        {    
                        "type":"click",
                        "name":"今日歌曲",
                        "key":"V1001_TODAY_MUSIC"
                        },
                        {
                        "name":"菜单",
                        "sub_button":[
                        {    
                        "type":"view",
                        "name":"搜索",
                        "url":"http://www.baidu.com/"
                        },
                        {
                        "type":"click",
                        "name":"赞一下我们",
                        "key":"V1001_GOOD"
                        }]
                        }],
                        "matchrule":{
                        "sex":"1",
                        "country":"中国",
                        "client_platform_type":"1",
                        "language":"zh_CN"
                        }
                        }';
            $menuid=$this->https_request($url, $filedata);    
            echo $menuid;
        }
        /*************************删除个性化菜单***********************/
        public function actionMenu_g_x()    
        {         
                   // 获取token
                $access_token=$this->actionAccess_token();
                //接口调用请求说明  (请使用https协议)
                $url="https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=".$access_token;
                $filedata='{
                            "menuid":"754920258"
                          }';
                $menu=$this->https_request($url, $filedata);
                echo $menu;
        }

        /*************************测试个性化菜单***********************/
        public function actionMenu_g_c()
        {
            // 获取token
                $access_token=$this->actionAccess_token();
                //接口调用请求说明  (请使用https协议)
                $url="https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=".$access_token;
                $filedata='{
                            "user_id":"om7RTxMF_w4YscrH8CMWlGgf8Ev4    "
                          }';
                $menu=$this->https_request($url, $filedata);
                echo $menu;
        }  

/*************************************网页授权**********************************************************/
        public function actionAdd()
        {   
            // $appid='';
            // $appsecret='';

            if (isset($_GET['code'])) {

                $code=$_GET['code'];
                $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxbbfa6df80debe0ae&secret=b97b0ef0248af454e15a8e1ea29f0e6d&code=".$code."&grant_type=authorization_code";
                $url=(array)json_decode(file_get_contents($url));
                $access_token=$url['access_token'];
                $oppid=$url['openid'];

                $openid_url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$oppid."&lang=zh_CN";

                $openid_url=file_get_contents($openid_url);
                file_put_contents("msg/ge.txt",$openid_url);
                var_dump($openid_url);

            }else{

                //回调地址
                $hd=urlencode("http://jmj.free.ngrok.cc/Month10/weixin/frontend/web/index.php?r=wei/add");

                $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbbfa6df80debe0ae&redirect_uri=".$hd."&response_type=code&scope=snsapi_userinfo&state=12345#wechat_redirect";

                header("Location:".$url);

            }
        }
/*******************************************创建二维码ticket*********************************************/
        public function actionTicket()
        {
                // 获取token
                $access_token=$this->actionAccess_token();
                $url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;  
                $filedata='{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info":{"scene":{"scene_id": 5}}}';                
                $result =$this->https_request($url, $filedata);
                // var_dump($result);die;                
                $ti=json_decode($result,true);
                // var_dump($ti);
                $ti=$ti['ticket'];
                // echo $ti;die;
                $ticket_tu="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ti);
                $erweima=file_get_contents($ticket_tu);
                //生成二维码图片日志
                file_put_contents("msg/erweima.jpg",$erweima);
                // var_dump($erweima);                 
                return $erweima;                
        }

/*************************************群发消息**********************************************************/
        //文本群发
        public function actionQunfa()
        {  
            $access_token=$this->actionAccess_token();
            $url="https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$access_token;
            $qun='{
                   "touser":[
                    "om7RTxP0MVDQmEec1nqWGhte04Os",
                    "om7RTxHuV-MlZcARf2swGh7E0u4I"
                   ],
                    "msgtype":"text",
                    "text":{"content":"群发回复的是当天的新闻信息等.."}
                }';
            $res=$this->https_request($url, $qun);
            var_dump($res);
        }
/*******************************************模版消息*****************************************************/

        public function actionIndustry()
        {
                // 获取token
                $access_token=$this->actionAccess_token();
                $industry_url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                $filedata='{
                       "touser":"om7RTxP0MVDQmEec1nqWGhte04Os",
                       "template_id":"kQrXiJpPBzZqBEORSLtxnchlYu6Ry_yAvCfeQek7FRE",
                       "url":"http://weixin.qq.com/",          
                       "data":{
                               "goodsname":{
                                   "value":"上岛咖啡",
                                   "color":"#173177"
                               },
                               "username":{
                                   "value":"微信账户",
                                   "color":"#173177"
                               },
                               "money":{
                                   "value":"$33.73元",
                                   "color":"#173177"
                               }
                       }
                   }';
                $result=$this->https_request($industry_url,$filedata);
                file_put_contents("msg/m.txt",$result);
                var_dump($result);  
        }

/*******************************************jssdk 分享*************************************************/
       public function actionOne()
        {
            //签名
            
            // 获取token
            $access_token=$this->actionAccess_token();

            $url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $js=json_decode(file_get_contents($url),true);
            // 签名算法需要几个参数
            // 获取ticket
            $ticket=$js['ticket'];
            //随机数
            $noncestr='sdfsdfsfsdfwgggegggdf';
            //时间戳
            $timestamp=time();
            //当前网页的URL
            $d_url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            //拼接成字符串string1
            $str="jsapi_ticket=".$ticket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$d_url;
            //进行sha1加密
            $sign=sha1($str);
            $arr=[
                "noncestr"=>$noncestr,
                "timestamp"=>$timestamp,
                "sign"=>$sign,
            ];
            // echo $sign;die;
            return $this->render('index',["arr"=>$arr]);
        }
/*******************************************获取临时素材*************************************************/
        //素材
        public function actionLinshi()
        {
                // 1 请求地址
                // 获取token
                $access_token=$this->actionAccess_token();
                // echo $access_token;die;

                $Media_url=$this->uploadMedia($access_token);

                $Media1=json_decode($Media_url,true);
                // var_dump($Media1);die;
                $Media=$Media1['media_id'];

                return $Media;                  
        }
        // 获取token值
        public function actionAccess_token()
        {        
               //判断文件是否存在
                if (is_file("msg/token.txt")) {
                       $access_token=json_decode(file_get_contents("msg/token.txt"),true);
                       //判断时间是否过期
                         if (time()-$access_token['times']>7000) {
                             $token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbbfa6df80debe0ae&secret=b97b0ef0248af454e15a8e1ea29f0e6d";
                            $token=file_get_contents($token_url);
                            $ken= json_decode($token,true);    
                            $ken['times']=time();                    
                         }
                            $access_token=$ken['access_token'];
                            return $access_token;                            
                     }else{
                             $token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbbfa6df80debe0ae&secret=b97b0ef0248af454e15a8e1ea29f0e6d";
                            $token=file_get_contents($token_url);
                            $ken= json_decode($token,true);                        
                            file_put_contents("msg/token.txt",$ken);
                            $access_token=$ken['access_token'];
                            return $access_token;
                     }                
        }
        // 2 组装参数
        public function uploadMedia($access_token)
        {
                $type = "voice";

                $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=".$type;  

                $filedata=array('media'=>new \CURLFile(realpath("voice/1.mp3")));

                $result=$this->https_request($url,$filedata);
                return $result;
         }
        // 3 请求
        public function https_request($url, $filedata)
        {
                $curl = curl_init ();
                curl_setopt ( $curl, CURLOPT_URL, $url );
                curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
                curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
                if (! empty ( $filedata)) {
                curl_setopt ( $curl, CURLOPT_POST, 1 );
                curl_setopt ( $curl, CURLOPT_POSTFIELDS,$filedata);
                }
                curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
                $output = curl_exec ( $curl );
                curl_close ( $curl );
                return $output;
        }

}

?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值