上传图片到微信服务器获得media_id和url (永久性)
其他接口类:https://www.cnblogs.com/gjw-hsf/p/7375261.html
转载地址:https://blog.csdn.net/httIsAWang/article/details/71576880
请求方式为表单/post; 请求url: http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE 如果是本地选择图片并上传可能需要上传到服务器并在服务端进行post;
0、先是获取token;
function get_token($id, $s){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=‘$id‘&secret=‘$s‘"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $jsoninfo = json_decode($output, true); $token = $jsoninfo["access_token"]; return $token; }
1、获取media_id和url
function uploadImg($token, $filepath){ $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=image"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_NOBODY, 0); //只取body头 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //发送 POST 请求 curl_setopt($ch, CURLOPT_POST, true); //全部数据使用HTTP协议中的 "POST" 操作来发送。 $data = array(‘media‘=>‘@‘.$filepath); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $res = curl_exec( $ch ); curl_close( $ch ); if($res){ //$res = json_decode($res,true); return $res; } else return null; }
结果:
文档:https://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html
测试工具接口:https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E5%9F%BA%E7%A1%80%E6%94%AF%E6%8C%81&form=%E5%A4%9A%E5%AA%92%E4%BD%93%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E6%8E%A5%E5%8F%A3%20/media/upload