Safety Guest'T blog

  • 首页
  • 归档
  • 软件开发
  • 网络安全
  • 逆向破解
  • 人工智能
  • 资源分享
  • 区 块 链
  • 隐私政策
  • 友情链接

使用PHP对接Open Ai的文生图功能

  • Tz
  • 2023-05-09
  • 0

1.申请Key点击去申请.
2.复制下面代码到服务器(注意因为我使用的Tp6 所以有用到框架函数的自行替换)

php代码:


        
        $post = Request::post();
        $prompt = base_check_post_data($post, 'prompt');
        $api_key = "OPENAI_KEY";
        // 设置请求URL
        $url = "https://api.openai.com/v1/images/generations";

        // 设置请求参数
        $data = array(
            "prompt" => $prompt,
            "num_images" => 2,
            "size" => "256x256",
            "response_format" => "url"
        );

        // 将请求参数编码为JSON格式
        $json_data = json_encode($data);

        // 设置cURL选项
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "Authorization: Bearer " . $api_key
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 发送请求并获取响应
        $response = curl_exec($ch);
        curl_close($ch);

        // 解码JSON格式的响应
        $response_data = json_decode($response, true);
        
        if (!isset($response_data['data'][0]['url'])) {
            
            if(isset($response_data['error']['message'])){
                $result = [
                    'code' => 500,
                    'msg' => '获取失败'.json_encode($response_data),
                    'error'=>'您输入的关键词被系统禁用',
                    // 'error'=>$response_data['error']['message'],
                ];
            }else{
                $result = [
                    'code' => 500,
                    'msg' => '获取失败'.json_encode($response_data),
                    'error'=>'网络错误请重试~',
                ];
            }
            
        }else{
            $result = [
                'code' => 200,
                'msg' => '成功',
                'data' => $response_data['data'],
            ];
        }
        
        return json_encode($result);
   
© 2025 Safety Guest'T blog
Theme by Wing
渝ICP备 2021011909号 渝公网安备 50019002502382号
  • {{ item.name }}
  • {{ item.name }}