ubuntu(linux服务器)定时推送企业微信应用消息(Tp5)

1.首先写TP5命令脚本

<?php
/**
 * Created by PhpStorm.
 * User: rk
 * Date: 2019/11/5
 * Time: 17:18
 */
namespace app\common\command;

use app\admin\controller\Base;
use app\admin\model\User;
use app\common\controller\Tools;
use app\crm\controller\Business;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Config;
class Task extends Command
{
    protected function configure()
    {
       //这里的setName和php文件名一致,setDescription随意
        $this->setName('Task')->setDescription('xxxx');
    }
    protected function execute(Input $input, Output $output)
    {
        Config::set('database',[ // 数据库类型
            'type'            => 'mysql',
            // 服务器地址
            'hostname'        => '',
            // 数据库名
            'database'        => '',
            // 用户名
            'username'        => '',//
            // 密码
            'password'        => '',//
            // 端口
            'hostport'        => '3306',
            // 连接dsn
            'dsn'             => '',
            // 数据库连接参数
            'params'          => [],
            // 数据库编码默认采用utf8
            'charset'         => 'utf8',
            // 数据库表前缀
            'prefix'          => '88_',
            // 数据库调试模式
            'debug'           => true,
            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'          => 0,
            // 数据库读写是否分离 主从式有效
            'rw_separate'     => false,
            // 读写分离后 主服务器数量
            'master_num'      => 1,
            // 指定从服务器序号
            'slave_no'        => '',
            // 自动读取主库数据
            'read_master'     => false,
            // 是否严格检查字段是否存在
            'fields_strict'   => true,
            // 数据集返回类型
            'resultset_type'  => 'array',]);
        //生成word文件
        $tools = new Tools();
        //推送企业微信应用文件    每天一次
        $res = $tools->send_file();
        //发送成功后删除文件
        $day = date("Y-m-d", time());
        if(file_exists('temp/'.$day.'.doc')){
            @unlink('temp/'.$day.'.doc');
        }
        if($res['code']!==200){
            $output->writeln('fail');
        }
        $output->writeln('success');

    }
}

大坑提示:
//坑 Command不会去掉数据库配置文件,试了很多方法,在think文件定义,在本类中引入DB和配置文件都不行

2.编写生发送企业微信应用文件信息的工具类.

 //获取上传企业微信 文件的ID
    public function send_file(){
        $vxmodel = new Base();
        $token_res = $vxmodel->get_access_token();
        $access_token =  $token_res['access_token'];
        //拿到 上传文件ID
        $tools = new Tools();
        $tools->ToWord();
        $time = time();
        $day = date("Y-m-d",$time);//'@'.ROOT_PATH.'temp/'.$day.'.doc'
        $file_path["media"] = '@'.ROOT_PATH.'temp/'.$day.'.doc';
        $file_url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type=file';
        $file_res = $tools->http_post_file($file_url, $file_path,true); //调用https请求方法发送消息
        $res_arr = json_decode($file_res,true);
        $media_id = $res_arr['media_id'];//文件ID

        $arr=array(
            'touser'=>"RK", //消息接收者工号"UserID1|UserID2|UserID3"$superior   |HuangZhenCheng
            "toparty"=> "",
            "totag"=> "",
            "msgtype"=> "file",
            "agentid"=> "",
            "file"=> array(
                "media_id"=>$media_id //发送的消息内容
            ),
            "safe"=> 1,//表示是否是保密消息,0表示否,1表示是,默认0
        );
        $send_data=json_encode($arr,JSON_UNESCAPED_UNICODE);
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$access_token;
        if($tools->https_request($url, $send_data)){
            return ['code'=>200];
        }; //调用https请求方法发送消息
        return ['code'=>0];
    }

大坑提示:
*//坑 发送企业微信应用文件消息,首先要拿到文件ID
上传文件时要注意上传的文件名就是别人收到的名称
CURL POST请求要写好

