爱意满满的作品展示区。
go522000

云函数写了一个 api.openai.com 接口中转( PHP 代码)

  •  
  •   go522000 · Mar 11, 2023 · 1429 views
    This topic created in 1199 days ago, the information mentioned may be changed or developed.

    之前使用 ChatGPT 尝试翻译一些短句,比百度翻译好用多了。前几天刚好在 twitter 上看到有大神写了一个 chrome 插件,尝试一下很好用(插件名字叫 OpenAI Translator )。

    家里有一台笔记本没有安装翻墙软件,就想着使用自己的服务器来中转一下,今天把代码迁移腾讯云的云函数上,效果也不错。

    代码比较粗糙,没有进行权限验证等,要注意安全。另外,腾讯云云函数前 3 个月有免费额度,之后是按每月约 12.8 元基础套餐扣费,如果用得少的话,可以改为 Cloudflare Worker ,每月都有免费额度。

    分享给大家共同讨论学习。

    =====

    ray-so-export.png

    =====

    // 怎么分享代码呢?就几行代码觉得没必要上传到 github 上。

    <?php
    header("Content-Type: application/json; charset=utf-8");
    
    // 直接转发,无权限验证,注意安全问题!!!
    $url     = 'https://api.openai.com'. str_ireplace('/release', '', $_SERVER ['PHP_SELF']);
    $data    = file_get_contents('php://input');
    $headers = [
        'authorization: Bearer 这里要改为 API KEY',
        'Content-Type: application/json; charset=utf-8',
        'Content-Length:' . strlen($data),
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    
    echo $response;
    
    
    Supplement 1  ·  Mar 13, 2023
    不知道腾讯云的云函数有什么毛病,第一天还好好的,代码也没修改,第二天居然报 CORS 错误。
    需要加上以下代码:
    ```

    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Methods: *');
    header('Access-Control-Allow-Headers: accept, content-type');
    header('Access-Control-Allow-Credentials: true');

    ```
    1 replies    2023-03-12 09:16:04 +08:00
    ninvfeng
        1
    ninvfeng  
    PRO
       Mar 12, 2023 via Android
    支持一下👍,有服务器的话用 nginx 做反向代理也方便
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4055 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 92ms · UTC 05:16 · PVG 13:16 · LAX 22:16 · JFK 01:16
    ♥ Do have faith in what you're doing.