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

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.xdnf.cn/news/15436.html

相关文章:

  • 代码随想录|图论|15并查集理论基础
  • ARC 03 从Github Action job 到 runner pod
  • Java4种设计模式详解(单例模式、工厂模式、适配器模式、代理模式)
  • 【DeepSeek实战】29、金融数据抓取全攻略:从AKShare到API实战,Python量化分析必备指南
  • JavaScript 中一些常见算法的实现及详细解析
  • 详解Linux下多进程与多线程通信(二)
  • Web应用性能优化之数据库查询实战指南
  • 时间的弧线,逻辑的航道——标准单元延迟(cell delay)的根与源
  • 单页面和多页面的区别和优缺点
  • 通用定时器GPT
  • 【Linux学习笔记】认识信号和信号的产生
  • 区块链平台之以太坊深入解读:技术、经济与生态的全面解析
  • 剑指offer57_和为S的两个数字
  • 串口连接工控机
  • 【离线数仓项目】——电商域DIM层开发实战
  • 服务端高效处理拖拽排序
  • 锁相环初探
  • 【6.1.2 漫画分布式事务技术选型】
  • BaseDao 通用更新方法设计与实现
  • 【PMP备考】敏捷思维:驾驭不确定性的项目管理之道
  • Java ThreadLocal详解:从原理到实践
  • 快速过一遍Python基础语法
  • 第34次CCF-CSP认证第4题,货物调度
  • 零基础搭建监控系统:Grafana+InfluxDB 保姆级教程,5分钟可视化服务器性能!​
  • Python 中的 encode() 和 decode() 方法详解
  • JavaSE常用类
  • 开阳630HV100芯片的外设配置
  • 【C++】封装红黑树模拟实现set和map
  • C语言<数据结构-单链表>(收尾)
  • Linux反弹shell的几种方式