利用thinkphp企业微信,发送消息

1.获取accesstokenphp

private $appId="wxcf....."; //微信企业号的appid

    public function getAccessToken() { //获取AccessToken的方法

    $data = json_decode(file_get_contents("AccessToken.json"));//获取存在AccessToken.json
    //$access_token=$data->access_token;

    if ($data->expire_time < time()) { //若是AccessToken过时则从新获取AccessToken
        // $config = C('WX_CONFIG');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxcf.....&corpsecret=2ASy1p9hBT_AGhaSeJEHMbXiXY........";//获取AccessToken的url及参数。
        
         $res =$this->https_request($url);//调用https请求方法
         $res = json_decode($res); //把$res设置为对象
         $access_token = $res->access_token; //获取结果集中的access_token
      if ($access_token) {
        $data->expire_time = time() + 7000; //上一次获取access_token的时间加上两小时,access_token的有效时间为两小时,超过两小时则从新获取。也能够每次使用时都从新获取,可是有获取次数限制。
        $data->access_token = $access_token;
        $fp = fopen("AccessToken.json", "w"); //打开AccessToken.json文件,“W”表示写入(Write)
        fwrite($fp, json_encode($data));//获取到的结果写入
        fclose($fp);//关闭文件
      }
    } else {
      $access_token = $data->access_token; //未过时状况下直接读取文件里的access_token
    }
    return $access_token;
  }

2.https 请求方法json

//https请求(支持GET和POST)
    public function https_request($url, $data = null){
        $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($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

3.发送消息api

//请假时发送消息给上级审批
public  function  sendMSG($superior,$name,$meet,$id){


$access_token=$this->getAccessToken();//调用getAccessToken方法获取access_token


$arr=array(      
  'touser'=>$superior, //消息接收者工号
  "msgtype"=> "text",
     "agentid"=>8,
      "text"=> array(
        "content"=>'<a href="http://....../qyhdev/index.php?s=/weixin/Bublic/index/id/'.$id.'/name/'.$name.'/meet/'.$meet.'">收到'.$name.''.$meet.'请假申请,请点击查看</a>'  //发送的消息内容
       )
 
  );

$arr=json_encode($arr,JSON_UNESCAPED_UNICODE); //利用json_encode把$arr变为json形式,“JSON_UNESCAPED_UNICODE”参数把中文变为json形式。

$url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$access_token;

 $res=$this->https_request($url, $arr); //调用https请求方法发送消息。
}

4.调用sendMSG方法微信

public function leave(){
 $this->sendMSG($superior,$name,$meetname,$id); //调用sendMSG方法
}
相关文章
相关标签/搜索