快手开放平台对接内容管理demo

其中包括用户授权,获取accessToken,获取用户信息,自动上传视频,发布视频,视频列表,删除视频等

<?php
namespace app\controller;

use app\BaseController;
use think\Exception;
use think\facade\App;

class KuaiShou extends BaseController
{

    private $accessToken = "";
    private $appId = "";
    private $appSecret = "";

    private $uploadToken; // 上传令牌
    private $endpoint;//上传网关的域名
    
    private $redirectUri = '';


    /**
     * 用户授权
     * */
    public function authorize($name = 'ThinkPHP6')
    {
        // 要请求的 URL
        $url = 'https://open.kuaishou.com/oauth2/authorize?';
        $params = [
            'app_id'                    => $this->appId,  // 应用唯一标识
            'scope'                     => 'user_info,user_base,user_video_publish,user_video_delete,user_video_info', // code
            'response_type'             => 'code',
            'redirect_uri'              => $this->redirectUri,// 应用授权作用域,多个授权作用域以英文逗号(,)分隔
            'state'                     => '123456789', //安全参数,标识和用户或者设备相关的授权请求。建议开发者实现。回调的时候会带回。
            'ua'                        => 'pc', // 运行环境,普通网页传pc, H5网页不传此参数即可
        ];
        //

        // 调用 CURL GET 请求方法
        $result = $this->performCurlGetRequestWithParameters($url,$params);
        exit;

    }


    /**
     * 获取access_token
     * */
    public function getAccessToken()
    {
        $url = "https://open.kuaishou.com/oauth2/access_token?";
        $data = [
            'app_id' => $this->appId,
            'app_secret' => $this->appSecret,
            'code' => 'b0881372a93aa4434335c4d3e9a1773dcc8cd759c65b965a727a6ec18b85699867841685',
            'grant_type' => 'authorization_code',
        ];

        $result = $this->performCurlGetRequestWithParameters($url,$data);
        dd($result);

    }

    /**
     * 刷新token
     * */
    public function refreshAccessToken()
    {
        $url = "https://open.kuaishou.com/oauth2/refresh_token?";
        $data = [
            'app_id' => $this->appId,
            'app_secret' => $this->appSecret,
            "refresh_token" => "ChJvYXV0aC5yZWZyZXNoVG9rZW4SoAEWZ1a48M_hdbBMnUf1R2Tep9mcpFOllaVLX_uHdVL-1D7pLxV1PrdS-cy44h1ecc8LaWeyA6By76joHJXUE8LHnPjWSq1lotOS1a4GczDxoDo9bAzkoln3lGdTxh3OaHkuXUAPku_IW7H7ql81DPORYZmVK6RQHNb3EVkLBuelvp9nxTwThxZxUYe1LZcMsKGAsbFrXtfMaIhrXclDfIVTGhJmpGi_HIZyL3299lSodYIPN3UiIInoA_U1haHPefAICe8rsnU1-tjTZu3NxcCPR3vzLlERKAUwAQ",
            'grant_type' => 'refresh_token',
        ];

        $result = $this->performCurlGetRequestWithParameters($url,$data);
        dd($result);
    }

    /**
     * 获取用户信息
     * */
    public function getUserInfo()
    {
        $url = "https://open.kuaishou.com/openapi/user_info?";
        $data = [
            'app_id' => $this->appId,
            'access_token' => $this->accessToken
        ];

        $result = $this->performCurlGetRequestWithParameters($url,$data);
        dd($result);
    }

    /**
     * 获取用户手机号码
     * */
    public function getUserPhone()
    {
        $url = "https://open.kuaishou.com/openapi/user_phone?";
        $data = [
            'app_id' => $this->appId,
            'access_token' => $this->accessToken
        ];

        $result = $this->performCurlGetRequestWithParameters($url,$data);
        dd($result);
    }

    /**
     * 发起上传
     * */
    public function startUpload()
    {
        $url = "https://open.kuaishou.com/openapi/photo/start_upload?";
        $data = [
            'app_id' => $this->appId,
            'access_token' => $this->accessToken
        ];
        $params = '';
        foreach ($data as $key => $val) {
            $params .= "$key=$val&";
        }
        $url .= rtrim($params, '&');

        $res = $this->sendPostRequest($url);
        $res = json_decode($res, true);
        if ($res['result'] == 1) {
            $this->uploadToken = $res['upload_token'];
            $this->endpoint = $res['endpoint'];
        }
    }

    /**
     * 视频上传 FormData
     * */
    public function uploadForFormData()
    {
        $basePath = App::getBasePath();
        // 构造runtime文件夹的完整路径
        $runtimePath = $basePath . '../runtime/storage/';;

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        // 上传到本地服务器
        $savename = \think\facade\Filesystem::putFile( 'topic', $file);

        $url = "http://{$this->endpoint}/api/upload/multipart?upload_token={$this->uploadToken}";

        $file_path = $runtimePath.$savename;
        $result = $this->sendPostFileRequest($url, $file_path);
        dd($result);
    }

