You need to enable JavaScript to run this app.
导航

请求获取授权Token

最近更新时间2023.03.16 11:40:11

首次发布时间2023.03.16 11:40:11

第一步:数据准备
  1. 已经确认找相关对接同学开通了【某个服务】,有使用需求

  2. 从火山获取 ACCESS_KEY / SECRET_KEY,详细步骤查看:文档中心-火山引擎

  3. 火山引擎 - 音频技术创建APP,拿到AppKey

第二步:通过Demo接口,填入必要的参数后激活设备并获取Token

参数说明

下面对需要的参数进行详细说明,只看参数过于枯燥,建议和下一节的 demo 接口代码配合使用

请求参数

  • 请求地址:http://open.volcengineapi.com

  • 请求方式:GET / POST

  • 请求参数:

字段类型是否必填说明

expiration

int64

需要申请的Token可用时长,单位为秒。

  • 注:最长可申请 90 天 = 90 * 24 * 60 * 60 = 7776000秒,超过该数值则默认为7776000
appkeystring可以在“火山引擎 - 音频技术 - 应用管理”页面下拿到
token_versionstring固定填:volc-offline-auth-v2

device_id

string

务必通过SDK接口获取正确的****设备ID,否则:

  1. 拿到的Token无法在对应设备使用

  2. 没有通过SDK接口拿到的其他设备ID,会占用一个激活名额

services

string list

  • 该设备需要激活的服务,从下文 "受支持的服务中英文名称对照表" 中选取英文名后填入

  • 传参方式:该参数通过 body 传入(demo代码已写好)

  • 注:务必确保填入的服务已经开通!否则会报错"service Unauthorized"

platforms

string list

  • 该设备需要激活的平台,从下文“受支持的平台列表”中选取后填入

  • 传参方式:在 body中传入(demo代码已写好)

  • 注:务必确保填入的服务已经开通!否则会报错"platform unauthorized"

  • 请求 Body示例

    {
        "services": [
            "offline_VoiceConversion"
        ],
        "platforms": [
            "mac",
            "win"
        ]
    }
    

响应字段

请求字段类型说明
task_idstring请求任务id,不用关注
tokenstring鉴权token,用于调用服务接口

expires_at

number

过期时间戳:如果请求了多个服务,代表最早过期的时间戳。用户可以基于此过期时间戳进行刷新 或 进行服务续期

status_codenumber状态码
status_textstring状态信息
  • 示例:

    {
        "status_code": 20000000,
        "status_text": "OK",
        "task_id": "53a1d948-c861-4223-a703-8e33c9a9ddf6",
        "token": "vq98KqLYAz2E5crXXJ1gnGG+FwGlLlw***************************************",
        "expires_at": 1669865698,
        "BaseResp": {
            "StatusMessage": "",
            "StatusCode": 0
        }
    }
    

Python版Demo

# -*- coding: utf-8 -*-
import json
import threading

from volcengine.ApiInfo import ApiInfo
from volcengine.Credentials import Credentials
from volcengine.ServiceInfo import ServiceInfo
from volcengine.base.Service import Service

AUTH_VERSION = "volc-offline-auth-v2"
api_url = "open.volcengineapi.com"

# user auth
ACCESS_KEY = "AKLTOTFmNmZjM2YzNGQ3NDQxNzk5NzUxMTg0***"
SECRET_KEY = "TTJGbVlqUTJaV00xTXpsbU5HTmpabUkxTmpjeU5EbGhaamc1***"
APPKEY = "zrJFign***"
device_id = "QWER001"
services = ["offline_VoiceConversion", "offline_AEC"]
platforms = ["win", "mac"]


# https://github.com/volcengine/volc-sdk-python
class SAMIService(Service):
    _instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        if not hasattr(SAMIService, "_instance"):
            with SAMIService._instance_lock:
                if not hasattr(SAMIService, "_instance"):
                    SAMIService._instance = object.__new__(cls)
        return SAMIService._instance

    def __init__(self):
        self.service_info = SAMIService.get_service_info()
        self.api_info = SAMIService.get_api_info()
        super(SAMIService, self).__init__(self.service_info, self.api_info)

    @staticmethod
    def get_service_info():
        service_info = ServiceInfo(api_url, {},
                                   Credentials('', '', 'sami', 'cn-north-1'), 10, 10)
        return service_info

    @staticmethod
    def get_api_info():
        api_info = {
            "GetToken": ApiInfo("POST", "/", {"Action": "GetToken", "Version": "2021-07-27"}, {}, {}),
        }
        return api_info

    def common_json_handler(self, api, body):
        params = dict()
        try:
            body = json.dumps(body)
            res = self.json(api, params, body)
            res_json = json.loads(res)
            return res_json
        except Exception as error:
            res = str(error)
            try:
                res_json = json.loads(res)
                return res_json
            except:
                raise Exception(str(error))


if __name__ == '__main__':
    sami_service = SAMIService()
    sami_service.set_ak(ACCESS_KEY)
    sami_service.set_sk(SECRET_KEY)
    req = {
        "appkey": APPKEY,
        "token_version": AUTH_VERSION,
        "expiration": 3600,
        "device_id": device_id,
        "services": services,
        "platforms": platforms
    }
    resp = sami_service.common_json_handler("GetToken", req)
    print(resp)

GO语言版Demo

package main

import (
   "encoding/json"
   "fmt"
   "net/http"
   "net/url"
   "time"

   "github.com/volcengine/volc-sdk-golang/base"
)

