Upload.php 1.5 KB
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/26
 * Time: 16:46
 */

namespace app\home\controller;


use app\common\controller\WechatBase;
use EasyWeChat\Foundation\Application;

class Upload extends WechatBase
{
    public function fetImage()
    {

        $options = [
            'app_id' => config('wechat.app_id'),
            'secret' => config('wechat.secret'),
        ];
        $app = new Application($options);
        $accessToken = $app->access_token;
        $access_token = $accessToken->getToken();
        $media = $this->request->param('media');
        $file = $this->getMedia($access_token, $media, '/uploads/wechat_img/' . date('Ymd'));
        $this->success('SUCCESS','',$file);
    }
    private function getMedia($access_token, $media_id, $folderName)
    {
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" . $access_token . "&media_id=" . $media_id;
        if (!file_exists(".".$folderName)) {
            mkdir(".".$folderName, 0777, true);
        }
        $file_name = md5(uniqid(rand())) . '.png';
        $targetName = ".".$folderName . '/' . $file_name;
        $saveName = $folderName . '/' . $file_name;
        $ch = curl_init($url); // 初始化
        $fp = fopen($targetName, 'wb'); // 打开写入
        curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置,值是一个资源类型
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return $saveName;
    }
}