【Coze】Coze JWTOAuth对接

package com.jpaas.coze;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.coze.openapi.client.auth.OAuthToken;
import com.coze.openapi.service.auth.JWTOAuth;
import com.coze.openapi.service.auth.JWTOAuthClient;
import com.coze.openapi.service.service.CozeAPI;

/*
This example is about how to use the service jwt oauth process to acquire user authorization.

Firstly, users need to access https://www.coze.com/open/oauth/apps. For the cn environment,
users need to access https://www.coze.cn/open/oauth/apps to create an OAuth App of the type
of Service application.
The specific creation process can be referred to in the document:
https://www.coze.com/docs/developer_guides/oauth_jwt. For the cn environment, it can be
accessed at https://www.coze.cn/docs/developer_guides/oauth_jwt.
After the creation is completed, the client ID, private key(.pem), and public key id, can be obtained.
For the client secret and public key id, users need to keep it securely to avoid leakage.
* */
public class JWTOAuthServer {

    public static void main(String[] args) {

        // The default access is api.coze.com, but if you need to access api.coze.cn,
        // please use base_url to configure the api endpoint to access
        String cozeAPIBase = System.getenv("COZE_API_BASE");
        if (cozeAPIBase == null || cozeAPIBase.isEmpty()) {
            cozeAPIBase = "api.coze.cn";
        }
        String jwtOauthClientID = System.getenv("COZE_JWT_OAUTH_CLIENT_ID");
        String jwtOauthPrivateKey = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY");
        String jwtOauthPrivateKeyFilePath = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY_FILE_PATH");
        String jwtOauthPublicKeyID = System.getenv("COZE_JWT_OAUTH_PUBLIC_KEY_ID");
        //    jwtOauthPublicKeyID+="123";
        JWTOAuthClient oauth = null;
        try {
            jwtOauthPrivateKey =
                    new String(
                            Files.readAllBytes(Paths.get(jwtOauthPrivateKeyFilePath)), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

    /*
    The jwt oauth type requires using private to be able to issue a jwt token, and through
    the jwt token, apply for an access_token from the coze service. The sdk encapsulates
    this procedure, and only needs to use get_access_token to obtain the access_token under
    the jwt oauth process.
    Generate the authorization token
    The default ttl is 900s, and developers can customize the expiration time, which can be
    set up to 24 hours at most.
    * */
        try {
            oauth =
                    new JWTOAuthClient.JWTOAuthBuilder()
                            .clientID(jwtOauthClientID)
                            .privateKey(jwtOauthPrivateKey)
                            .publicKey(jwtOauthPublicKeyID)
                            .baseURL(cozeAPIBase)
                            .build();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try {
            OAuthToken resp = oauth.getAccessToken();
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    /*
    The jwt oauth process does not support refreshing tokens. When the token expires,
    just directly call get_access_token to generate a new token.
    * */
        CozeAPI coze =
                new CozeAPI.Builder()
                        .auth(JWTOAuth.builder().jwtClient(oauth).build())
                        .baseURL(cozeAPIBase)
                        .build();
        // you can also specify the scope and session for it
    }
}

package example.workflow;

import java.util.HashMap;
import java.util.Map;

import com.coze.openapi.client.workflows.run.RunWorkflowReq;
import com.coze.openapi.client.workflows.run.RunWorkflowResp;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.service.CozeAPI;

/*
This example describes how to use the workflow interface to chat.
* */
public class RunWorkflowExample {

  public static void main(String[] args) {
    // Get an access_token through personal access token or oauth.
    String token = System.getenv("COZE_API_TOKEN");
    TokenAuth authCli = new TokenAuth(token);

    // Init the Coze client through the access_token.
    CozeAPI coze =
        new CozeAPI.Builder()
            .baseURL(System.getenv("COZE_API_BASE"))
            .auth(authCli)
            .readTimeout(10000)
            .build();
    ;

    String workflowID = System.getenv("WORKFLOW_ID");

    // if your workflow need input params, you can send them by map
    Map<String, Object> data = new HashMap<>();
    data.put("param name", "param values");
    RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build();

    RunWorkflowResp resp = coze.workflows().runs().create(req);
    System.out.println(resp);
  }
}
<think>好的,用户想了解如何将Coze API与Web进行对接,并需要教程、示例和代码。首先,我需要确认用户所说的Coze API具体指什么。因为“Coze”可能有不同的含义,比如某个特定公司的API或者开源项目。假设这里指的是一个假设的第三方服务,类似于其他RESTful API服务,比如发送消息或处理数据。 接下来,用户需要对接Web的教程。通常,Web对接涉及前端和后端的交互。可能需要使用JavaScript在前端调用API,或者在后端服务器(如Node.js、Python等)中处理API请求。由于用户提到示例代码,我需要提供前后端的示例。 需要考虑API认证方式,常见的如API密钥、OAuth等。假设Coze API使用API密钥,需要在请求头中携带。例如,在JavaScript中使用fetch,或在Python中使用requests库发送请求。 然后,用户可能需要分步骤的教程:注册获取API密钥、安装必要的库、编写请求代码、处理响应和错误。同时,示例代码需要符合最佳实践,比如环境变量保存密钥,错误处理机制。 另外,确保示例代码的语法正确,比如Python的缩进、JavaScript的async/await用法。还要考虑跨域问题(CORS),如果前端直接调用API,可能需要配置代理或后端中转。 用户可能遇到的问题包括认证失败、参数错误、网络问题等,应该在教程中提及常见问题解决方法。例如检查API密钥、验证参数格式、使用try-catch处理异常。 最后,生成相关问题,帮助用户深入理解,比如如何优化API调用、处理分页数据、保障安全性等。 总结步骤:介绍准备工作、提供前后端代码示例、说明注意事项和常见问题,最后生成相关问题。确保回答结构清晰,代码正确,覆盖用户需求。</think>### Coze API与Web对接教程 通过四个步骤实现Coze API的Web对接,以消息发送接口为例演示完整流程: 一、准备工作 1. 登录Coze开发者平台创建应用 2. 在「API管理」模块获取`API_KEY` 3. 确认接口文档中的请求格式和参数要求 二、前端调用示例(JavaScript) ```javascript async function sendCozeMessage(content) { const API_ENDPOINT = 'https://api.coze.com/v1/messages'; try { const response = await fetch(API_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.COCE_API_KEY}` }, body: JSON.stringify({ content: content, session_id: 'user-123' }) }); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return await response.json(); } catch (error) { console.error('API调用失败:', error); } } ``` 三、后端代理示例(Python Flask) ```python from flask import Flask, request, jsonify import requests app = Flask(__name__) API_KEY = "your_api_key_here" @app.route('/send-message', methods=['POST']) def proxy_coze(): try: payload = request.json headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } response = requests.post( "https://api.coze.com/v1/messages", json=payload, headers=headers ) response.raise_for_status() return jsonify(response.json()), 200 except requests.exceptions.RequestException as e: return jsonify({"error": str(e)}), 500 ``` 四、注意事项 1. 安全存储API密钥(推荐使用环境变量) 2. 生产环境需启用HTTPS加密传输 3. 实施请求频率限制(建议使用漏桶算法)[^1] 4. 建议添加请求签名验证机制
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星星点点洲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值