当前位置: 首页 > news >正文

COZE token刷新

coze个人版token有效期最多30天,升级团队版或企业版后可设置token为长期。

但是刷新token不是所有场景都适用,根据目前个人版权限,不支持工作流

刷新token需要创建OAuth应用,创建时应用类型选择渠道,下载证书。

在设置/发布渠道中选择企业自定义渠道管理,添加平台时可选择发布的渠道。

token刷新代码:

JWTServer

<?php
namespace app\index\server;class jwtServer {private $key = "";private $algo = "HS256";private $kid = "";public function __construct($kid, $key, $type = "str") {$this->kid = $kid;$this->setkey($key, $type);}public function setkey($key, $type = "str") {$usekey = false;if ($type == "file") {$file = $key;if (!is_file($file)) {throw new \Exception("file:" . $file . "not exist");}$usekey = file_get_contents($file);}if ($type == "str") {if (!is_string($key) || empty($key)) {throw new \Exception("set key error");}$usekey = $key;}if (empty($usekey)) {throw new \Exception("set key fail");}$resource = openssl_pkey_get_private($usekey);if (!$resource) {throw new \Exception("key is not private key");}$this->key = $usekey;}public function setalgo($algo) {$this->algo = $algo;}/*** 生成字符串*/public function generate($payload) {if (empty($this->key)) {throw new \Exception("key not set");}$header = $this->getHeader();$payload = $this->getPayload($payload);$signature = $this->getSignature($header, $payload);$token = $header . "." . $payload . "." . $signature;return $token;}private function getHeader() {if (empty($this->kid)) {throw new \Exception("kid is empty");}$typ = "JWT";$data = ["alg" => $this->algo,"typ" => $typ,"kid" => $this->kid,];$headerJson = json_encode($data);$headerBase64 = $this->base64UrlEncode($headerJson);return $headerBase64;}private function getPayload($payload) {$payloadJson = json_encode($payload);$payloadBase64 = $this->base64UrlEncode($payloadJson);return $payloadBase64;}private function getSignature($headerBase64, $payloadBase64) {// $sign = $this->getSignEncryption($headerBase64, $payloadBase64);$sign = $this->getSignEncryption2($headerBase64, $payloadBase64);$signBase64 = $this->base64UrlEncode($sign);return $signBase64;}/*** 签名加密 废弃*/private function getSignEncryption($headerBase64, $payloadBase64) {if (empty($this->key)) {throw new \Exception("key not set");}$algo = $this->algo;$signStr = $headerBase64 . "." . $payloadBase64;$sign = hash_hmac($algo, $signStr, $this->key, true);return $sign;}public function getSignEncryption2($headerBase64, $payloadBase64) {if (empty($this->key)) {throw new \Exception("key not set");}$key = $this->key;$signStr = $headerBase64 . "." . $payloadBase64;openssl_sign($signStr, $encrypted, $key, OPENSSL_ALGO_SHA256);return $encrypted;}/*** Base64URL编码*/private function base64UrlEncode($data) {return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');}/*** Base64URL解码*/private function base64UrlDecode($data) {return base64_decode(strtr($data, '-_', '+/'));}public function vertify($token) {$data = explode(".", $token);if (count($data) < 3) {throw new \Exception("token format error");}list($headerBase64, $payloadBase64, $signBase64) = $data;$header = json_decode($this->base64UrlDecode($headerBase64), true);$payload = json_decode($this->base64UrlDecode($payloadBase64), true);$sign = $this->base64UrlDecode($signBase64);// $signCheck = $this->getSignEncryption($headerBase64, $payloadBase64);$signCheck = $this->getSignEncryption2($headerBase64, $payloadBase64);if ($sign != $signCheck) {throw new \Exception("token error");}//验证时间if (isset($payload['exp'])) {if ($payload['exp'] > time()) {throw new \Exception("token Failure");}}return $payload;}
}

COZE获取token

amespace app\index\server;use app\index\model\businesstypemodel;
use think\Log;class cozeserver {private $oauth2token_url = "https://api.coze.cn/api/permission/oauth2/token";private function getoauthconfig() {$id = "id"; //id$key = "key"; //公钥指纹$pem_file = ROOT_PATH . "/private_key.pem";$config = ['id' => $id,'key' => $key,'pem_file' => $pem_file,];return $config;}public function gettoken($type, $username = "") {$config = $this->getoauthconfig();$s_jwt = new jwtServer($config['key'], $config['pem_file'], 'file');$s_jwt->setalgo("RS256");$max_day = 30;$time = time();$exp_time = strtotime("+$max_day days");$jti = getRandomStrings();$session_name = empty($username) ? "watercat" : $username;$payload = ["iss" => $config['id'], // OAuth 应用的 ID"aud" => "api.coze.cn", // 扣子 API 的 Endpoint"iat" => $time, // JWT 开始生效的时间,秒级时间戳"exp" => $exp_time, // JWT 过期时间,秒级时间戳"jti" => $jti, // 随机字符串,防止重放攻击"session_name" => $session_name, //用户在业务侧的 UID];$jwtstr = $s_jwt->generate($payload);$url = $this->oauth2token_url;$authorization = " Bearer " . $jwtstr;$header = ['Authorization:' . $authorization,'Content-Type: application/json',];$postdata = ["grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",// "duration_seconds" => 86399,//默认900秒// "scope" => "",];$data = json_encode($postdata, 320);$result = requestCurl($url, "post", $data, $header);Log::info($result);$jsondata = json_decode($result, true);if (isset($jsondata['error'])) {$msg = $jsondata['error_message'];throw new \Exception($msg);}//解析后数据return $jsondata;}
}

http://www.lryc.cn/news/586899.html

相关文章:

  • 一文读懂现代卷积神经网络—使用块的网络(VGG)
  • 2025江苏省信息安全管理与评估赛项二三阶段任务书
  • 改进后的 OpenCV 5.x + GStreamer + Python 3.12 编译流程(适用于 Orange Pi / ARM64)
  • 3.7 ASPICE的问题解决与改进过程
  • Linux-网络管理
  • iTestin 自动化录制工具
  • Kimi K2深度解析:开源万亿参数大模型,复杂场景能力强悍,为AI Agent而生!
  • Vision Kit之文档扫描
  • 【PyMuPDF】PDF图片处理过程内存优化分析
  • 论文Review 3DGSSLAM GauS-SLAM: Dense RGB-D SLAM with Gaussian Surfels
  • kettle从入门到精通 第102课 ETL之kettle xxl-job调度kettle的两种方式
  • 归并排序递归法和非递归法的简单简单介绍
  • 三种网络类型
  • X00211-基于残差edge-graph注意力机制的深度强化学习优化车辆路径问题
  • RedisJSON 技术揭秘(五)`JSON.ARRPOP` 原子弹出 修改数组的终极手段
  • 基于Java Web的销售管理系统设计系统
  • 操作系统--用户态和内核态
  • MongoDB对接SpringBoot【大数据存储】
  • ref 和 reactive
  • https交互原理
  • [Subtitle Edit] 字幕格式处理 | .Net依赖管理(NuGet)
  • Python----OpenCV(图像分割——彩色图像分割,GrabCut算法分割图像)
  • LeetCode--44.通配符匹配
  • Mybatis 两级缓存可能导致的问题
  • Java4种设计模式详解(单例模式、工厂模式、适配器模式、代理模式)
  • 笔记/sklearn中的数据划分方法
  • 赛力斯6月新能源汽车销量46086辆,同比增长4.44%
  • JavaScript加强篇——第九章 正则表达式高级应用(终)
  • Linux编程:6、进程通信-信号量与共享内存
  • OpenLayers 入门指南【二】:坐标系与投影转换