php开发微信

<?php
namespace backend\controllers;


use Yii;
use yii\web\Controller;


/**

*/
class WechatController extends controller
{
public $enableCsrfValidation=false;


public function actionInit()
{
// echo $_GET['echostr'];die;
    $postStr = file_get_contents("php://input");
    file_put_contents("log/".time().rand(1000,9999).".log",$postStr);
    $arr = (array)simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
    $type = $arr['MsgType'];
    //事件类型
    if ($type == 'event') {
      if ($arr['Event'] == 'subscribe') {
        $this->actionSendtext($arr,'欢迎关注');
      }


      if ($arr['Event'] == 'CLICK') {
        if ($arr['EventKey'] == 'V1001_GOOD') {
          $this->actionSendtext($arr,'谢谢你的赞');
        }
        if ($arr['EventKey'] == 'V1001_TODAY_MUSIC') {
          $this->actionSendtext($arr,'依然爱你.mp3');
        }
      }
    }


    if ($type == 'text') {
      if ($arr['Content'] == '你好') {
        $this->actionSendtext($arr,'恩,一直都在');
      }
      if ($arr['Content'] == '图文') {
        $this->actionImgnews($arr);
      }


      if ($arr['Content'] == '语音') {
        $this->actionVoice($arr,'o786_ccbS8ZFwSHf9d5YpJTuB4n06K4d6tGLA-dedOM6WgOLkWorrAaHkotWmVJl');
      }
    }


    if ($type == 'image') {
      $this->actionImg($arr);
    }
}


