文档:https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Permanent_Assets.html
第一步:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传素材</title>
</head>
<body>
<form action="/wxmenu/uploadImage" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="media" id="">
<input type="submit" value="提交素材">
</p>
</form>
</body>
</html>
第二步:
在wxmenu的控制器中添加方法
public function action_uploadImage(){
$files = $_FILES['media'];
// 得到扩展名
$extname = pathinfo($files['name'], PATHINFO_EXTENSION);
//上传到服务器的路径
$url = '/upload/banner/';
$name = time().'.'.$extname;
$realpath = $url.$name;
move_uploaded_file($files['tmp_name'], $realpath);
echo $this->uploadMaterial($realpath);
}
private function uploadMaterial($path)
{
$upload_url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".Utils::get_access_token()."&type=image";
$json = $this->http_request_post($upload_url, [], $path);
// json转为数组
$arr = json_decode($json, true);
p($arr);
return $arr['media_id'];
}
private function http_request_post($url, $data, $file='')
{
if(!empty($file))
{
$data['media'] = new CURLFile($file);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
//判断有无出错
if (curl_errno($curl) > 0)
{
echo curl_error($curl);
$output = 'http请求出错!'.'['.curl_error($curl).']';
}
curl_close($curl);
return $output;
}
获取access_token
public static function get_access_token()
{
$redis = new Redis();
$redis->connect('127.0.0.1', 7001);
$redis->auth('123456');
$time = $redis->ttl('access_token');
if($time > 0){
$access_token = $redis->get('access_token');
}else{
$appid = "123456"; //需替换成你的appID
$appsecret = "123456"; //需替换成你的appsecret
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&"."appid=$appid&secret=$appsecret";
$output = Utils::https_request($url);
$jsoninfo = json_decode($output, true);
$access_token = $jsoninfo["access_token"];
$redis->setex('access_token',7200,$access_token);
}
return $access_token;
}
亲测可用!!!