    /**
     * body二进制 视频上传
     * */
    public function uploadForBinaryData()
    {
        $basePath = App::getBasePath();
        // 构造runtime文件夹的完整路径
        $runtimePath = $basePath . '../runtime/storage/';;

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 上传到本地服务器

        $savename = \think\facade\Filesystem::putFile( 'topic', $file);

        $url = "http://{$this->endpoint}/api/upload?upload_token={$this->uploadToken}";

        $file_path = $runtimePath.$savename;

        $result = $this->sendPostBinaryDataRequest($url, $file_path);

        dd($result);
    }

    /**
     * 分片上传
     * */
    public function uploadFragment()
    {

        $basePath = App::getBasePath();
        // 构造runtime文件夹的完整路径
        $runtimePath = $basePath . '../runtime/storage/';;

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::putFile( 'topic', $file);
        $file_path = $runtimePath.$savename;
        
        // 使用示例
        $chunkSize = 1024 * 1024 * 2; // 分片大小,例如:1MB
        $chunks = $this->splitFileIntoChunks($file_path, $chunkSize);

        $is_file = false;
        foreach ($chunks as $k => $chunk) {
            // 对每个分片进行处理,例如上传到服务器或写入到另一个文件
            $url = "http://{$this->endpoint}/api/upload/fragment?fragment_id={$k}&upload_token={$this->uploadToken}";
            $result = $this->sendPostBinaryDataRequest($url, $chunk, $is_file);
        }
        echo $k;
    }

   /**
    * 断点续传
    * */
    public function uploadResume()
    {
        $endpoint = "upload.kuaishouzt.com";
        $url = "http://{$endpoint}/api/upload/resume?upload_token={$this->uploadToken}";

        $this->performCurlGetRequestWithParameters($url);
    }

    /**
     * 完成分片上传
     * */
    public function uploadComplete()
    {
        $fragment_count = 10;
        $url = "http://{$this->endpoint}/api/upload/complete?upload_token={$this->uploadToken}&fragment_count={$fragment_count}";

        $this->sendPostRequest($url);
    }

    function splitFileIntoChunks($filePath, $chunkSize) {
        $fileHandle = fopen($filePath, 'rb'); // 以二进制读取模式打开文件
        if ($fileHandle === false) {
            return false;// 如果文件打开失败,返回false
        }
        $chunks = [];
        while (!feof($fileHandle)) {
            $buffer = fread($fileHandle, $chunkSize);
            // 读取文件的一个片段
            if ($buffer === false) {
                break;// 如果读取失败,跳出循环
            }
            $chunks[] = $buffer; // 将片段添加到数组中
        }
        fclose($fileHandle); // 关闭文件句柄

        return $chunks;// 返回包含所有片段的数组
    }


    /**
     * 发布视频
     * */
    public function publish()
    {
        $basePath = App::getBasePath();
        // 构造runtime文件夹的完整路径
        $runtimePath = $basePath . '../runtime/storage/';;

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        // 上传到本地服务器
        $savename = \think\facade\Filesystem::putFile( 'topic', $file);
        $file_path = $runtimePath.$savename;

        $url = "https://open.kuaishou.com/openapi/photo/publish?";
        $data = [
            'app_id' => $this->appId,
            'access_token' => $this->accessToken,
            'upload_token' => $this->uploadToken,
        ];

        $params = '';
        foreach ($data as $key => $val) {
            $params .= "$key=$val&";
        }
        $url .= rtrim($params, '&');

        $title = "分片";
        $res = $this->sendPostFileRequest1($url,$file_path,$title);
        dd($res);
    }

    /**
     * 查询用户视频列表
     * */
    public function userVideoList()
    {
        $url = "https://open.kuaishou.com/openapi/photo/list?";
        $data = [
            'access_token'	=> $this->accessToken,
            'app_id'	=> $this->appId
        ];

        $this->performCurlGetRequestWithParameters($url, $data);
    }


    /**
     * 删除视频
     * */
    public function deleteVideo()
    {
        $url = "https://open.kuaishou.com/openapi/photo/delete?";

        $data = [
            'access_token'	=> $this->accessToken,
            'app_id'	=> $this->appId,
            'photo_id' => '3xurpbkusbyh6hw'
        ];

        $params = '';
        foreach ($data as $key => $val) {
            //if ($key=='redirect_uri') $val = urlEncode($val);
            $params .= "$key=$val&";
        }
        $url .= rtrim($params, '&');

        $res = $this->sendPostRequest($url);
        dd($res);
    }