  //图片消息
  public function actionImg($arr)
  {
       $str="<xml>
       <ToUserName><![CDATA[".$arr['FromUserName']."]]></ToUserName>
       <FromUserName><![CDATA[".$arr['ToUserName']."]]></FromUserName>
       <CreateTime>".time()."</CreateTime>
       <MsgType><![CDATA[image]]></MsgType>
       <Image>
       <MediaId><![CDATA[".$arr['MediaId']."]]></MediaId>
       <Image>
       </xml>";
       echo $str;die;
  }
  //文本消息
  public function actionSendtext($arr,$Content)
  {
    $str = "<xml>
            <ToUserName><![CDATA[".$arr['FromUserName']."]]></ToUserName>
            <FromUserName><![CDATA[".$arr['ToUserName']."]]></FromUserName>
            <CreateTime>".time()."</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[".$Content."]]></Content>
            </xml>";
            echo $str;die;
  }
  //语音消息
  public function actionVoice($arr,$MediaId)
  {
    echo $str="<xml>
      <ToUserName><![CDATA[".$arr['FromUserName']."]]></ToUserName>
      <FromUserName><![CDATA[".$arr['ToUserName']."]]></FromUserName>
      <CreateTime>".time()."</CreateTime>
      <MsgType><![CDATA[voice]]></MsgType>
      <Voice>
      <MediaId><![CDATA[".$MediaId."]]></MediaId>
      </Voice>
      </xml>";
  }
  //图文消息
  public function actionImgnews($arr)
  {
    $str = "<xml>
      <ToUserName><![CDATA[".$arr['FromUserName']."]]></ToUserName>
      <FromUserName><![CDATA[".$arr['ToUserName']."]]></FromUserName>
      <CreateTime>".time()."</CreateTime>
      <MsgType><![CDATA[news]]></MsgType>
      <ArticleCount>3</ArticleCount>
      <Articles>
      <item>
      <Title><![CDATA[鹿晗关晓彤公布恋情 跑男晚会电视剧牵的红线?]]></Title> 
      <Description><![CDATA[鹿晗关晓彤公布恋情 跑男晚会电视剧牵的红线?]]></Description>
      <PicUrl><![CDATA[http://n.sinaimg.cn/ent/transform/20171009/WkiX-fymrcmm9358430.jpg]]></PicUrl>
      <Url><![CDATA[http://ent.sina.com.cn/zt_d/lhgxtlq/]]></Url>
      </item>
      <item>
      <Title><![CDATA[陈翔上节目痛哭 网友猜测其9月已与毛晓彤分手]]></Title> 
      <Description><![CDATA[陈翔上节目痛哭 网友猜测其9月已与毛晓彤分手]]></Description>
      <PicUrl><![CDATA[http://k.sinaimg.cn/n/ent/transform/20171009/pvJM-fymrcmm9439943.png/w150h100f1t0l0q100syf.png]]></PicUrl>
      <Url><![CDATA[http://ent.sina.com.cn/tv/zy/2017-10-09/doc-ifymrcmm9440300.shtml?cre=tianyi&mod=pcent&loc=0&r=-1&doct=0&rfunc=99&tj=none&tr=73]]></Url>
      </item>
      <item>
      <Title><![CDATA[奶爸陈赫给女儿唱歌超有爱 安安乖巧聆听背影软萌]]></Title> 
      <Description><![CDATA[奶爸陈赫给女儿唱歌超有爱 安安乖巧聆听背影软萌]]></Description>
      <PicUrl><![CDATA[http://k.sinaimg.cn/n/ent/transform/20171009/Q6Od-fymrcpw5218013.png/w150h100f1t0l0q100syf.png]]></PicUrl>
      <Url><![CDATA[http://ent.sina.com.cn/s/m/2017-10-09/doc-ifymrcmm9471924.shtml?cre=tianyi&mod=pcent&loc=2&r=25&doct=0&rfunc=99&tj=none&tr=25]]></Url>
      </item>
      </Articles>
      </xml>";
      echo $str;die;
  }
   //获取token
   public function getToken()
  {
    $file="token.txt";
    if(is_file($file))
    {
      $access_token=file_get_contents($file);
      $access_token=json_decode($access_token,true);
      if(!$access_token['access_token'] || time()-$access_token['time']>7000)
      {
        $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx60b756b3c891df9d&secret=7951fe913a837cc80a21f3575aaff815";
        $access_token=file_get_contents($access_token_url);
        $access_token=json_decode($access_token,true);
        $access_token['time']=time();
        file_put_contents($file,json_encode($access_token));
      }


    }
    return $access_token;
  }


  //获取URL
  public function http_post_upload($url,$data)
  {
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $a=curl_exec($ch);
    curl_close($ch);
    return $a;
  }
  //临时素材
  public function actionLinshi()
  {
    $access_token=$this->getToken();
    //url
    $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token['access_token']."&type=voice";
    //组装参数
    $data=array(
      'media'=>new \CURLFile(realpath("aa.mp3")),
      );
    //请求
    $res=$this->http_post_upload($url,$data);
    var_dump($res);
  }
  //自定义菜单
  public function actionMenu()
  {
  $token=$this->getToken();
  $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token['access_token'];
  $uu=urlencode("http://edc.free.ngrok.cc/tenth/backend/web/index.php?r=wechat/one");


  $data = '{
        "button": [
            { 
              "type":"click",
              "name":"今日歌曲",
              "key":"V1001_TODAY_MUSIC"
            },
            {
                "name": "微信小工具", 
                "sub_button": [
                    {
                        "type": "pic_sysphoto", 
                        "name": "系统拍照发图", 
                        "key": "rselfmenu_1_0"
                     }, 
                    {
                        "type": "pic_photo_or_album", 
                        "name": "拍照或者相册发图", 
                        "key": "rselfmenu_1_1"
                    }, 
                    {
                        "type": "pic_weixin", 
                        "name": "微信相册发图", 
                        "key": "rselfmenu_1_2" 
                    },
                     {
                        "type": "scancode_waitmsg", 
                        "name": "扫码带提示", 
                        "key": "msgkey"
                    }, 
                    {
                        "type": "scancode_push", 
                        "name": "扫码推事件", 
                        "key": "pushkey"
                    }
                ]
            }, 
            {
                "name": "菜单", 
                "sub_button": [
                    {
                        "type": "location_select", 
                        "name": "发送位置", 
                        "key": "areakey"
                     }, 
                    {
                        "type": "view", 
                        "name": "搜索", 
                        "url":"http://www.soso.com/" 
                    }, 
                    {
                        "type": "click", 
                        "name": "赞一下我们", 
                        "key": "V1001_GOOD"
                    },
                    {
                      "type":"view",
                      "name":"登录",
                      "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx60b756b3c891df9d&redirect_uri='.$uu.'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect"
                    }
                ]
            }
        ]
    }';


  $res=$this->http_post_upload($url,$data);
        var_dump($res);
  }


    //网页授权
  public function actionOne()
  {
    $code=$_GET['code'];
    // print_r($code);die;
    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx60b756b3c891df9d&secret=7951fe913a837cc80a21f3575aaff815&code=".$code."&grant_type=authorization_code";
    $res=file_get_contents($url);  
    $res=json_decode($res,true);
    $userurl="https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";
    $result=file_get_contents($userurl);
    var_dump($result);
  }


  //二维码
  public function actionTicket()
  {
  $token = $this->getToken();
  $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token['access_token'];
  $data = '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 5}}}';
  $res = $this->http_post_upload($url,$data);
  $res = json_decode($res,1);
  $ticket = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($res['ticket']);
  $result = file_get_contents($ticket);
  file_put_contents('ma.jpg',$result);
  var_dump('成功');
  }


  //模板消息
  public function actionBan()
  {
  $token = $this->getToken();
  $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token['access_token'];
  $data = '{
           "touser":"oenn61EZ765nV2wL5ro58VdKRJPs",
           "template_id":"gZAWqkO0khwhVV2vdo2MRGdHDoLMZ7TBcNS2XhfYAmg",
           "url":"http://weixin.qq.com",     
           "data":{
                   "first": {
                       "value":"恭喜你购买成功!",
                       "color":"#173177"
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keynote2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keynote3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买!",
                       "color":"#173177"
                   }
           }
       }';


       $res =$this->http_post_upload($url,$data);
       var_dump($res);
  }


  //群发消息
  public function actionQunfa()
  {
  $token = $this->getToken();
  $url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$token['access_token'];
  $data = '{
  "touser":[
   "oenn61Lg6xu8uOWjXvbYtQ5ckKgc",
   "oenn61EZ765nV2wL5ro58VdKRJPs"
  ],
   "msgtype": "text",
   "text": { "content": "欢迎来到王者荣耀"}
}';


$res = $this->http_post_upload($url,$data);
var_dump($res);
  }


  //获取标签下粉丝列表
  public function actionSignlist()
  {
     $token = $this->getToken();
     $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=".$token['access_token'];
     $data = '{
        "tagid" : 2,
        "next_openid":"oenn61EZ765nV2wL5ro58VdKRJPs"
      }';


      $res = $this->http_post_upload($url,$data);
      var_dump($res);
  }


  //批量给用户打标签
  public function actionSign()
  {
    $token = $this->getToken();
    $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=".$token['access_token'];
    $data = '{
      "openid_list" : [
        "oenn61Lg6xu8uOWjXvbYtQ5ckKgc"
      ],
      "tagid" : 2
    }';


    $res = $this->http_post_upload($url,$data);
    var_dump($res);
  }


  //取消标签
  public function actionDel()
  {
    $token = $this->getToken();
    $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=".$token['access_token'];
    $data = '{
      "openid_list" : [
        
        "oenn61Lg6xu8uOWjXvbYtQ5ckKgc"
      ],
      "tagid" : 2
    }';


    $res = $this->http_post_upload($url,$data);
    var_dump($res);
  }


  //个性化菜单
  // public function actionPersonality()
  // {
  //   $token = $this->getToken();
  //   $url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$token['access_token'];
  //   $data = '{
  //       "button":[
  //       { 
  //           "type":"click",
  //           "name":"今日歌曲",
  //           "key":"V1001_TODAY_MUSIC" 
  //       },
  //       { 
  //         "name":"菜单",
  //         "sub_button":[
  //         { 
  //           "type":"view",
  //           "name":"搜索",
  //           "url":"http://www.soso.com/"
  //         },
  //         {
  //           "type":"click",
  //           "name":"赞一下我们",
  //           "key":"V1001_GOOD"
  //               }]
  //      }],
  //     "matchrule":{
  //       "sex":"1", 
  //       }
  //     }';
  //     $res = $this->http_post_upload($url,$data);
  //     var_dump($res);
  // }


  //获取标签
  public function actionGetmenu()
  {
    $token = $this->getToken();
    $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=".$token['access_token'];
    $res = file_get_contents($url);
    var_dump($res);
  }


  //删除个性化菜单
  public function actionDelmenu()
  {
    $token = $this->getToken();
    $url = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=".$token['access_token'];
    $data = '{
        "menuid":"562561439"
          }';
    $res =$this->http_post_upload($url,$data);
    var_dump($res);
  }
  
  //分享朋友圈
  public function actionEnjoy()
  {
    $token = $this->getToken();
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token['access_token']."&type=jsapi";
    $ticket = file_get_contents($url);
    $ticket = json_decode($ticket,1);
    $ticket = $ticket['ticket'];
    $noncestr = 'Wm3WZYTPz0wzccnW';
    $timestamp = time();
    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    // var_dump($ticket);die;
    $str = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
    $sign = sha1($str);
    $arr = [
        "timestamp" => $timestamp,
        "noncestr"  => $noncestr,
        "sign"      => $sign
    ];
    return $this->render('index',['arr'=>$arr]);
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值