PHP 微信公众号真正正确的客服头像上传

首先我们来看官方文档

这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) {
    }

 

看看别人的介绍 很清楚指出 文件类型 和文件名称都是需要的 

 

转载于:https://www.cnblogs.com/lt-com/p/8073947.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值