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,然後查看日誌或者收到通知表示成功了。。。,