首先我们来看官方文档
这TM的搞笑呢 什么破玩意儿!
需要条件
1 需要有一个客服的账号 (废话)
2 一致jpg格式的图片(扯蛋)
完整流程
1 获取access_token
2获取账号
3 $url地址拼接
$url = 'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token=' . $access_token . '&kf_account=' . $kf_account;
4 使用curl 模拟 post 文件提交(重点)
5获取curl 返回判断
下面是代码
PHP 业务逻辑
/** * 设置微信头像 * @param $app_id * @param $kf_account * @param $file $_FILES 文件哈 * @return int|mixed */ public static function upload_head_img($app_id, $kf_account, $file) { $access_token = self::get_access_token($app_id); $url = 'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token=' . $access_token . '&kf_account=' . $kf_account; $path = $file['tmp_name']; //文件地址 $type = $file['type']; //文件类型 只支持 jpg类型的 image/jpg | image/jpeg 的注意 $file_name = $file['name']; //文件名 $result = wx_tools::curl_post_file($url, $path, $type, $file_name); return $result; }
curl 模拟提交
/** * 使用curl 文件上传 版本大于5.5 * @param $url * @param $file_name * @param $type * @param $path * @return int|mixed */ public static function curl_post_file($url, $path, $type, $file_name) { $curl = curl_init(); curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); $data = ['file' => new \CURLFile($path, $type, $file_name)]; curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_USERAGENT, "TEST"); $result = curl_exec($curl); $status = curl_getinfo($curl); if (intval($status["http_code"]) == 200) { curl_close($curl); return $result; } $error = curl_errno($curl); curl_close($curl); return $error; }
值得注意一点 因为PHP 版本大于5.5 之后不能够在使用@文件的方式传输
只能够实例化 CURLFile这个文件类 但是很坑的一点就是那些所谓的网上文档全是错误的
他们所有的写法 都是 $file = new \CURLFile($file_name);
但是我在使用的时候curl 执行一直是false
我们来看这个类的源码
/** * Create a CURLFile object * @link http://www.php.net/manual/en/curlfile.construct.php * @param string $filename <p>Path to the file which will be uploaded.</p> * @param string $mimetype [optional] <p>Mimetype of the file.</p> * @param string $postname [optional] <p>Name of the file.</p> * @since 5.5.0 */ function __construct($filename, $mimetype, $postname) { }
看看别人的介绍 很清楚指出 文件类型 和文件名称都是需要的