微信公众号新增永久图片素材的接口是:
https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=image
一定要却保公众号的AppId和AppSecret正确 现在开始获取图片的media媒体文件:
$data['media'] = new \CURLFile(realpath('这里是你要新增图片素材在服务器的绝对路径.jpg'));然后直接用post请求接口即可,一定不要手贱把$data数据进行转成json格式,不然就会出现41005,media data missing问题,直接数组格式数据请求即可; 完整代码:
//先把access_token在redis存两个小时,当然存数据库也可以 $redis = new \Redis(); $redis->connect(config('redis.host'), config('redis.port'), 5); //连接redis 超过5秒放弃 $redis->auth(config('redis.password')); $access_token = $redis->get('access_token'); if($access_token==false){ $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$routineAppId."&secret=".$routineAppSecret; $token=file_get_contents($url); $token=json_decode($token,true); $access_token=$token['access_token']; $redis->set('access_token',$access_token,7200); } //新增加公众永久素材 $post_url='https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$access_token.'&type=image'; $obj = new \CURLFile(realpath('/www/wwwroot/thinkphp_download/public/977ee96bb94326d1265013aae648969.jpg')); $data['media'] = $obj; $data['type'] = 'image'; $send=$this->https_request($post_url,$data); dump(json_decode($send,true)); //https请求(支持GET和POST) public function https_request($url,$data=null) { $ch = curl_init(); $params[CURLOPT_URL] = $url; //请求url地址 $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息 $params[CURLOPT_SSL_VERIFYPEER] = false; $params[CURLOPT_SSL_VERIFYHOST] = false; $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回 $params[CURLOPT_POST] = true; $params[CURLOPT_POSTFIELDS] = $data; curl_setopt_array($ch, $params); //传入curl参数 $content = curl_exec($ch); //执行 curl_close($ch); //关闭连接 return $content; }