// user and app info
const (
   apiUrl    = "open.volcengineapi.com" 
   tokenVersion = "volc-offline-auth-v2"
   //update user info
   accessKey = "AKLTOTFmNmZjM2YzNGQ3NDQxNzk5NzUx***"
   secretKey = "TTJGbVlqUTJaV00xTXpsbU5HTmpabUkxTmpje***"
   appKey    = "zrJFign***"
)

var (
   services  = []string{"offline_VoiceConversion", "offline_AEC"}
   platforms = []string{"mac", "win"}
   //  tip: get device_id from sdk
   device_id = "QDSNDC<NZ<NKLJIOWJEORIJ<>Z?:QK&*#$Y!*O*($JKHAS"
)

type TokenRequest struct {
   Expiration int64  `json:"expiration,required" query:"expiration,required"`
   AppKey     string `json:"appkey,required" query:"appkey,required"`
   Version    string `json:"token_version,required" query:"token_version,required"`

   Namespace string   `json:"namespace,omitempty" query:"namespace,omitempty"`
   DeviceId  string   `json:"device_id,omitempty" query:"device_id,omitempty"`
   Services  []string `json:"services,omitempty" query:"services,omitempty"`
   Platforms []string `json:"platforms,omitempty" query:"platforms,omitempty"`
}

type GetTokenResponse struct {
   StatusCode   int32            `form:"status_code,required" json:"status_code,required" query:"status_code,required"`
   StatusText   string           `form:"status_text,required" json:"status_text,required" query:"status_text,required"`
   TaskId       string           `form:"task_id,required" json:"task_id,required" query:"task_id,required"`
   Token        string           `form:"token,required" json:"token,required" query:"token,required"`
   ExpiresAt    int64            `form:"expires_at,required" json:"expires_at,required" query:"expires_at,required"`
   ExpiresAtMap map[string]int64 `thrift:"expires_at_map" json:"expires_at_map,omitempty"`
}

// volcengine sdk including auth: https://github.com/volcengine
// https://github.com/volcengine/volc-sdk-golang/blob/main/service/visual/README.md
// when success:
// {"code":0,"msg":"ok","get_token":"your_token_with_expiration"}
func main() {
   // DefaultInstance.Client.ServiceInfo.Credentials = base.Credentials{Region: DefaultRegion, Service: "sami"}
   DefaultInstance.Client.SetAccessKey(accessKey)
   DefaultInstance.Client.SetSecretKey(secretKey)
   expiration := int64(10) // expiration in seconds
   reqData, _ := json.Marshal(
      TokenRequest{
         Expiration: expiration,
         AppKey:     appKey,
         Version:    tokenVersion,
         DeviceId:   device_id,
         Services:   services,
         Platforms:  platforms,
      },
   )

   resp := &GetTokenResponse{}
   fmt.Println(string(reqData))
   status, err := DefaultInstance.commonHandlerJSON("GetToken", string(reqData), &resp)
   fmt.Println(status, err)
   fmt.Printf("resp: %#v\n", resp)
}

// volcengine client wrapper: sami open api info
const (
   DefaultRegion          = "cn-north-1"
   ServiceVersion20210727 = "2021-07-27"
   ServiceName            = "sami"
)

var (
   // DefaultInstance 默认的实例
   DefaultInstance = NewInstance()
   ServiceInfo     = &base.ServiceInfo{
      Timeout:     10 * time.Second,
      Host:        apiUrl,
      Header:      http.Header{"Accept": []string{"application/json"}},
      Credentials: base.Credentials{Region: "cn-north-1", Service: ServiceName},
   }
   ApiInfoList = map[string]*base.ApiInfo{
      "GetToken": {
         Method: http.MethodPost,
         Path:   "/",
         Query: url.Values{
            "Action":  []string{"GetToken"},
            "Version": []string{ServiceVersion20210727},
         },
      },
   }
)

// Sami .
type Sami struct {
   Client *base.Client
}

// NewInstance new Sami client instance
func NewInstance() *Sami {
   instance := &Sami{}
   instance.Client = base.NewClient(ServiceInfo, ApiInfoList)
   instance.Client.ServiceInfo.Credentials.Service = ServiceName
   instance.Client.ServiceInfo.Credentials.Region = DefaultRegion
   return instance
}
func (p *Sami) commonHandler(api string, form url.Values, resp interface{}) (int, error) {
   respBody, statusCode, err := p.Client.Post(api, form, nil)
   fmt.Println(string(respBody))
   if err != nil {
      errMsg := err.Error()
      // business error will be shown in resp, request error should be nil here
      if errMsg[:3] != "api" {
         return statusCode, err
      }
   }
   if err := json.Unmarshal(respBody, resp); err != nil {
      return statusCode, err
   }
   return statusCode, nil
}
func (p *Sami) commonHandlerJSON(api string, jsonBody string, resp interface{}) (int, error) {
   respBody, statusCode, err := p.Client.Json(api, nil, jsonBody)
   if err != nil {
      errMsg := err.Error()
      // business error will be shown in resp, request error should be nil here
      if errMsg[:3] != "api" {
         return statusCode, err
      }
   }
   if err := json.Unmarshal(respBody, resp); err != nil {
      return statusCode, err
   }
   return statusCode, nil
}
参考数据

受支持的服务中英文名称对照表

服务中文名服务英文名
声音转换 - SDKoffline_VoiceConversion

受支持的平台列表

开通某个平台的SDK后,【platforms】字段可以按规定格式传入以下参数。(若未开通某个平台,但仍传入对应参数,则会返回"platform unauthorized"的报错)

平台英文名
win
mac
linux
android
ios