/**
     * 构造企业微信上传临时素材的请求链接
     **/
    function http_post_file($url,$param,$post_file=false){
        $oCurl = curl_init(); //初始化curl

        if(strpos($url,"https://")!==FALSE){ //判断$url中是否存在"https://";如果存在的话就执行以下代码
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); //关闭CURLOPT_SSL_VERIFYPEER服务-禁用后cURL将终止从服务端进行验证
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); //不设置CURLOPT_SSL_VERIFYPEER服务-禁用后cURL将终止从服务端进行验证
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //使用的SSL版本
        }
        if(PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')){
            $is_curlFile = true;
        }else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }

        if($post_file) {
            if($is_curlFile) {
                foreach ($param as $key => $val) {
                    if(isset($val["tmp_name"])){
                        $param[$key] = new \CURLFile(realpath($val["tmp_name"]),$val["type"],$val["name"]);//$val["tmp_name"] 上传的文件名
                    }else if(substr($val, 0, 1) == '@'){
                        $day = date("Y-m-d", time());
                        $param[$key] = new \CURLFile(realpath(substr($val,1)),'file','xxx'.$day);//xxx  上传的文件名
                    }
                }
            }
            $strPOST = $param;
        }else{
            $strPOST = json_encode($param); //将数值转换成json数据存储格式
        }
        curl_setopt($oCurl, CURLOPT_URL, $url); //获取的URL地址
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($oCurl, CURLOPT_HEADER, 0);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true); //在启用CURLOPT_RETURNTRANSFER的时候,返回原生的(Raw)输出。
        curl_setopt($oCurl, CURLOPT_POST,true); //发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST); //全部数据使用HTTP协议中的"POST"操作来发送。
        curl_setopt($oCurl, CURLOPT_VERBOSE, 1); //汇报所有的信息,存放在STDERR或指定的CURLOPT_STDERR中

        //curl_setopt($oCurl, CURLOPT_HEADER,  array( 'Expect:' ));  //将其删掉返回的为json串
        curl_error($oCurl);
        $sContent = curl_exec($oCurl); //执行一个cURL会话
        curl_close($oCurl); //关闭一个cURL会话
//        var_dump(htmlspecialchars($sContent));die;
        return $sContent; //返回结果
    }

3.编写生成word文件工具类.

