Remote Config 服务端API接入指南
Remote Config 服务端API接入指南
Remote Config 服务端API
Remote Config 服务端 API 是面向需要在服务端集成 Remote Config 的开发者提供的服务端集成的 API 列表。
API Endpoint: https://c.unity.cn
Remote Config 服务端 API 授权
使用 Basic Authorization 来进行鉴权 (推荐服务器端程序使用). 步骤如下:
在 UOS 网站上获取当前需要使用的 UOS APP 的 AppId 和 AppServiceSecret
注:此处 AppId 和 AppServiceSecret,可在 UOS 网站上获取


在请求任意 API 的 Request Header 中增加 Header:
- Authorization: Basic base64(appId:appServiceSecret)
示例代码
C## C# 使用示例 - Basic 授权方式 using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; class Program { private static string GetBasicAuthorization(string appId, string appServiceSecret) { string credentials = $"{appId}:{appServiceSecret}"; byte[] credentialsBytes = Encoding.UTF8.GetBytes(credentials); string encodedCredentials = Convert.ToBase64String(credentialsBytes); return $"Basic {encodedCredentials}"; } public static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { // 使用项目的 APP_ID, APP_SERVICE_SECRET 获取 headers client.DefaultRequestHeaders.Add("Authorization", GetBasicAuthorization(APP_ID, APP_SERVICE_SECRET)); // 以get方法为例,替换 url 为你需要请求的 url HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); // 其他处理…… } } }Python# Python 使用示例 - Basic 授权方式 import base64 import requests def get_basic_authorization(app_id, app_service_secret): """ 获取basic auth的Header """ credentials = f'{app_id}:{app_service_secret}' encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8") return {'Authorization': f'Basic {encoded_credentials}'} # 使用 APP_ID, APP_SERVICE_SECRET 获取Basic Token Header headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET) # 以get方法为例,替换 url 为你需要请求的 url response = requests.get(url, headers=headers)JavaScript// JavaScript 使用示例 - Basic 授权方式 const axios = require('axios'); function getBasicAuthorization(appId, appServiceSecret) { /** 获取 basic auth 的 Header */ const credentials = `${appId}:${appServiceSecret}`; const encodedCredentials = btoa(credentials); return { 'Authorization': `Basic ${encodedCredentials}` }; } // 使用 APP_ID, APP_SERVICE_SECRET 获取Basic Token Header const headers = getBasicAuthorization(APP_ID, APP_SERVICE_SECRET); // 以get方法为例,替换 url 为你需要请求的 url const response = await axios.get(url, { headers });Go// Go 使用示例 - Basic 授权方式 import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "net/http" ) func GetBasicAuthorization(appID, appServiceSecret string) string { credentials := appID + ":" + appServiceSecret encodedCredentials := base64.StdEncoding.EncodeToString([]byte(credentials)) return "Basic " + encodedCredentials } func main() { // 以get方法为例,替换 url 为你需要请求的 url req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // 使用 APP_ID, APP_SERVICE_SECRET 获取Basic Token Header req.Header.Set("Authorization", GetBasicAuthorization(APP_ID, APP_SERVICE_SECRET)) client := &http.Client{} response, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() // ……其他处理 }
Remote Config 服务端 API 列表
Configs
Overrides
Settings
Remote Config API 调用示例
调用示例:
# [UOS Config - 远程配置] 服务端API使用示例
# 功能模块具体使用方法可参考 https://uos.unity.cn/docs/remote-config.html
# -*-coding: utf-8-*-
import base64
import json
import uuid
import requests
from datetime import datetime
# 配置
BASE_URL = 'https://c.unity.cn'
APP_ID = '' # App ID
APP_SERVICE_SECRET = '' # App Service Secret
USER_ID = '' # 用户ID (必填)
PERSONA_ID = '' # 角色ID (选填)
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(USER_ID) == 0:
USER_ID = "user-" + datetime.today().strftime('%Y%m%d') + "-" + str(uuid.uuid4())[:8]
def get_basic_auth_header():
""" 生成 Auth Header """
credentials = f"{APP_ID}:{APP_SERVICE_SECRET}".encode("utf-8")
encoded_credentials = base64.b64encode(credentials).decode("utf-8")
return f"Basic {encoded_credentials}"
HEADERS = {
"Content-Type": "application/json",
"Accept": "*/*",
"Authorization": get_basic_auth_header()
}
def handle_response(response):
""" 处理返回 """
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
print(response.text)
raise
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
raise
else:
return response.json()
def create_config(key, value_type, value):
""" 创建配置 (Config) """
url = BASE_URL + "/v1/configs"
config_data = {
"key": key,
"type": value_type,
"value": value
}
response = requests.post(url, json=config_data, headers=HEADERS)
return handle_response(response)
def create_override(name, description, start_date, end_date, priority, rule, rollout_percentage, variants):
""" 创建覆盖 (Override) """
url = BASE_URL + "/v1/overrides"
override_data = {
"name": name,
"description": description,
"priority": priority,
"rule": rule,
"rolloutPercentage": rollout_percentage,
"variants": variants
}
if start_date != "":
override_data["startDate"] = start_date
if end_date != "":
override_data["endDate"] = end_date
response = requests.post(url, json=override_data, headers=HEADERS)
return handle_response(response)
def enable_override(override_id_to_enable):
""" 启用覆盖 (Override) """
url = BASE_URL + "/v1/overrides/" + override_id_to_enable + "/enable"
response = requests.put(url, headers=HEADERS)
return response.ok
def get_settings(keys, types):
""" 获取全局设定 (Settings) """
url = BASE_URL + "/v1/settings"
settings_data = {}
if len(keys) != 0:
settings_data["keys"] = keys
if len(types) != 0:
settings_data["types"] = types
response = requests.post(url, json=settings_data, headers=HEADERS)
return handle_response(response)
def get_settings_overrides(user_id, persona_id, keys, types, player_attributes):
""" 获取玩家设定 (Player Overrides) """
url = BASE_URL + "/v1/settings/overrides"
settings_override_data = {
"userId": user_id,
"personaId": persona_id,
"keys": keys,
"types": types,
"attributes": player_attributes
}
response = requests.post(url, json=settings_override_data, headers=HEADERS)
return handle_response(response)
def list_overrides():
""" 获取覆盖列表 """
url = BASE_URL + "/v1/overrides"
response = requests.get(url, headers=HEADERS)
return handle_response(response)
def list_configs():
""" 获取配置列表 """
url = BASE_URL + "/v1/configs"
response = requests.get(url, headers=HEADERS)
return handle_response(response)
def delete_overrides(override_ids):
""" 删除覆盖 """
params = "&overrideIds=".join(override_ids)
url = BASE_URL + "/v1/overrides" + "?overrideIds=" + params
response = requests.delete(url, headers=HEADERS)
return response.ok
def delete_configs(config_ids):
""" 删除配置 """
params = "&configIds=".join(config_ids)
url = BASE_URL + "/v1/configs" + "?configIds=" + params
response = requests.delete(url, headers=HEADERS)
return response.ok
# 示例
print("AppId:", APP_ID)
print("UserId:", USER_ID)
print("PersonId:", PERSONA_ID)
# 1 创建配置 (Config)
config_response = create_config("key1", "STRING", "value1")
print("Config Response:", config_response)
config_id = config_response.get("config", {}).get("configId", "")
print("ConfigId:", config_id)
new_value = "value2"
# 配置的值以字符串的形式传入
create_config("key2", "INT", "10")
create_config("key3", "LONG", "2147483648")
create_config("key4", "FLOAT", "2.71828")
create_config("key5", "BOOL", "True")
create_config("key6", "JSON", json.dumps({"k1": "v1"}))
# 2 创建覆盖 (Override)
variant1 = [
{
"name": "variant1",
"weight": 100,
"values": [
{
"configId": config_id,
"value": new_value
}
]
}
]
override_response = create_override(
"override1",
"Description",
"2023-01-01T00:00:00Z",
"", # never expire
100,
"user.rank > 5",
50,
variant1,
)
print("Override Response:", override_response)
override_id = override_response.get("overrideId", "")
print("OverrideId:", override_id)
# 3 启用覆盖
success = enable_override(override_id)
print("Override Enabled:", success)
# 4 获取全局玩家配置
# 注意: 这里的settings不考虑覆盖override,所以是全局的,对于每个玩家都一致。
settings = get_settings(["key1", "key2"], [])
print("Settings (key1, key2):", settings)
settings = get_settings([], ["STRING", "INT", "JSON"])
print("Settings (string, int, json):", settings)
settings = get_settings([], [])
print("Settings (all):", settings)
# 5 获取玩家覆盖配置
# 这里的返回会考虑覆盖
attributes = {
"unity": {
"appVersion": "1.0",
"appBuildVersion": "23",
"country": "US",
"cpu": "Intel(R) Core(TM) i7-7920 HQ CPU @ 3.10GHz",
"cpuFrequency": "3100",
"graphicsDeviceVendor": "Apple",
"language": "en",
"osVersion": "Mac OS X 10.14.4",
"platform": "macOS",
"ram": 8192,
"model": "Macbook Pro 13",
"timeSinceStart": 60000
},
"app": {
"isDebugBuild": True,
"packageVersion": "2.1.1"
},
"user": {
"rank": 10
}
}
settings_overrides = get_settings_overrides(
"user123",
"persona456",
["key1", "key2"],
["STRING", "INT"],
attributes)
print("Settings Overrides:", settings_overrides)
# 6 获取覆盖列表
override_list_response = list_overrides()
print("Overrides List:", override_list_response)
# 7 获取配置列表
config_list_response = list_configs()
print("Config List:", config_list_response)
# # 8 删除覆盖
# override_list = override_list_response.get("overrides", [])
# override_id_list = []
# for override in override_list:
# override_id = override.get("overrideId", "")
# if len(override_id) != 0:
# override_id_list.append(override_id)
# delete_response = delete_overrides(override_id_list)
# print("Delete Overrides:", delete_response)
#
# # 9 删除配置
# config_list = config_list_response.get("configs", [])
# config_id_list = []
# for config in config_list:
# config_id = config.get("configId", "")
# if len(config_id) != 0:
# config_id_list.append(config_id)
# delete_response = delete_configs(config_id_list)
# print("Delete Configs:", delete_response)