获取Token
using UnityEngine;
using System;
using System.Text;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using UnityEngine.Networking;
using System.Collections.Generic;
using System.Globalization;
using Cysharp.Threading.Tasks;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class AliTTSCtrl : MonoBehaviour
{
private readonly string accessKeyId = "********";
private readonly string accessKeySecret = "********";
private readonly string accessKey = "********";
private readonly string account = "********";
private readonly string regionId = "cn-shanghai";
private readonly string version = "2019-02-28";
private readonly string action = "CreateToken";
private readonly string formatType = "JSON";
private readonly string signatureMethod = "HMAC-SHA1";
private readonly string signatureVersion = "1.0";
private DateTime expirationTime = DateTime.MinValue;
void Start()
{
}
[ContextMenu("获取 Token")]
#if UNITY_EDITOR
[ExecuteInEditMode]
#endif
public async UniTask<string> GetToken()
{
try {
var res = CheckTokenExpireTime();
if (res.Item1)
{
return res.Item2;
}
else
{
var token = await PostTokenRequest();
return token;
}
}catch(Exception e)
{
Debug.LogError($"错误: {
e}");
}
throw new NullReferenceException("Token 无法获取");
}
private (bool, string) CheckTokenExpireTime()
{
string tokenString = PlayerPrefs.GetString(accessKeyId, "");
if (!string.IsNullOrEmpty(tokenString))
{
JObject token = JObject.Parse(tokenString);
long expireTime = token["ExpireTime"].Value<long>();
long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
long timeLeft = expireTime - currentTime;
string tokenID = token["Id"].Value<string>();
if (timeLeft < 86400)
{
Debug.Log("Token 将在24小时内过期 True");
return (false, null);
}
else
{
Debug.Log("Token 还可以使用 False");
return (true, tokenID);
}
}
return (false, null);
}
async UniTask<string> PostTokenRequest()
{
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
string signatureNonce = Guid.NewGuid().ToString();
var parameters = new Dictionary<string, string>
{
{
"AccessKeyId", accessKeyId },
{
"Action", action },
{
"Format", formatType },
{
"RegionId", regionId },
{
"SignatureMethod", signatureMethod },
{
"SignatureNonce", signatureNonce },
{
"SignatureVersion", signatureVersion },
{
"Timestamp", timestamp},
{
"Version", version }
};
string queryString = EncodeDictionary(parameters);
string stringToSign = "GET&" + EncodeText("/") + "&" + EncodeText(queryString);
string signature = CalculateSignature(accessKeySecret, stringToSign);
signature = EncodeText(signature);
string url = $"https://nls-meta.cn-shanghai.aliyuncs.com/?Signature={
signature}&{
queryString}";
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
var asyncOp = www.SendWebRequest();
await asyncOp;
var header = www.GetResponseHeaders();
string headerStr = "";
headerStr += www.uri.Host+"\n";
foreach (var head in header)
{
headerStr += $"{
head.Key} : {
head.Value} \n";
}
Debug.Log($"请求 Response: {
headerStr}");
if (www.result != UnityWebRequest.Result.Success)
{
string textData = www.downloadHandler.text;
Debug.LogError($"请求错误 Error:{
www.result} + {
www.error} -> {
textData}");
}
else
{
string jsonResponse = www.downloadHandler.text;
Debug.Log($"请求成功 Response: {
jsonResponse}");
JObject json = JObject