    /**
     * params string $url 请求的url
     * $file_path 文件路径
     * */
    public function sendPostFileRequest1($url,$file_path, $title)
    {
        // 初始化cURL会话
        $ch = curl_init();
        // 设置目标URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 启用POST方法,并设置请求体的类型为multipart/form-data
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(
            'cover' => new \CURLFile($file_path),
            'caption' => $title
        ));

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 为cURL会话设置适当的请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        // 设置cURL选项,以便将响应结果直接作为字符串返回,而不是输出到浏览器
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // 执行cURL请求并获取结果
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
        }

        // 关闭cURL会话
        curl_close($ch);// 输出响应结果echo $response;

        return $response;
    }


    public function sendPostBinaryDataRequest($url, $binaryData, $is_file = true)
    {
        // 初始化cURL会话
        $ch = curl_init();
        // 设置目标URL,替换{endpoint}为实际的服务器地址

        // 设置请求头
        $headers = array('Content-Type: video/mp4');
        if ($is_file) {
            // 准备二进制数据,这里假设$binaryData是文件的二进制内容
            $binaryData = file_get_contents($binaryData);
        }

        // 替换为实际的文件二进制内容
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $binaryData);

        // 设置cURL选项,以便将响应结果直接作为字符串返回,而不是输出到浏览器
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行cURL请求
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if(curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
        }
        // 关闭cURL会话
        curl_close($ch);

        // 输出响应结果
        return $response;
    }


    public function sendPostFileRequest($url,$file_path )
    {
        // 初始化cURL会话
        $ch = curl_init();
        // 设置目标URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 启用POST方法,并设置请求体的类型为multipart/form-data
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(
            'file' => new \CURLFile($file_path),
        ));

        // 为cURL会话设置适当的请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        // 设置cURL选项,以便将响应结果直接作为字符串返回,而不是输出到浏览器
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // 执行cURL请求并获取结果
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
        }

        // 关闭cURL会话
        curl_close($ch);// 输出响应结果echo $response;

        return $response;
    }

    public function sendPostRequest($url, $data = array(), $headers = array()) {
        // 创建 curl 实例
        $ch = curl_init();

        // 设置请求 URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 设置 POST 请求方式
        curl_setopt($ch, CURLOPT_POST, 1);

        // 设置请求头为 application/json
        //$headers[] = "Content-Type: application/json";
        if ($data) {
            // 将数据以 JSON 格式发送
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 忽略 SSL 认证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        // 设置cURL选项,以便将响应结果直接作为字符串返回,而不是输出到浏览器
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // 执行 curl 请求
        $response = curl_exec($ch);

        // 获取响应代码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭 curl 连接
        curl_close($ch);

        return $response;
    }

    function performCurlGetRequestWithParameters($url, $parameters = []) {
        // 构建带有参数的 URL
        $params = '';
        foreach ($parameters as $key => $val) {
            //if ($key=='redirect_uri') $val = urlEncode($val);
            $params .= "$key=$val&";
        }
        $url .= rtrim($params, '&');
        header("Content-Type: application/json");
        header("Location: $url");
        die();
        var_dump($url);exit;
        // 执行 CURL GET 请求
        $this->performCurlGetRequest($url);

    }

    /**
     * 执行 CURL GET 请求的方法
     *
     * @param string $url 要请求的 URL
     * @return string 请求的结果
     */
    function performCurlGetRequest($url,$data = array()) {
        // 初始化 CURL
        $ch = curl_init();

        // 设置请求方式为 GET
        curl_setopt($ch, CURLOPT_HTTPGET, true);

        // 设置要请求的 URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 禁用 SSL 证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // 设置默认的头部信息
        $headers = [
            'Content-Type: application/json'
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 将数据以 JSON 格式发送
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // 执行请求
        $result = curl_exec($ch);

        // 检查请求是否成功
        if (curl_errno($ch)) {
            // 处理请求失败的情况
            echo "CURL 请求失败: ". curl_error($ch);
            return;
        }

        // 关闭 CURL 连接
        curl_close($ch);
        // 返回请求结果

        return $result;
    }

}

相关推荐

  1. 快手开放平台对接内容管理demo

    2024-04-09 09:48:03       29 阅读
  2. 平台组成-内容管理

    2024-04-09 09:48:03       46 阅读
  3. 开源大数据管理平台

    2024-04-09 09:48:03       51 阅读
  4. Gradio——语音对话demo

    2024-04-09 09:48:03       41 阅读
  5. 开源大数据管理平台选型

    2024-04-09 09:48:03       49 阅读
  6. RASP技术相关内容DEMO实现

    2024-04-09 09:48:03       54 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 09:48:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 09:48:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 09:48:03       87 阅读
  4. Python语言-面向对象

    2024-04-09 09:48:03       96 阅读

热门阅读

  1. LISP学习历程

    2024-04-09 09:48:03       41 阅读
  2. AntPathMatcher路径匹配器

    2024-04-09 09:48:03       34 阅读
  3. Spring之底层架构核心概念解析

    2024-04-09 09:48:03       30 阅读
  4. 自然语言处理

    2024-04-09 09:48:03       31 阅读
  5. LeetCode笔记——1042.不邻接植花

    2024-04-09 09:48:03       36 阅读
  6. matlab 直方图及分布拟合

    2024-04-09 09:48:03       33 阅读
  7. NLP数据清洗:文本预处理

    2024-04-09 09:48:03       34 阅读
  8. 11. TypeScript 函数类型

    2024-04-09 09:48:03       36 阅读
  9. 安全运营中心(SOC)的核心功能

    2024-04-09 09:48:03       32 阅读