class Material extends Controller
{
//微信素材相关url
private $materialUrl = [
//上传素材列表
'upload' => 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=type',
//计算总数
'calculateTotal' => 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=',
//获取列表
'materialList' => 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=',
];
//全局TOKEN
private $globalToken = '';
private $totalKey = 'WechatMaterialTotal';
//获取素材列表
public function getMaterial()
{
$page = $this -> request -> param('page', 1,'intval');
//获取素材类型
$type = $this -> request -> param('type', 'image');
$requestData = [
'type' => 'image',
'offset' => (1 - $page) * 20,
'count' => 20,
];
echo self::httpsRequest($this->materialUrl['materialList'] . $this -> globalToken, json_encode($requestData));
}
public function uploadMaterial() {
if($this->request->isPost()) {
$file = $this -> request -> file('file');
//tmp_name 文件的绝对路径
//type 文件类型
//name 文件名称
$data = ['media'=> new \CURLFile($file->getInfo('tmp_name'), $file->getInfo('type'), $file->getInfo('name'))];
echo self::httpsRequest($this->materialUrl['upload'], $data);
}
}
private function httpsRequest($url, $data = null,$time_out=60,$out_level="s",$headers=array())
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
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);
}
if($out_level=="s") {
//超时以秒设置
curl_setopt($curl, CURLOPT_TIMEOUT,$time_out);//设置超时时间
} elseif ($out_level=="ms") {
curl_setopt($curl, CURLOPT_TIMEOUT_MS,$time_out); //超时毫秒,curl 7.16.2中被加入。从PHP 5.2.3起可使用
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if($headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//如果有header头 就发送header头信息
}
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
public function httpGet($url, $header = '') {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
if(!empty($header)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
}
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
}