微信上传图片素材接口

微信官方文档,这个接口的media解释着实让人有点摸不着头脑(其实没啥用,这是解释文件信息里包含什么,不需要专门处理)

微信上传图片素材接口_第1张图片

搜索资料,写测试代码不断尝试,主要实现方式两种:

1.方式一是直接用curl,主要是用来测试接口参数怎么设置,能否调通微信接口:

$pathName = realpath('./111.png');

		$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESSTOKEN&type=image";
		$data = array(
			'media' => new CURLFile($pathName, 'image/png', '111.png')
		);
		$description = array(
			'title' => '111.png',
			'introduction' =>  '111.png',
		);
		$data['description'] = urldecode(json_encode($description));
		// $data = http_build_query($data);//上传文件使用curlfile不能使用http_build_query处理

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		@curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSLVERSION, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch);
		var_dump($data);

 需要注意的是要根据php版本选择上传文件的方式,可参考官网(截图如下)

微信上传图片素材接口_第2张图片

 2.方式二是使用GuzzleHttp实现上传:

        $pathName = realpath('./111.png');
		$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESSTOKEN&type=image";
		$description = array(
			'title' => '111.png',
			'introduction' =>  '111.png',
		);
		// $data['description'] = urldecode(json_encode($description));
        try{
            $client = new Client();
            $multipart = [
			        [
			            'name'     => 'media',
			            'contents' => fopen($pathName, 'r')
			        ],
			        [
			        	'name' => 'description',
			        	'contents' => urldecode(json_encode($description))
			        ]
			    ];
            $response = $client->request('POST', $url, [
            	'timeout' => 3,
                'multipart' => $multipart,
            ]);
            $response = json_decode($response->getBody(), true);
            var_dump($response);
        }catch(\Exception $e){
            echo $e->getMessage();
        }

你可能感兴趣的:(微信接口,php,公众号接口)