这是一个临时材质插槽,只能存在3天。 目前小程序不支持永久素材上传,仅公众号支持。
public function uploadWxMedia(){ $token = $this->get_accessToken(); $type = "image"; $filepath = Env::get('root_path').'public\assets\imageName.png'; //文件在服务器的绝对路径,按自己存放位置修改 $data = array("media"=>new CURLFile($filepath)); //php5.6以上必须用这种方法上传文件 $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=".$type; $action = new Action(); //封装的curl方法,看附录 $result = $action->curl_post($url,$data); print_r($result); } //调用微信api,获取access_token,有效期7200s public function get_accessToken(){ $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的秘钥'; //替换成自己的小程序id和secret $res = file_get_contents($url); $data = json_decode($res,true); $token = $data['access_token']; return $token; }
访问uploadWxMedia()方法会上传设置的图片并返回一个json数据:
{“类型”:“图像”,“media_id”:“LTbNsi****************JqG”普通php网站封装小程序普通php网站封装小程序,“created_at”:1558062553}
media_id用于填写第二步回复图片中的值
附录
打包卷曲方法
namespace think; class Action { //get方式请求接口 public function get_json($url) { $data = file_get_contents($url); //转换成数组 $data = json_decode($data,true); //输出 return $data; } //post方式请求接口 public function curl_post($url,$data,$headers = null) { //$data 是一个 array() 数组;未编码 $curl = curl_init(); // 启动一个CURL会话 if(substr($url,0,5)=='https'){ // 跳过证书检查 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //只有在CURL低于7.28.1时CURLOPT_SSL_VERIFYHOST才支持使用1表示true,高于这个版本就需要使用2表示了(true也不行)。 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); if($headers != null){ //post请求中携带header参数 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); } //返回api的json对象 $response = curl_exec($curl); //关闭URL请求 curl_close($curl); //返回json对象 return $response; } }