ゲームサーバーにフルフィルメントを実装する
注釈:本資料はAI技術を用いて翻訳されています。
概要
この記事では、コード引き換えの実装方法と、ゲームサーバーがプレイヤーにアイテムを付与できるようにする方法について説明します。
コード引き換え
プレイヤーはキャンペーンコードを引き換えて、ゲーム、ゲーム内アイテム、コインなどのエンタイトルメントを受け取ることができます。コードを引き換えるには、Fulfillment API の RedeemCode を呼び出します。次の条件を満たすと、コードが引き換えられ、プレイヤーはエンタイトルメントを受け取ります。
- コードがゲームネームスペースに存在する
- 最大引き換え回数に達していない
- 引き換えの日時が引き換え期間内である
- Unreal Engine
- Unity
- C# Extend SDK
- Go Extend SDK
- Java Extend SDK
- Python Extend SDK
FString Code = FString("MyRedeemCode");
FString Region = FString("US"); // Leave it blank if you want to use the default value from user token
FString Language = FString("en"); // Leave it blank if you want to use the default value from user token
auto ApiClient = AccelByteOnlineSubsystemPtr->GetApiClient();
auto FulfillmentApi = ApiClient->GetFulfillmentApi().Pin();
FulfillmentApi->RedeemCode(Code, Region, Language, THandler<FAccelByteModelsFulfillmentResult>::CreateLambda([](const FAccelByteModelsFulfillmentResult& Result)
{
// Do something if RedeemCode succeeds
}),
FErrorHandler::CreateLambda([](int32 ErrorCode, const FString& ErrorMessage)
{
// Do something if RedeemCode fails
UE_LOG(LogTemp, Log, TEXT("Error RedeemCode, Error Code: %d Error Message: %s"), ErrorCode, *ErrorMessage);
}));
string code= "some-code";
string region = "US";
string language = "en";
AccelByteSDK.GetClientRegistry().GetApi().GetFulfillment().RedeemCode(code, region, language, result =>
{
if (result.IsError)
{
// Do something if RedeemCode fails
Debug.Log($"Error RedeemCode, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
}
else
{
// Do something if RedeemCode succeeds
}
});
string userId = "<user-id>";
var response = sdk.Platform.Fulfillment.PublicRedeemCodeOp
.SetBody(new FulfillCodeRequest()
{
Code = "<some-code>",
Region = "US",
Language = "en"
})
.Execute(sdk.Namespace, userId);
if (response != null)
{
//do something if success
}
fulfillmentService := &platform.FulfillmentService{
Client: factory.NewPlatformClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
userId := "myuserid"
code := "somecode"
body := platformclientmodels.FulfillCodeRequest {
Code: &code,
Region: "US",
Language: "en",
}
input := &fulfillment.PublicRedeemCodeParams{
Body: &body,
Namespace: namespace,
UserID: userId,
}
result, err := fulfillmentService.PublicRedeemCodeShort(input)
Fulfillment fulfillmentWrapper = new Fulfillment(sdk);
String userId = "<user-id>";
FulfillmentResult response;
try {
FulfillCodeRequest reqBody = FulfillCodeRequest.builder()
.code("<some-code>")
.region("US")
.language("en")
.build();
response = fulfillmentWrapper.publicRedeemCode(PublicRedeemCode.builder()
.namespace("<namespace>")
.userId(userId)
.body(reqBody)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something when successful
}
import accelbyte_py_sdk.api.platform as platform_service
import accelbyte_py_sdk.api.platform.models as platform_models
result, error = platform_service.public_redeem_code(
body=platform_models.FulfillCodeRequest()
.with_code("MyRedeemCode")
.with_language("en")
.with_region("US"),
user_id="********************************",
namespace=namespace, # optional, gets the value from the global instance if unspecified
sdk=sdk, # optional, gets the global instance if unspecified
)
if error:
exit(error)
ゲームサーバーがプレイヤーにアイテムを付与する
信頼できるゲームサーバーまたはバックエンドからアイテムを付与するには、Fulfillment V3 を使用します。
PUT /platform/v3/admin/namespaces/{namespace}/users/{userId}/fulfillments/{transactionId}
対象の環境がこのエンドポイントをサポートしている必要があります。ADMIN:NAMESPACE:{namespace}:USER:{userId}:FULFILLMENT 権限と UPDATE アクション(2)を持つサーバーアクセストークンを使用してください。従来の CREATE 権限のみが設定されているクライアントには、この権限を追加する必要があります。サーバーの認証情報をゲームクライアントに含めないでください。
リクエストを送信する前に、論理的な付与処理ごとにトランザクション ID を生成し、永続化してください。その付与処理を再試行するときは、同じ ID とペイロードを使用します。ユーザー、アイテム、数量が同じでも、新しい報酬には新しい ID を使用する必要があります。再試行のたびに新しい ID を生成しないでください。
このエンドポイントは FulfillmentV2Request を受け取り、FulfillmentV2Result を返します。モデル名によってエンドポイントのバージョンが変わるわけではありません。FulfillmentV3Request は、別の一括処理用エンドポイントでのみ使用してください。
統合方法を選択する
以下の公開済み Extend SDK バージョンには、後述の例で使用するメソッドが含まれています。これらは検証済みの参照バージョンであり、V3 が初めて導入された最小バージョンを示すものではありません。各 SDK のインストール手順に従い、アップグレード前に互換性を確認してください。
| 統合方法 | 公開済みの参照バージョン | 付与メソッド |
|---|---|---|
| Go Extend SDK | v0.89.1 | FulfillmentService.FulfillItemsV3Short |
| Java Extend SDK | v0.82.0 | Fulfillment.fulfillItemsV3 |
| C# Extend SDK | v0.81.0 | Fulfillment.FulfillItemsV3 |
| Python Extend SDK | v0.85.1 | platform.fulfill_items_v3 |
Unreal SDK 28.10.1 と Unity SDK 17.17.1 の FulfillUserItem は、引き続き非推奨の V1 エンドポイントを呼び出します。V3 を使用するには、信頼できるサーバーから以下の REST リクエストを送信するか、Extend SDK で実装したバックエンドを呼び出してください。リクエストとレスポンスの構造が異なるため、V1 SDK メソッドの URL を V3 の URL に置き換えないでください。
REST リクエスト
以下の環境変数をサーバーの値に置き換えてください。AB_BASE_URL は /platform を含まない環境の URL、AB_ACCESS_TOKEN はサーバーアクセストークンです。AB_ITEM_ID をカタログのアイテム ID に、AB_TRANSACTION_ID を今回の付与処理のために永続化した ID に置き換えてください。
curl --fail-with-body --request PUT \
"${AB_BASE_URL}/platform/v3/admin/namespaces/${AB_NAMESPACE}/users/${AB_USER_ID}/fulfillments/${AB_TRANSACTION_ID}" \
--header "Authorization: Bearer ${AB_ACCESS_TOKEN}" \
--header 'Content-Type: application/json' \
--data "{\"items\":[{\"itemId\":\"${AB_ITEM_ID}\",\"quantity\":1,\"source\":\"REWARD\"}]}"
HTTP 200 レスポンスでも、トランザクションの一部が失敗している場合があります。結果を処理するの説明に従い、state と stateInfo を確認してください。
Extend SDK の例
以下の例では、対象環境で認証済みの sdk または fulfillmentService が初期化されていることを前提とします。プレースホルダーをネームスペース、プレイヤー ID、アイテム ID、永続化したトランザクション ID に置き換えてください。SDK の例外や返されたエラーは、アプリケーションのエラー処理方針に従って処理してください。
- C# Extend SDK
- Go Extend SDK
- Java Extend SDK
- Python Extend SDK
using System;
using System.Collections.Generic;
using AccelByte.Sdk.Api.Platform.Model;
using AccelByte.Sdk.Api.Platform.Operation;
var body = new FulfillmentV2Request
{
Items = new List<FulfillmentV2RequestItem>
{
new FulfillmentV2RequestItem
{
ItemId = "<ItemId>",
Quantity = 1,
Source = FulfillmentV2RequestItemSource.REWARD
}
}
};
var operation = FulfillItemsV3.Builder.Build(
body, "<YourNamespace>", "<PersistedTransactionId>", "<PlayerUserId>");
var result = sdk.Platform.Fulfillment.FulfillItemsV3(operation);
if (result == null || result.State != FulfillmentV2ResultState.FULFILLED)
{
// Inspect StateInfo and classify the failure before retrying.
throw new InvalidOperationException("Fulfillment is incomplete; inspect the transaction.");
}
import (
"fmt"
"github.com/AccelByte/accelbyte-go-sdk/platform-sdk/pkg/platformclient/fulfillment"
"github.com/AccelByte/accelbyte-go-sdk/platform-sdk/pkg/platformclientmodels"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/service/platform"
)
func grantItem(service *platform.FulfillmentService, namespace, userID, itemID, transactionID string) error {
quantity := int32(1)
result, err := service.FulfillItemsV3Short(&fulfillment.FulfillItemsV3Params{
Namespace: namespace,
UserID: userID,
TransactionID: transactionID,
Body: &platformclientmodels.FulfillmentV2Request{
Items: []*platformclientmodels.FulfillmentV2RequestItem{
{ItemID: itemID, Quantity: &quantity, Source: "REWARD"},
},
},
})
if err != nil {
return err
}
if result == nil || result.State == nil || *result.State != "FULFILLED" {
// Inspect StateInfo and classify the failure before retrying.
return fmt.Errorf("fulfillment %s is incomplete; inspect the transaction", transactionID)
}
return nil
}
import java.util.Collections;
import net.accelbyte.sdk.api.platform.models.FulfillmentV2Request;
import net.accelbyte.sdk.api.platform.models.FulfillmentV2RequestItem;
import net.accelbyte.sdk.api.platform.models.FulfillmentV2Result;
import net.accelbyte.sdk.api.platform.operations.fulfillment.FulfillItemsV3;
import net.accelbyte.sdk.api.platform.wrappers.Fulfillment;
Fulfillment fulfillment = new Fulfillment(sdk);
FulfillmentV2Request body = FulfillmentV2Request.builder()
.items(Collections.singletonList(FulfillmentV2RequestItem.builder()
.itemId("<ItemId>")
.quantity(1)
.source("REWARD")
.build()))
.build();
FulfillmentV2Result result = fulfillment.fulfillItemsV3(FulfillItemsV3.builder()
.namespace("<YourNamespace>")
.userId("<PlayerUserId>")
.transactionId("<PersistedTransactionId>")
.body(body)
.build());
if (result == null || !"FULFILLED".equals(result.getState())) {
// Inspect stateInfo and classify the failure before retrying.
throw new IllegalStateException("Fulfillment is incomplete; inspect the transaction.");
}
import accelbyte_py_sdk.api.platform as platform_service
import accelbyte_py_sdk.api.platform.models as platform_models
result, error = platform_service.fulfill_items_v3(
body=platform_models.FulfillmentV2Request.create(
items=[platform_models.FulfillmentV2RequestItem.create(
item_id="<ItemId>",
quantity=1,
source="REWARD",
)],
),
namespace="<YourNamespace>",
user_id="<PlayerUserId>",
transaction_id="<PersistedTransactionId>",
sdk=sdk,
)
if error:
raise RuntimeError(str(error))
if result is None or result.state != "FULFILLED":
# Inspect state_info and classify the failure before retrying.
raise RuntimeError("Fulfillment is incomplete; inspect the transaction.")
結果を処理する
state == "FULFILLED"は、トランザクションの完了を示します。entitlementSummariesが空でも失敗を意味しません。完了済みのトランザクションでは新たな付与は返されず、アイテムタイプによっては別のサマリーが使用されます。FULFILL_FAILEDの場合は、stateInfo.failedListとその中のバンドルのitemsを調べて、エラーを確認してください。処理に成功した構成アイテムは、付与済みのまま残る場合があります。再試行の前に原因を修正し、永続的な設定エラーに対して無制限に再試行しないでください。- Retry Fulfillment V3 を使用すると、リクエストボディを再送せずに、保存済みのトランザクションを再試行できます。または、同じトランザクション ID とペイロードで元の付与リクエストを再送してください。成功状態が保存されている構成アイテムはスキップされます。
- アセットの書き込みとフルフィルメント状態の永続化は、アトミックな処理ではありません。処理が中断された場合やネットワーク障害で結果が不明な場合は、再試行する前にトランザクションと付与済みアセットを照合してください。V3 は、無条件に厳密に 1 回だけ実行されることを保証するものではありません。
サポートされるアイテムタイプ、リクエストフィールド、トランザクションのクエリ、取り消しの制限については、サードパーティストアでアイテムのフルフィルメントを管理するを参照してください。