Passport 服务端API接入指南
Passport 服务端API接入指南
Passport 服务端API
Passport 服务端API是面向已有独立的ID系统,需要使用UOS Passport提供的其它服务(如好友,权利,排行榜等)的开发者提供的服务端集成的 API 列表。
文档中 URL / Request / Response 中出现的 idDomainID 均为 UOS App ID
API Endpoint: https://p.unity.cn
授权
使用 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() // ……其他处理 }
服务端可供集成的 API 列表
Realm
Realm对应游戏中服务器的概念,支持服务器的创建、删除、更新和查询。
服务器 API 调用示例
# [UOS Passport - 服务器]服务端API使用示例
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
def run():
print("============ 创建服务器 ============")
# 服务器外部ID(1:1映射,不可重复),此处以"exampleRealmID"为例
external_realm_id = "exampleRealmID"
response = create_realm(name="exampleRealmName", external_realm_id=external_realm_id)
print(response)
realm_id = response.get('realm').get('realmID')
print("============ 获取服务器信息 ============")
response = get_realm(realm_id)
print(response)
print("============ 更新服务器信息 ============")
response = update_realm(realm_id, name="updatedRealmName")
print(response)
print("============ 获取服务器列表 ============")
response = list_realms()
print(response)
print("============ 删除服务器 ============")
response = delete_realm(realm_id)
print(response)
def create_realm(name, external_realm_id):
""" 创建服务器 """
url = API_ENDPOINT + '/v1/realms'
data = {
"name": name,
"externalRealmID": external_realm_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_realm(realm_id):
""" 获取服务器信息 """
url = API_ENDPOINT + '/v1/realms/' + realm_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def update_realm(realm_id, name):
""" 更新服务器信息 """
url = API_ENDPOINT + '/v1/realms/' + realm_id
data = {
"name": name
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def list_realms():
""" 获取服务器列表 """
url = API_ENDPOINT + '/v1/realms/search'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def delete_realm(realm_id):
""" 删除服务器 """
url = API_ENDPOINT + '/v1/realms/' + realm_id
response = requests.delete(url, headers=headers)
check_response(response)
return response
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Login
支持使用外部ID登录。
登录 API 调用示例
# [UOS Passport - 登录]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/external-login.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
def run():
print("============ 使用外部ID登录,获取Persona(角色) ============")
# external_user_id为已有ID系统的用户ID,此处用“10001”模拟外部ID系统的用户ID
external_user_id = "10001"
response = external_login(external_user_id, display_name="testUser")
print(response)
def external_login(external_user_id, display_name):
""" 使用外部ID登录,获取Persona(角色) """
url = API_ENDPOINT + '/v1/login/external'
data = {
"externalUserID": external_user_id,
"displayName": display_name,
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)User
User对应游戏中用户账号的概念,支持获取、更新和删除用户信息。
用户 API 调用示例
# [UOS Passport - 用户]服务端API使用示例
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录过后,在此填入玩家的用户ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家的用户ID可通过登录后的返回值中的UserID获取,或者在UOS APP网页 - Passport - 账号 - 用户管理 页面可查看当前已有的用户列表
USER_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(USER_ID) == 0:
print(
"请在玩家登录过后,在此填入玩家的用户ID。登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 获取用户信息 ============")
response = get_user(USER_ID)
print(response)
print("============ 更新用户信息 ============")
response = update_user(USER_ID, name="updatedUserName")
print(response)
print("============ 搜索用户 ============")
response = search_users(USER_ID)
print(response)
print("============ 删除用户 ============")
response = delete_user(USER_ID)
print(response)
def get_user(user_id):
""" 获取用户信息 """
url = API_ENDPOINT + '/v1/users/' + user_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def update_user(user_id, name):
""" 更新用户信息 """
url = API_ENDPOINT + '/v1/users/' + user_id
data = {
"name": name
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def search_users(user_id):
""" 搜索用户 """
url = API_ENDPOINT + '/v1/users/search'
data = {
"userID": user_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def delete_user(user_id):
""" 删除用户 """
url = API_ENDPOINT + '/v1/users/' + user_id
response = requests.delete(url, headers=headers)
check_response(response)
return response
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Persona
Persona对应游戏服务器中角色的概念,支持获取、更新和删除角色信息,同时可以封禁和解封指定角色。
角色 API 调用示例
# [UOS Passport - 角色]服务端API使用示例
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录过后,在此填入玩家的角色ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家的角色ID可通过登录后的返回值中的PersonaID获取,或者在UOS APP网页 - Passport - 账号 - 角色管理 页面可查看当前已有的角色列表
PERSONA_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(PERSONA_ID) == 0:
print(
"请在玩家登录之后,在PERSONA_ID处填入玩家角色的ID,登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 获取角色信息 ============")
response = get_persona(PERSONA_ID)
print(response)
print("============ 更新角色信息 ============")
response = update_persona(PERSONA_ID, display_name="updatedPersonaName")
print(response)
print("============ 搜索角色 ============")
response = search_personas(PERSONA_ID)
print(response)
print("============ 封禁角色 ============")
response = ban_persona(PERSONA_ID)
print(response)
print("============ 解封角色 ============")
response = unban_persona(PERSONA_ID)
print(response)
print("============ 删除角色 ============")
response = delete_persona(PERSONA_ID)
print(response)
def get_persona(persona_id):
""" 获取角色信息 """
url = API_ENDPOINT + '/v1/personas/' + persona_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def update_persona(persona_id, display_name):
""" 更新角色信息 """
url = API_ENDPOINT + '/v1/personas/' + persona_id
data = {
"displayName": display_name
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def search_personas(persona_id):
""" 搜索角色 """
url = API_ENDPOINT + '/v1/personas/search'
data = {
"personaID": persona_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def ban_persona(persona_id):
""" 封禁角色 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/ban'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def unban_persona(persona_id):
""" 解封角色 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/unban'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def delete_persona(persona_id):
""" 删除角色 """
url = API_ENDPOINT + '/v1/personas/' + persona_id
response = requests.delete(url, headers=headers)
check_response(response)
return response
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Metrics
支持获取到运营数据。
Friends
支持获取好友列表和拉黑列表。
好友 API 调用示例
# [UOS Passport - 好友]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/friends.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录过后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家角色的ID可通过登录后的返回值中的PersonaID获取,或者在UOS APP网页 - Passport - 账号 - 角色管理 页面可查看当前已有的角色列表
PERSONA_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(PERSONA_ID) == 0:
print(
"请在玩家登录过后,在此填入玩家角色的ID。登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 获取好友列表 ============")
response = get_friends_list(PERSONA_ID)
print(response)
print("============ 获取拉黑列表 ============")
response = get_friends_blacklist(PERSONA_ID)
print(response)
def get_friends_list(persona_id):
""" 获取好友列表 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/friends'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_friends_blacklist(persona_id):
""" 获取拉黑列表 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/friend-blacklist'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Tag
支持创建标签、查看使用该标签的用户和角色、修改标签名和删除标签等操作。
标签 API 调用示例
# [UOS Passport - 标签]服务端API使用示例
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录过后,在此填入玩家的用户ID和角色ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家的用户ID可通过登录后的返回值中的UserID获取,或者在UOS APP网页 - Passport - 账号 - 用户管理 页面可查看当前已有的用户列表
# 玩家的角色ID可通过登录后的返回值中的PersonaID获取,或者在UOS APP网页 - Passport - 账号 - 角色管理 页面可查看当前已有的角色列表
USER_ID = ''
PERSONA_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(USER_ID) == 0 or len(PERSONA_ID) == 0:
print(
"请在玩家登录之后,在USER_ID处填入玩家的用户ID,在PERSONA_ID处填入玩家的角色ID,登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 创建标签 ============")
response = create_tag(name="sampleTagName")
print(response)
tag_id = response.get('tag').get('id')
print("============ 获取标签信息 ============")
response = get_tag(tag_id)
print(response)
print("============ 获取标签列表 ============")
response = list_tags()
print(response)
print("============ 更新标签信息 ============")
response = update_tag(tag_id, name="updatedTagName")
print(response)
print("============ 为用户添加标签 ============")
response = add_tag_to_user(USER_ID, tag_id)
print(response)
print("============ 获取某个用户的标签列表 ============")
response = get_user_tags(USER_ID)
print(response)
print("============ 获取一个标签对应的用户列表 ============")
response = get_users_under_tag(tag_id)
print(response)
print("============ 为用户取消标签 ============")
response = remove_tag_from_user(USER_ID, tag_id)
print(response)
print("============ 为角色添加标签 ============")
response = add_tag_to_persona(PERSONA_ID, tag_id)
print(response)
print("============ 获取某个角色的标签列表 ============")
response = get_persona_tags(PERSONA_ID)
print(response)
print("============ 获取一个标签对应的角色列表 ============")
response = get_personas_under_tag(tag_id)
print(response)
print("============ 为角色取消标签 ============")
response = remove_tag_from_persona(PERSONA_ID, tag_id)
print(response)
print("============ 删除标签 ============")
response = delete_tag(tag_id)
print(response)
def create_tag(name):
""" 创建标签 """
url = API_ENDPOINT + '/v1/tags'
data = {
"name": name
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_tag(tag_id):
""" 获取标签信息 """
url = API_ENDPOINT + '/v1/tags/' + tag_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def list_tags():
""" 获取标签列表 """
url = API_ENDPOINT + '/v1/tags'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def update_tag(tag_id, name):
""" 更新标签信息 """
url = API_ENDPOINT + '/v1/tags/' + tag_id
data = {
"name": name
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def add_tag_to_user(user_id, tag_id):
""" 为用户添加标签 """
url = API_ENDPOINT + '/v1/users/' + user_id + '/tag'
data = {
"tagID": tag_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_user_tags(user_id):
""" 获取某个用户的标签列表 """
url = API_ENDPOINT + '/v1/users/' + user_id + '/tags'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_users_under_tag(tag_id):
""" 获取一个标签对应的用户列表 """
url = API_ENDPOINT + '/v1/tags/' + tag_id + '/users'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def remove_tag_from_user(user_id, tag_id):
""" 为用户取消标签 """
url = API_ENDPOINT + '/v1/users/' + user_id + '/untag'
data = {
"tagID": tag_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def add_tag_to_persona(persona_id, tag_id):
""" 为角色添加标签 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/tag'
data = {
"tagID": tag_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_persona_tags(persona_id):
""" 获取某个角色的标签列表 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/tags'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_personas_under_tag(tag_id):
""" 获取一个标签对应的角色列表 """
url = API_ENDPOINT + '/v1/tags/' + tag_id + '/personas'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def remove_tag_from_persona(persona_id, tag_id):
""" 为角色取消标签 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/untag'
data = {
"tagID": tag_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def delete_tag(tag_id):
""" 删除标签 """
url = API_ENDPOINT + '/v1/tags/' + tag_id
response = requests.delete(url, headers=headers)
check_response(response)
return response
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Report
支持获取举报列表、处理举报等操作。
AntiAddiction
支持上报玩家的充值金额。
防沉迷 API 调用示例
# [UOS Passport - 防沉迷]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/anti-addiction.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录过后,在此填入玩家的用户ID
# 使用此功能的玩家需要先完成「实名认证」,需要先在UOS APP网页 - Passport - 登录 - 登录配置 页面开启实名认证
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 使用「External登录」之后可以通过客户端「实名认证验证」接口进行实名认证,可参考https://uos.unity.cn/docs/passport/client-api.html User下的「实名认证验证」
# 玩家的用户ID可通过登录后的返回值中的UserID获取,或者在UOS APP网页 - Passport - 账号 - 用户管理 页面可查看当前已有的用户列表
USER_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(USER_ID) == 0:
print(
"请在玩家登录过后,在此填入玩家的用户ID。登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 上报玩家充值金额(建议充值成功后调用)amount单位为分 ============")
# 充值50元
response = upload_payment(amount=5000, user_id=USER_ID)
print(response)
def upload_payment(amount, user_id):
""" 上报玩家充值金额(建议充值成功后调用) """
url = API_ENDPOINT + '/v1/anti-addiction/payments'
data = {
"amount": amount,
"userID": user_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Leaderboard
支持创建、修改和删除排行榜,查看榜单历史成绩等操作。
排行榜 API 调用示例
# [UOS Passport - 排行榜]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/leaderboard.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请前往UOS App - Passport - 排行榜 下创建一个新的排行榜,创建时「榜中榜」选择「用户自定义」,并在此填入排行榜的唯一标识SlugName
LEADERBOARD_SLUG = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(LEADERBOARD_SLUG) == 0:
print(
"请前往UOS App - Passport - 排行榜 下创建一个新的排行榜,创建时「榜中榜」选择「用户自定义」,并在LEADERBOARD_SLUG处填入排行榜的SlugName")
exit(1)
def run():
# 若需要玩家成绩排行榜,memberId可填入玩家的personaId,可以关联玩家的角色信息
member_id_1 = "1010100001"
member_id_2 = "1010100002"
member_id_3 = "1010100003"
member_id_4 = "1010100004"
# 自定义的「榜中榜」ID
bucket_id_1 = "bucket1"
bucket_id_2 = "bucket2"
# ============ 排行榜配置信息相关 ============
print("============ 获取所有排行榜的配置信息 ============")
response = list_leaderboards()
print(response)
print("============ 获取某一个排行榜的配置信息 ============")
response = get_leaderboard(LEADERBOARD_SLUG)
print(response)
version_id = response.get('leaderboard').get('versionId')
# ============ 更新、查询排行榜成员成绩相关 ============
print("============ 更新排行榜成员分数 ============")
response = update_member_score(LEADERBOARD_SLUG, member_id_1, score=60, bucket_id=bucket_id_1)
print(response)
print("============ 批量更新排行榜成员分数,当排行榜为用户自定义榜中榜时,需要指定玩家成绩的bucketId ============")
member_scores = [
{
"memberId": member_id_1,
"score": 70,
"bucketId": bucket_id_1
},
{
"memberId": member_id_2,
"score": 80,
"bucketId": bucket_id_1
},
{
"memberId": member_id_3,
"score": 90,
"bucketId": bucket_id_2
},
{
"memberId": member_id_4,
"score": 20,
"bucketId": bucket_id_2
},
]
response = batch_update_member_score(LEADERBOARD_SLUG, member_scores)
print(response)
print("============ 获取排行榜的成绩列表 ============")
response = list_leaderboard_scores(LEADERBOARD_SLUG)
print(response)
print("============ 获取一个排行榜中某个成员的成绩 ============")
response = get_leaderboard_member_score(LEADERBOARD_SLUG, member_id_1)
print(response)
print(
"============ 获取一个排行榜中某个成员及其附近成员的成绩,带range=1查询该成员排名前一个+自己+排名后一个的成员成绩 ============")
response = get_leaderboard_member_score(LEADERBOARD_SLUG, member_id_1, range=1)
print(response)
print("============ 查询该成员在所有排行榜中的成绩信息 ============")
response = get_member_scores(member_id_1)
print(response)
print("============ 删除排行榜中的成绩 ============")
response = delete_leaderboard_member_score(LEADERBOARD_SLUG, member_id_3)
print(response)
# ============ 排行榜 榜中榜信息相关 ============
print("============ 获取排行榜中某个成员所在小榜的成绩列表,即同一bucketId下的所有成员成绩 ============")
response = list_member_bucket_scores(LEADERBOARD_SLUG, member_id_1)
print(response)
print("============ 查看所有自定义的bucketId ============")
response = list_buckets(LEADERBOARD_SLUG)
print(response)
print("============ 查看自定义的bucket中的成绩列表 ============")
response = list_bucket_scores(LEADERBOARD_SLUG, bucket_id_1)
print(response)
# ============ 排行榜重置相关 ============
print(
"============ 获取排行榜重置计划,可在UOS App排行榜页面点击进入某个排行榜详情后,在「重置管理」中设置 ============")
response = get_leaderboard_reset_schedule(LEADERBOARD_SLUG)
print(response)
print("============ 立刻手动重置排行榜,会清除此排行榜当前所有成绩并保留在历史版本赛季数据中 ============")
response = reset_leaderboard(LEADERBOARD_SLUG)
print(response)
print("============ 获取一个排行榜的历史版本列表 ============")
response = list_leaderboard_history_versions(LEADERBOARD_SLUG)
print(response)
print("============ 获取排行榜某个历史版本中的成绩 ============")
response = list_leaderboard_history_scores(LEADERBOARD_SLUG, version_id)
print(response)
print("============ 获取历史排行榜中某个成员的成绩 ============")
response = get_leaderboard_member_history_scores(LEADERBOARD_SLUG, version_id, member_id_1)
print(response)
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
def list_leaderboards():
""" 获取所有排行榜的配置信息 """
url = API_ENDPOINT + '/v1/leaderboards'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_leaderboard(leaderboard_slug):
""" 获取某一个排行榜的配置信息 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def update_member_score(leaderboard_slug, member_id, score, bucket_id):
""" 更新排行榜成员分数,若需要玩家成绩排行榜,参数中memberId可填入玩家的personaId """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/scores'
data = {
"memberId": member_id,
"score": score,
"bucketId": bucket_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def batch_update_member_score(leaderboard_slug, member_scores):
""" 批量更新排行榜成员分数,当排行榜为用户自定义榜中榜时,需要指定玩家成绩的bucketId """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/scores/batch'
data = {
"memberScores": member_scores
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def list_leaderboard_scores(leaderboard_slug):
""" 获取排行榜的成绩列表 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/scores'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_leaderboard_member_score(leaderboard_slug, member_id, range=None):
""" 获取一个排行榜中某个成员的成绩 带range即查询该成员及其排名附近成员的成绩"""
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/members/' + member_id + '/scores'
params = {}
if range is not None:
params = {
'range': range
}
response = requests.get(url, headers=headers, params=params)
check_response(response)
return response.json()
def get_member_scores(member_id):
""" 查询该成员在所有排行榜中的成绩信息 """
url = API_ENDPOINT + '/v1/leaderboards/members/' + member_id + '/scores'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def delete_leaderboard_member_score(leaderboard_slug, member_id):
""" 删除排行榜中的成绩 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/scores'
params = {
'memberId': member_id
}
response = requests.delete(url, headers=headers, params=params)
check_response(response)
return response.json()
def list_member_bucket_scores(leaderboard_slug, member_id):
""" 获取排行榜中某个成员所在小榜的成绩列表,即同一bucketId下的所有成员成绩 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/members/' + member_id + '/scores-in-bucket'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def list_buckets(leaderboard_slug):
""" 查看所有自定义的bucketId """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/buckets'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def list_bucket_scores(leaderboard_slug, bucket_id):
""" 查看自定义的bucket中的成绩列表 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/buckets/search'
data = {
"bucketId": bucket_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_leaderboard_reset_schedule(leaderboard_slug):
""" 获取排行榜重置计划,可在UOS App排行榜页面点击进入某个排行榜详情后,在「重置管理」中设置 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/schedule'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def reset_leaderboard(leaderboard_slug):
""" 立刻手动重置排行榜,会清除此排行榜当前所有成绩并保留在历史版本赛季数据中 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/reset'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def list_leaderboard_history_versions(leaderboard_slug):
""" 获取一个排行榜的历史版本列表 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/versions'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def list_leaderboard_history_scores(leaderboard_slug, version_id):
""" 获取排行榜某个历史版本中的成绩 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/versions/' + version_id + '/scores'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_leaderboard_member_history_scores(leaderboard_slug, version_id, member_id):
""" 获取历史排行榜中某个成员的成绩 """
url = API_ENDPOINT + '/v1/leaderboards/' + leaderboard_slug + '/versions/' + version_id + '/members/' + member_id + '/scores'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Guild
支持公会配置、公会权限设置、查看公会列表和成员等操作。
公会 API 调用示例
# [UOS Passport - 公会]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/guild.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录过后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家角色的ID可通过登录后的返回值中的PersonaID获取,或者在UOS APP网页 - Passport - 账号 - 角色管理 页面可查看当前已有的角色列表
PERSONA_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(PERSONA_ID) == 0:
print(
"请在玩家登录之后,在PERSONA_ID处填入玩家角色的ID,登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 创建一个新的公会 ============")
# 由于一个玩家角色只能加入一个公会,如果遇到'已在公会中,无法创建/加入其他公会'错误,可更改的PERSONA_ID后重新运行
create_guild_data = {
"guildName": "testGuildName",
"guildType": "league",
"ownerId": PERSONA_ID,
"visibility": "public",
"announcement": "你好welcome!",
"properties": {
"color": "red",
"region": "Asia"
},
"enableGainApprovalBeforeJoin": True,
"namespace": "testNamespace"
}
response = create_guild(create_guild_data)
print(response)
guild_id = response.get('guild').get('id')
print("============ 获取公会信息 ============")
response = get_guild(guild_id)
print(response)
print("============ 获取公会列表 ============")
response = list_guilds()
print(response)
print("============ 游戏后台更新公会属性 ============")
system_properties = {
"level": "2"
}
response = update_guild_system_properties(guild_id, system_properties)
print(response)
print("============ 获取公会权限列表 ============")
print("============ 权限列表可在UOS网站的App下 - Passport - 公会 - 公会配置 中进行管理和查看 ============")
response = list_guild_roles()
print(response)
print("============ 游戏后台管理公会成员的权限(将会长更新为成员) ============")
response = manage_member_role(guild_id, PERSONA_ID, role_slug="member")
print(response)
print("============ 游戏后台管理公会成员的权限(重新更新为会长) ============")
response = manage_member_role(guild_id, PERSONA_ID, role_slug="owner")
print(response)
def create_guild(create_guild_data):
""" 创建一个新的公会 """
url = API_ENDPOINT + '/v1/guilds'
response = requests.post(url, headers=headers, json=create_guild_data)
check_response(response)
return response.json()
def get_guild(guild_id):
""" 获取公会信息 """
url = API_ENDPOINT + '/v1/guilds/' + guild_id
params = {
"withDetail": True
}
response = requests.get(url, headers=headers, params=params)
check_response(response)
return response.json()
def list_guilds():
""" 获取公会列表 """
url = API_ENDPOINT + '/v1/guilds'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def update_guild_system_properties(guild_id, system_properties):
""" 游戏后台更新公会属性 """
url = API_ENDPOINT + '/v1/guilds/' + guild_id
data = {
"systemProperties": system_properties
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def list_guild_roles():
""" 获取公会权限列表 """
url = API_ENDPOINT + '/v1/guilds/roles'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def manage_member_role(guild_id, persona_id, role_slug):
""" 游戏后台管理公会成员的权限 """
url = API_ENDPOINT + '/v1/guilds/' + guild_id + '/roles'
data = {
"memberId": persona_id,
"role": role_slug
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Token
支持查询指定的礼包活动,礼包码生成、查询、导出和作废等操作。
礼包 API 调用示例
# [UOS Passport - 礼包]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/token.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己的UOS App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后,在「设置」中获取
APP_ID = ""
APP_SERVICE_SECRET = ""
# 请前往[UOS App - Passport - 礼包]下创建一个新的礼包活动,礼包活动的类型选择唯一码,创建成功后发布礼包活动,并在此填入礼包活动的ID
TOKEN_CLASS_ID = ""
# 请在玩家登录过后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家角色的ID可通过登录后的返回值中的PersonaID获取,或者在UOS APP网页 - Passport - 账号 - 角色管理 页面可查看当前已有的角色列表
PERSONA_ID = ""
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
exit("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
if len(TOKEN_CLASS_ID) == 0:
exit("请前往[UOS App - Passport - 礼包]下创建一个新的礼包活动,礼包活动的类型选择唯一码,创建成功后发布礼包活动,并在此填入礼包活动的ID")
def run():
# 获取礼包活动详情
print("============ 获取礼包活动 ============")
response = get_token_class(TOKEN_CLASS_ID)
print(f"获取礼包活动成功\n{response}\n")
# 生成礼包码
print("============ 生成礼包码 ============")
generate_options = {
"tokenClassId": TOKEN_CLASS_ID,
"quantity": 20,
"batch": "20240101_00001",
}
response = generate_tokens(generate_options)
print(f"生成礼包码成功\n{response}\n")
batch1 = response["batch"]
# 生成另一批次的礼包码
print("============ 生成礼包码 ============")
generate_options = {
"tokenClassId": TOKEN_CLASS_ID,
"quantity": 20,
"batch": "20240101_00002",
}
response = generate_tokens(generate_options)
print(f"生成礼包码成功\n{response}\n")
batch2 = response["batch"]
# 搜索礼包活动下,未使用的礼包码信息
print("============ 生成礼包码 ============")
search_options = {
"tokenClassId": TOKEN_CLASS_ID,
"fulfilled": False,
}
response = search_token_instances(search_options)
print(f"搜索礼包码成功\n{response}\n")
instances = response["tokenInstances"]
instance1 = instances[0]
# 获取礼包码详情
print("============ 获取礼包码 ============")
response = get_token_instance(instance1["id"])
print(f"获取礼包码成功\n{response}\n")
# 作废单个礼包码
print("============ 作废礼包码 ============")
response = invalidate_token(instance1["id"])
print(f"作废礼包码成功\n{response}\n")
# 批量作废指定批次的礼包码
print("============ 批量作废礼包码 ============")
batch_options = {
"tokenClassId": TOKEN_CLASS_ID,
"batch": batch1,
}
response = invalidate_batch_tokens(batch_options)
print(f"批量作废礼包码成功\n{response}\n")
# 导出指定批次中未使用的礼包码
print("============ 导出礼包码 ============")
export_options = {
"tokenClassId": TOKEN_CLASS_ID,
"batch": batch2,
"fulfilled": False
}
response = export_tokens(export_options)
print(f"导出礼包码成功\n{response}\n")
# 生成一批带自定义属性的礼包码
print("============ 生成自定义属性礼包码 ============")
generate_options = {
"tokenClassId": TOKEN_CLASS_ID,
"quantity": 2,
"batch": "batch_properties_00001",
"propertiesKeys": "key1,key2",
"propertiesValues": ["value01,value02", "value11,value12"]
}
response = generate_tokens(generate_options)
print(f"生成礼包码成功\n{response}\n")
instances = response["instances"]
code = instances[0]
# 核销礼包码
print("============ 核销礼包码 ============")
redeem_options ={
"code": code,
"personaId": PERSONA_ID
}
response = redeem_token(redeem_options)
print(f"核销礼包码成功\n{response}\n")
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
def get_token_class(token_class_id):
""" 查看指定的礼包活动详情 """
url = API_ENDPOINT + '/v1/token/classes/' + token_class_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def generate_tokens(data):
""" 生成礼包码 """
url = API_ENDPOINT + '/v1/token/instances/generate'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def redeem_token(data):
""" 核销礼包码 """
url = API_ENDPOINT + '/v1/token/instances/redeem'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def invalidate_token(token_instance_id):
""" 作废指定的礼包码 """
url = API_ENDPOINT + f'/v1/token/instances/{token_instance_id}/invalidate'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def invalidate_batch_tokens(data):
""" 批量作废指定批次的礼包码 """
url = API_ENDPOINT + '/v1/token/instances/invalidate'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_token_instance(token_instance_id):
""" 查看指定的礼包码详情 """
url = API_ENDPOINT + '/v1/token/instances/' + token_instance_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def search_token_instances(data):
""" 搜索符合查询条件的礼包码 """
url = API_ENDPOINT + '/v1/token/instances/search'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def export_tokens(data):
""" 导出礼包码 """
url = API_ENDPOINT + '/v1/token/instances/export'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Achievement
支持获取成就配置列表。
成就 API 调用示例
# [UOS Passport - 成就]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/achievement.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
def run():
print("============ 获取成就配置列表 ============")
# 若此项为空,可前往UOS App - Passport - 成就 - 成就配置 下创建一个新的成就配置
response = search_achievement_meta()
print(response)
def search_achievement_meta():
""" 获取成就配置列表 """
url = API_ENDPOINT + '/v1/achievements/meta/search'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Economy
支持真实货币购买、查询交易记录和背包资源的相关操作。
经济系统 API 调用示例
# [UOS Passport - 经济系统]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/economy.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请前往UOS App - Passport - 经济系统 - 资源 下创建一个新的「物品」,并在此填入物品的唯一标识SlugName
RESOURCE_SLUG = ''
# 请前往UOS App - Passport - 经济系统 - 商品 下创建一个新的「商品」,商品的「消耗」请选择「人民币CNY」,「消耗数量」填1,并在此填入物品的唯一标识SlugName。注意在创建成功后需要「发布」商品。
PRODUCT_SLUG = ''
# 请在玩家登录过后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 玩家角色的ID可通过登录后的返回值中的PersonaID获取,或者在UOS APP网页 - Passport - 账号 - 角色管理 页面可查看当前已有的角色列表
PERSONA_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
if len(RESOURCE_SLUG) == 0:
print(
"请前往UOS App - Passport - 经济系统 - 资源 下创建一个新的「物品」,并在RESOURCE_SLUG处填入物品的唯一标识SlugName")
exit(1)
if len(PRODUCT_SLUG) == 0:
print(
"请前往UOS App - Passport - 经济系统 - 商品 下创建一个新的「商品」,商品的「消耗」请选择「人民币CNY」,「消耗数量」填1,并在PRODUCT_SLUG处填入物品的唯一标识SlugName。注意在创建成功后需要「发布」商品。")
exit(1)
if len(PERSONA_ID) == 0:
print(
"请在玩家登录之后,在PERSONA_ID处填入玩家角色的ID,登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html")
exit(1)
def run():
print("============ 增加角色背包内资源 ============")
response = deposit_resources(PERSONA_ID, RESOURCE_SLUG, quantity=10)
print(response)
inventory_item_id = response.get('inventoryItems')[0].get('inventoryItemId')
print("============ 更新背包资源属性 ============")
custom_data = {
"level": "2"
}
response = update_inventory_custom_data(inventory_item_id, custom_data)
print(response)
print("============ 消耗角色背包内资源 ============")
response = consume_resources(PERSONA_ID, inventory_item_id, quantity=1)
print(response)
print("============ 搜索背包信息 ============")
response = search_inventory(PERSONA_ID)
print(response)
print("============ 真实货币购买 ============")
# 如果出现“请求金额与商品金额不一致”错误,请修改amount为PRODUCT_SLUG商品购买需要消耗的人民币数额
response = real_money_purchase(PERSONA_ID, PRODUCT_SLUG, amount=1)
print(response)
print("============ 查找交易记录 ============")
response = search_transactions(PERSONA_ID)
print(response)
def deposit_resources(persona_id, resource_slug, quantity):
""" 增加角色背包内资源 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/inventory/deposit'
data = {
"depositResources": [
{
"resourceSlug": resource_slug,
"depositQuantity": quantity
}
]
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def update_inventory_custom_data(inventory_item_id, custom_data):
""" 更新背包资源属性 """
url = API_ENDPOINT + '/v1/personas/inventory/' + inventory_item_id
data = {
"customData": custom_data
}
response = requests.put(url, headers=headers, json=data)
check_response(response)
return response.json()
def search_inventory(persona_id):
""" 搜索背包信息 """
url = API_ENDPOINT + '/v1/inventory/search'
data = {
"personaId": persona_id,
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def consume_resources(persona_id, inventory_item_id, quantity):
""" 消耗角色背包内资源 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/inventory/consume'
data = {
"inventoryItems": [
{
"inventoryItemId": inventory_item_id,
"consumeQuantity": quantity
}
]
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def real_money_purchase(persona_id, product_slug, amount):
""" 真是货币购买 """
url = API_ENDPOINT + '/v1/products/purchase'
data = {
"personaId": persona_id,
"currency": "CNY",
"amount": amount,
"productSlug": product_slug,
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def search_transactions(persona_id):
""" 查找交易记录 """
url = API_ENDPOINT + '/v1/transactions/search'
data = {
"personaId": persona_id
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Inbox
支持邮件的发送以及模版的创建和获取。
邮件 API 调用示例
# [UOS Passport - 邮件]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/inbox.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己的UOS App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后,在「设置」中获取
APP_ID = ""
APP_SERVICE_SECRET = ""
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
exit("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
def run():
# 创建一个新的邮件模板,这一步推荐在UOS Dev Portal进行配置
print("============ 创建模板 ============")
create_data = {
"slugName": "update_2_1",
"displayName": "更新公告_2.1",
"title": "版本更新公告",
"subtitle": "2.1版本全服停机更新公告",
"body": "各位玩家,全服将于X月X日8:00 - 11:00进行停机更新",
"attachment": [],
"source": "系统邮件",
"targetScope": "All",
"expiredTimeInHours": 720,
}
response = create_inbox_template(create_data)
print(f"创建模板成功\n{response}\n")
# 根据模板slug获取邮件模板
print("============ 获取模板 ============")
template_slug = "update_2_1"
response = get_inbox_template(template_slug)
print(f"获取模板成功\n{response}\n")
# 发送邮件
print("============ 发送邮件 ============")
send_data = {
"templateSlug": template_slug
}
response = send_inbox_message(send_data)
print(f"发送邮件成功\n{response}\n")
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
def create_inbox_template(data):
""" 创建邮件模板 """
url = API_ENDPOINT + '/v1/inbox/templates'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_inbox_template(template_slug):
""" 获取邮件模板 """
url = API_ENDPOINT + '/v1/inbox/templates/' + template_slug
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def send_inbox_message(data):
""" 发送邮件 """
url = API_ENDPOINT + '/v1/inbox/messages'
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Billboard
支持获取公告列表、查看公告详情等。
公告 API 调用示例
# [UOS Passport - 公告]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/billboard.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print(len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0)
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
def run():
print("============ 创建公告 ============")
response = create_billboard()
print(response)
print("============ 更新公告 ============")
response = update_billboard()
print(response)
print("============ 搜索公告 ============")
response = search_billboard()
print(response)
print("============ 获取公告详情 ============")
billboard_id = response.get("billboards")[0].get("id")
response = get_billboard(billboard_id)
print(response)
print("============ 发布公告 ============")
response = publish_billboard(billboard_id)
print(response)
print("============ 撤销公告 ============")
response = revoke_billboard(billboard_id)
print(response)
print("============ 获取公告命名空间列表 ============")
response = list_billboard_namespaces()
print(response)
def create_billboard():
""" 创建公告 """
url = API_ENDPOINT + '/v1/billboards'
data = {
"namespace": "Activity",
"title": "关于停服更新的通知",
"briefTitle": "通知",
"content": "下周停服更新",
"dimensions": [
"ios"
],
"properties": {},
"expiredAt": "2080-11-23T07:36:00.0000Z"
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def update_billboard():
""" 更新公告 """
url = API_ENDPOINT + '/v1/billboards'
data = {
"namespace": "Announcement",
"title": "关于停服更新的通知2",
"briefTitle": "通知2",
"content": "下下周停服更新",
"dimensions": [
"ios"
],
"properties": {},
"expiredAt": "2080-12-23T07:36:00.0000Z"
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def search_billboard():
""" 搜索公告 """
url = API_ENDPOINT + '/v1/billboards/search'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def get_billboard(billboard_id):
""" 获取公告详情 """
url = API_ENDPOINT + '/v1/billboards/' + billboard_id
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def publish_billboard(billboard_id):
""" 发布公告 """
url = API_ENDPOINT + '/v1/billboards/' + billboard_id + '/publish'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def revoke_billboard(billboard_id):
""" 撤销公告 """
url = API_ENDPOINT + '/v1/billboards/' + billboard_id + '/revoke'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def list_billboard_namespaces():
""" 获取公告命名空间列表 """
url = API_ENDPOINT + '/v1/billboards/namespaces'
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)BattlePass
支持获取战令、解锁奖励槽等操作。
战令 API 调用示例
# [UOS Passport - 战令]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/battlepass.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己的UOS App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后,在「设置」中获取
APP_ID = ""
APP_SERVICE_SECRET = ""
# 请前往[UOS App - Passport - 战令]下创建一个新的战令,并为其配置付费的奖励槽。创建成功后发布战令,并在此处填入战令的SlugName
BATTLE_PASS_SLUG = ""
# 请在玩家登录并初始化战令后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 初始化战令的过程可参考「战令 - 初始化角色战令」:https://uos.unity.cn/docs/passport/battlepass.html#initPersonaBp
PERSONA_ID = ""
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
exit("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
if len(BATTLE_PASS_SLUG) == 0:
exit("请前往[UOS App - Passport - 战令]下创建一个新的战令,并为其配置付费的奖励槽。创建成功后发布战令,并在此处填入战令的SlugName")
if len(PERSONA_ID) == 0:
exit("请在玩家登录并初始化战令后,在此填入玩家角色的ID")
def run():
# 获取礼包活动详情
print("============ 获取角色战令 ============")
response = get_persona_battle_pass(PERSONA_ID, BATTLE_PASS_SLUG)
print(f"获取角色战令成功\n{response}\n")
battle_pass = response["battlePass"]
# 解锁角色战令下的所有付费奖励槽
print("============ 解锁奖励槽 ============")
for slot in battle_pass["slots"]:
if slot["type"] == "Paid":
response = activate_slot(PERSONA_ID, slot["slugName"])
print(f"解锁奖励槽成功\n{response}\n")
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
def get_persona_battle_pass(persona_id, battle_pass_slug):
""" 查看指定的角色战令详情 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/battle-pass/' + battle_pass_slug
response = requests.get(url, headers=headers)
check_response(response)
return response.json()
def activate_slot(persona_id, slot_slug):
""" 解锁角色战令的奖励槽 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/battle-pass/activate-slot'
data = {
"slotSlug": slot_slug
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Quest
支持搜索任务配置、获取角色任务详情。
任务集 API 调用示例
# [UOS Passport - 任务]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/quest.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录并初始化任务集后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
# 初始化任务集的过程可参考「任务 - 同步初始化角色任务」:https://uos.unity.cn/docs/passport/quest.html#fetchPersonaQuests
PERSONA_ID = ''
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print(len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0)
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
def run():
print("============ 搜索任务配置 ============")
# 若此项为空,可前往UOS App - Passport - 任务 下创建一个新的任务
response = search_quests()
print(response)
print("============ 获取角色任务详情 ============")
response = search_persona_quests(PERSONA_ID)
print(response)
def search_quests():
""" 搜索任务配置 """
url = API_ENDPOINT + '/v1/quests/search'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def search_persona_quests(persona_id):
""" 获取角色任务详情 """
url = API_ENDPOINT + '/v1/personas/' + persona_id + '/quests/search'
response = requests.post(url, headers=headers)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)Payment
经济系统线上支付相关,包括创建交易记录、处理支付回调。
线上支付 API 调用示例
# [UOS Passport - 线上支付]服务端API使用示例
# 功能模块具体使用方法可参考https://uos.unity.cn/docs/passport/payment.html
# API完整参数列表可参考https://uos.unity.cn/docs/passport/server-api.html
import random
# -*-coding: utf-8-*-
import requests
import base64
import json
API_ENDPOINT = "https://p.unity.cn"
# 请填入自己UOS App的App ID和App Service Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取
APP_ID = ''
APP_SERVICE_SECRET = ''
# 请在玩家登录后,在此填入玩家角色的ID
# 登录方式和过程可参考「Passport登录」:https://uos.unity.cn/docs/passport/login.html 或 「External登录」:https://uos.unity.cn/docs/passport/external-login.html
PERSONA_ID = ''
# 请配置好人民币购买的商品并发布后,在此填入商品slug
# 具体配置商品过程可参考「线上支付 - 资源商品配置」:https://uos.unity.cn/docs/passport/payment#passport-product.html
PRODUCT_SLUG = ''
# 在此填入上方商品购买所需要的人名币价格,单位为分
PRODUCT_PRICE =
# 唯一订单号,此处用随机数模拟
OUT_TRADE_NO = str(random.randint(1000, 9999))
if len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0:
print(len(APP_ID) == 0 or len(APP_SERVICE_SECRET) == 0)
print("请填入自己UOS App的App ID和App Secret,可前往https://uos.unity.cn/apps下进入App后在「设置」中获取")
exit(1)
def run():
print("============ 创建交易记录 ============")
response = create_payment(PERSONA_ID, PRODUCT_SLUG, PRODUCT_PRICE, OUT_TRADE_NO)
print(response)
print("============ 支付回调 ============")
response = payment_notify(OUT_TRADE_NO, PRODUCT_PRICE, "TRADE_SUCCESS", True)
print(response)
def create_payment(persona_id, product_slug, product_price, out_trade_no):
""" 创建交易记录 """
url = API_ENDPOINT + '/v1/payments'
data = {
"personaId": persona_id,
"outTradeNo": out_trade_no,
"paymentMethod": "alipay.trade.page.pay",
"totalAmount": product_price,
"productSlug": product_slug,
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def payment_notify(out_trade_no, product_price, trade_state, payment_success):
""" 支付回调 """
url = API_ENDPOINT + '/v1/payments/notify'
data = {
"outTradeNo": out_trade_no,
"tradeState": trade_state,
"totalAmount": product_price,
"paymentSuccess": payment_success
}
response = requests.post(url, headers=headers, json=data)
check_response(response)
return response.json()
def get_basic_authorization(app_id, app_secret):
""" 获取basic auth的Header """
credentials = f'{app_id}:{app_secret}'
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return {'Authorization': f'Basic {encoded_credentials}'}
headers = get_basic_authorization(APP_ID, APP_SERVICE_SECRET)
# 校验Response
def check_response(response):
""" 校验Response,如果有错误,抛出异常值 """
if not response.ok:
try:
error_message = response.json()
except json.JSONDecodeError:
error_message = response.text
raise Exception(f"Error {response.status_code}: {error_message}")
if __name__ == "__main__":
try:
run()
except Exception as e:
print(e)