public function ToWord()
    {
        $phpWord = new PhpWord();//实例化对象
//        $request = request()->param();
        $PHPWordHelper = new Font();
        $section = $phpWord->addSection();//新增一个空白页
        $pro = $phpWord->getDocInfo();
        $date = date("Y-m-d", time() - 24 * 3600);
        $pro->setTitle($date . '的数据');// 标题
//        $phpWord->addTitle($date.'的数据',array('color'=>'FF0000', 'size'=>14,'align'=>'center'));// 标题
        $pro->setCreated(time());     // 创建时间
        $fontStyle = array('size' => 11, 'align' => 'left');
        $titleStyle = array('size' => 12, 'align' => 'left');
//        'indentation' => array( // 首行缩进
//            'firstLine' => $PHPWordHelper->pointSizeToTwips(32)
//        )
        $phpWord->addFontStyle('myOwnStyle', $fontStyle);
        $phpWord->addFontStyle('myTitleStyle', $titleStyle);

        $topTitleStyle = array('color' => 'FF0000', 'size' => 13, 'align' => 'center', 'indent' => 1,);
        $phpWord->addFontStyle('myTopTitleStyle', $topTitleStyle);
      
        $section->addText(
            'xxx', 'myTopTitleStyle',['align' => 'center']
        );

        $section->addText(
            'xxx', 'myTitleStyle'
        );//添加一个段落文字
        $region = $this->TenderingInfo('xxx');
        $section->addText(
            'xxx:', 'myOwnStyle'
        );
        $section->addText(
            $region['areaNameNum']
        );

        $section->addText(
            'xxx:', 'myOwnStyle'
        );
        $section->addText(
            $region['buyMethodNum']
        );
//        $section->addTextBreak(1);

        $section->addText(
            'xxxxx:', 'myOwnStyle'
        );
        $section->addText(
            $region['buyTypeNum']
        );
        $section->addTextBreak(1);
 
        $section->addText(
            'xxxx', 'myTitleStyle'
        );//添加一个段落文字
        $region = $this->TenderingInfo('xxx');
        $section->addText(
            'x:', 'myOwnStyle'
        );
        $section->addText(
            $region['areaNameNum']
        );

        $section->addText(
            'xxxx:', 'myOwnStyle'
        );
        $section->addText(
            $region['buyMethodNum']
        );
//        $section->addTextBreak(1);

        $section->addText(
            'xxxx:', 'myOwnStyle'
        );
        $section->addText(
            $region['buyTypeNum']
        );
        $section->addTextBreak(1);


        // xxxx报告
        $section->addText(
            'xxxx报告', 'myTopTitleStyle',['align' => 'center']
        );
        $saleData = $this->salesReport();
        $tableStyle = array(
            'borderSize' => 6,
            'borderColor' => '006699'
        );
                // word 表格样式
        $table = $section->addTable($tableStyle);
        $fancyTableCellStyle = array('valign' => 'center');
        $table->addRow(500);
        $thStyle['size'] = 10;
        $thStyle['color'] = 'FF0000';
        $paraStyle['align'] = 'center';
        $table->addCell(2000, $fancyTableCellStyle)->addText('部门名称', $thStyle, $paraStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('总人数', $thStyle, $paraStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('登录人数', $thStyle, $paraStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('操作人数', $thStyle, $paraStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('分配数量', $thStyle, $paraStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('数量', $thStyle, $paraStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('人员占比', $thStyle, $paraStyle);

        $tdStyle['size'] = 10;
        $fancyTableCellStyle['bgColor'] = 'D3D3D3';
        foreach ($saleData as $sKey => $sVal) {
            $table->addRow(500);
            $table->addCell(2000, $fancyTableCellStyle)->addText($sVal['department_name'], $tdStyle, $paraStyle);
            $table->addCell(2000, $fancyTableCellStyle)->addText($sVal['total_people_num'], $tdStyle, $paraStyle);
            $table->addCell(2000, $fancyTableCellStyle)->addText($sVal['total_login_num'], $tdStyle, $paraStyle);
            $table->addCell(2000, $fancyTableCellStyle)->addText($sVal['action_people_num'], $tdStyle, $paraStyle);
            $table->addCell(2000, $fancyTableCellStyle)->addText($sVal['business_num'], $tdStyle, $paraStyle);
            $table->addCell(2000, $fancyTableCellStyle)->addText($sVal['zhogbiao_num'], $tdStyle, $paraStyle);
            $table->addCell(2000, $fancyTableCellStyle)->addText('登录:'.$sVal['login_rate'] . '<w:br/>' . '操作:'.$sVal['action_rate'], $thStyle, $paraStyle);
        }

        ob_end_clean();
        ob_start();
        $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
        header("Content-Type: application/doc");
        header("Content-Disposition: attachment; filename=" . date("YmdHis") . ".doc");//设置导出保存的文件名
        $day = date("Y-m-d", time());
        if (!is_dir('temp')) {
            @mkdir('temp');
        }
        $objWriter->save('temp/' . $day . '.doc');//"php://output"-用于本地测试 通过postman请求保存文件到本地
        ob_end_flush();
    }

大坑提示:
*//坑 word表格样式 表格一列中换行显示 . ‘<w:br/>’

4.crontab 定时任务编写

首先写个sh文件放在项目根目录就行。。。。

#!/bin/bash
PATH=/usr/local/php/bin:/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
cd /var/www/xxx&&php think xxxx

开发小技巧
写好了1,2,3步,在本地先测试下是否通了。。cmd项目目录 输入命令即可

在这里插入图片描述

然后重启下cron,然后查看日志或者收到通知表示成功了。。。,

发布了31 篇原创文章 · 获赞 6 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章