Cocos Creator用のSDK / アプリケーション側でSDKを統合する
 ドキュメントに戻る

Cocos Creator用のSDK

  • 統合ガイド

  • デモプロジェクト

  • 認証

  • カタログ

  • プロモーション

  • サブスクリプション

  • 商品購入

  • プレイヤーインベントリ

  • ユーザーアカウントと属性


  • アプリケーション側でSDKを統合する

    1. ログインシステム、インゲームストアなど、アプリケーションのページのインターフェイスをデザインします。
    2. SDKメソッドを使って、ユーザー認証、ストア表示、購入などのロジックをアプリケーションに実装できます。

    お知らせ
    Cocos Creatorマニュアルに従って独自のソリューションを作成することもできますし、デモシーンをテンプレートとして使用することもできます。

    基本的なSDK機能の使用を開始するには、次のステップバイステップのチュートリアルに従ってください:

    使用されるスクリプトは、SDKの<xsollaExtention>/assets/scripts/samplesディレクトリにあります。

    お知らせ
    チュートリアルのスクリプトではSDKメソッドを使用します。SDKを正しくインストールし、初期化していることを確認してください。

    ユーザー名/メールアドレスとパスワードによるユーザーの新規登録とログイン

    この説明では、SDKのメソッドを使用して実装する方法を示します:

    ユーザーの認証は、ユーザー名またはメールアドレスで行うことができます。以下の例では、ユーザー名でユーザーを認証し、メールアドレスは登録の確認やパスワードのリセットに使用します。

    お知らせ
    ログインウィジェットをサイト(ウェブストアなど)で使用する場合は、サイトとアプリケーションで同じユーザー認証方法を実装していることを確認してください。デフォルトでは、ウィジェットは認証に電子メールアドレスを使用します。ユーザー名によるユーザーログインを設定するには、カスタマーサクセスマネージャーまでお問い合わせるか、csm@xsolla.comに電子メールを送信してください。

    ユーザー登録を実装する

    このチュートリアルでは、以下のロジックの実装について説明します:

    ページのインターフェースを作成する

    新規登録ページのシーンを作り、そこに以下の要素を追加します:

    • ユーザー名フィールド
    • ユーザーEメールアドレスフィールド
    • ユーザーパスワードフィールド
    • 新規登録ボタン

    ページ構造の例:

    登録スクリプトコンポーネントを作成する

    1. RegistrationComponentを作成し、次のプロパティを追加します:
      • usernameEditBox
      • emailEditBox
      • passwordEditBox
      • signUpButton — 任意。コードを使用してコールバック関数をボタンにバインドするときに使用されます

    1. スクリプトの例に示すように、SignUpButtonをクリックしたときに呼び出されるメソッドをRegistrationComponentクラスに追加し、クリックイベントを処理するロジックを追加します。
    2. RegistrationComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、シーン要素をRegistrationComponentのプロパティにバインドします:

    1. 以下のいずれかの方法で、新規登録ボタンにコールバックをバインドします:
      • 下の図に示すように、Inspectorパネルを使用します。
      • 以下のコードブロックをページスクリプトに挿入する。

    Inspectorパネルを使用してコールバックをバインドします:

    コード経由でコールバックをバインドします:

    Copy
    Full screen
    Small screen

    start() {
     this.signUpButton.node.on(Button.EventType.CLICK, this.onSignUpClicked, this);
     }
    

    お知らせ

    スクリプトの例では、onCompleteonErrorメソッドは標準のconsole.logメソッドを呼び出します。エラーが発生した場合、エラーコードと説明がerrorパラメータで渡されます。

    登録メールの再送リクエストのページを開いたり、登録が成功した場合にログインページを開くなど、他のアクションを追加することができます。

    クラススクリプト(RegistrationComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Button, Component, EditBox } from 'cc';
    import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('RegistrationComponent')
    export class RegistrationComponent extends Component {
    
        @property(EditBox)
        usernameEditBox: EditBox;
    
        @property(EditBox)
        emailEditBox: EditBox;
    
        @property(EditBox)
        passwordEditBox: EditBox;
    
        @property(Button)
        signUpButton: Button;
    
        start() {
            this.signUpButton.node.on(Button.EventType.CLICK, this.onSignUpClicked, this);
        }
    
        onSignUpClicked() {
            XsollaAuth.registerNewUser(this.usernameEditBox.string, this.passwordEditBox.string, this.emailEditBox.string, 'xsollatest', null, null, token => {
                if(token != null) {
                    console.log(`Successful login. Token - ${token.access_token}`);
                }
                else {
                    console.log('Thank you! We have sent you a confirmation email');
                }
            }, err => {
                console.log(err);
            });
        }
    }
    

    登録の確認メールを設定する

    登録に成功すると、ユーザーは指定したアドレスに登録確認メールを受け取ります。アドミンページで、ユーザーに送られるメールはカスタマイズできます。

    モバイルアプリケーションを開発している場合、ユーザーが登録を確認した後、アプリケーションに戻るためのディープリンクをセットアップします。

    お知らせ
    お客様のセキュリティ基準で許可されている場合は、電子メールアドレスによる登録確認を無効にすることができます。無効にするには、カスタマーサクセスマネージャーに連絡するか、csm@xsolla.comまでご連絡ください。

    登録確認メールの再送依頼を実装する

    このチュートリアルでは、以下のロジックの実装について説明します:

    ページのインターフェースを作成する

    確認メールの再送信依頼があるページのシーンを作り、そこに以下の要素を追加します:

    • ユーザー名/メールアドレスフィールド
    • メール再送信ボタン

    ページ構造の例:

    メール再送スクリプトコンポーネントを作成する

    1. ResendConfirmationEmailComponentを作成し、次のプロパティを追加します:
      • usernameTextBox
      • resendEmailButton — 任意。コードを使用してコールバック関数をボタンにバインドするときに使用されます

    1. スクリプトの例に示すように、ResendEmailをクリックしたときに呼び出されるメソッドをResendConfirmationEmailComponentクラスに追加し、クリックイベントを処理するロジックを追加します。
    2. ResendConfirmationEmailComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、シーン要素をResendConfirmationEmailComponentのプロパティにバインドします:

    1. 以下のいずれかの方法でコールバックを新規登録確認メールのリクエストボタンにバインドします
      • 下の図に示すように、Inspectorパネルを使用する
      • 以下のコードブロックを、確認メールを再送するリクエストとともにページのスクリプトに挿入する

    Inspectorパネルを使用してコールバックをバインドします:

    コード経由でコールバックをバインドします:

    Copy
    Full screen
    Small screen

    start() {
        this.resendEmailButton.node.on(Button.EventType.CLICK, this.onResendEmailClicked, this);
      }
    

    リクエストが成功した場合、ユーザーは登録時に指定したメールアドレスに登録確認メールを受け取ります。

    お知らせ

    スクリプトの例では、onCompleteonErrorメソッドは標準のconsole.logメソッドを呼び出します。他のアクションを追加することができます。

    エラーが発生した場合、エラーコードと説明がerrorパラメータで渡されます。

    クラススクリプト(ResendConfirmationEmailComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Button, Component, EditBox } from 'cc';
    import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('ResendConfirmationEmailComponent')
    export class ResendConfirmationEmailComponent extends Component {
    
        @property(EditBox)
        usernameEditBox: EditBox;
    
        @property(Button)
        resendEmailButton: Button;
    
        start() {
            this.resendEmailButton.node.on(Button.EventType.CLICK, this.onResendEmailClicked, this);
        }
    
        onResendEmailClicked() {
            XsollaAuth.resendAccountConfirmationEmail(this.usernameEditBox.string, 'xsollatest', null, () => {
                console.log('A verification link has been successfully sent to your email');
            }, err => {
                console.log(err);
            });
        }
    }
    

    ユーザーログインを実装する

    このチュートリアルでは、以下のロジックの実装について説明します:

    ページのインターフェースを作成する

    ログインページのシーンを作成し、そこに以下の要素を追加します:

    • ユーザー名フィールド
    • パスワードフィールド
    • ログイン状態を保存するトグル
    • ログインボタン

    ページ構造の例:

    ログインスクリプトコンポーネントを作成する

    1. LoginComponentを作成し、次のプロパティを追加します:
      • usernameEditBox
      • passwordEditBox
      • remeberMeToggle
      • loginButton — 任意。コードを使用してコールバック関数をボタンにバインドするときに使用されます

    1. スクリプトの例に示すように、LoginButtonをクリックしたときに呼び出されるメソッドをLoginComponentクラスに追加し、クリックイベントを処理するロジックを追加します。
    2. LoginComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、シーン要素をLoginComponentのプロパティにバインドします:

    1. 以下のいずれかの方法でコールバックをログインボタンにバインドします:
      • 下の図に示すように、Inspectorパネルを使用します。
      • 以下のコードブロックをページスクリプトに挿入する。

    Inspectorパネルを使用してコールバックをバインドします:

    コード経由でコールバックをバインドします:

    Copy
    Full screen
    Small screen

    start() {
         this.loginButton.node.on(Button.EventType.CLICK, this.onLoginClicked, this);
      }
    

    お知らせ

    スクリプトの例では、onCompleteonErrorメソッドは標準のconsole.logメソッドを呼び出します。他のアクションを追加することができます。

    エラーが発生した場合、エラーコードと説明がerrorパラメータで渡されます。

    クラススクリプト(LoginComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Button, Component, EditBox, Toggle } from 'cc';
    import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('LoginComponent')
    export class LoginComponent extends Component {
    
        @property(EditBox)
        usernameEditBox: EditBox;
    
        @property(EditBox)
        passwordEditBox: EditBox;
    
        @property(Toggle)
        remeberMeToggle: Toggle;
    
        @property(Button)
        loginButton: Button;
    
        start() {
            this.loginButton.node.on(Button.EventType.CLICK, this.onLoginClicked, this);
        }
    
        onLoginClicked() {
            XsollaAuth.authByUsernameAndPassword(this.usernameEditBox.string, this.passwordEditBox.string, this.remeberMeToggle.isChecked, token => {
                console.log('Successful login. Token - ${token.access_token}');
            }, err => {
                console.log(err);
            });
        }
    }
    

    パスワードリセットを実装する

    このチュートリアルでは、以下のロジックの実装について説明します:

    ページのインターフェースを作成する

    パスワードのリセットページのシーンを作成し、以下を追加します:

    • ユーザー名フィールド
    • パスワードリセットボタン

    ページ構造の例:

    パスワードリセットスクリプトコンポーネントを作成する

    1. ResetPasswordComponentを作成し、次のプロパティを追加します:
      • usernameEditBox
      • resetPasswordButton — 任意。コードを使用してコールバック関数をボタンにバインドするときに使用されます

    1. スクリプトの例に示すように、ResetPasswordをクリックしたときに呼び出されるメソッドをResetPasswordComponentクラスに追加し、クリックイベントを処理するロジックを追加します。
    2. ResetPasswordComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、シーン要素をResetPasswordComponentのプロパティにバインドします:

    1. 以下のいずれかの方法でコールバックをパスワードリセットボタンにバインドします:
      • 下の図に示すように、Inspectorパネルを使用します。
      • 以下のコードブロックをページスクリプトに挿入する。

    Inspectorパネルを使用してコールバックをバインドします:

    コード経由でコールバックをバインドします:

    Copy
    Full screen
    Small screen

    start() {
            this.resetPasswordButton.node.on(Button.EventType.CLICK, this.onResetPasswordClicked, this);
        }
    

    お知らせ

    スクリプトの例では、onCompleteonErrorメソッドは標準のconsole.logメソッドを呼び出します。他のアクションを追加することができます。

    エラーが発生した場合、エラーコードと説明がerrorパラメータで渡されます。

    クラススクリプト(ResetPasswordComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Button, Component, EditBox } from 'cc';
    import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('ResetPasswordComponent')
    export class ResetPasswordComponent extends Component {
    
        @property(EditBox)
        usernameEditBox: EditBox;
    
        @property(Button)
        resetPasswordButton: Button;
    
        start() {
            this.resetPasswordButton.node.on(Button.EventType.CLICK, this.onResetPasswordClicked, this);
        }
    
        onResetPasswordClicked() {
            XsollaAuth.resetPassword(this.usernameEditBox.string, null, () => {
                console.log('Follow the instructions we sent to your email');
            }, err => {
                console.log(err);
            });
        }
    }
    

    ソーシャルログイン

    お知らせ
    Cocos Creator用のSDKはAndroidとiOSのビルドでのみソーシャルログインをサポートしています。

    このガイドでは、SDKメソッドを使用して、ユーザーのサインアップとソーシャルネットワークアカウントによるログインを実装する方法を紹介します。

    ユーザー名/ユーザーのメールアドレスとパスワードによるユーザー認証とは異なり、ユーザーのサインアップのために別のロジックを実装する必要はありません。ユーザーの初回ログインがソーシャルネットワーク経由の場合、新しいアカウントが自動的に作成されます。

    別の認証方法としてアプリケーションにソーシャルログインを実装している場合、以下の条件を満たすと、ソーシャルネットワークアカウントは既存のユーザーアカウントに自動的にリンクします。

    • ユーザー名/メールアドレスとパスワードでサインアップしたユーザーが、ソーシャルネットワークアカウントを介してアプリケーションにログインしました。
    • ソーシャルネットワークでは、メールアドレスを返します。
    • ソーシャルネットワークでのユーザーのメールアドレスは、アプリケーションで登録に使用したメールアドレスと同じです。

    このチュートリアルでは、以下のロジックの実装について説明します:

    この例では、Facebookアカウントによるユーザーログインを設定しています。すべてのソーシャルネットワークを同じ方法で設定できます。

    この例では、SDKメソッドの基本的な概要を提供します。アプリケーションは通常、より複雑なインターフェースとロジックを必要とします。

    ページのインターフェースを作成する

    ソーシャルログインページのシーンを作成し、それにソーシャルログインボタンを追加します。

    ページ構造の例:

    ソーシャルログインスクリプトコンポーネントを作成する

    1. SocialLoginComponentを作成します。コードを使用してコールバック関数をソーシャルログインボタンにバインドするには、socialLoginButtonプロパティを追加します。
    2. スクリプトの例に示すように、SocialLoginをクリックしたときに呼び出されるメソッドをSocialLoginComponentクラスに追加し、クリックイベントを処理するロジックを追加します。
    3. startライフサイクル関数を追加します。関数内では、スクリプト例に示すように、次のグローバルシーンイベントをバインドします:

      • socialAuthSuccess
      • socialAuthError
      • socialAuthCanceled

    1. SocialLoginComponentをシーン上のノードに追加しますSDK初期化で追加したXsollaSettingsManagerコンポーネントを使用して、新しいノードを追加するか、既存のノードを使用することができます。
    2. 図に示すように、SocialLoginボタンをSocialLoginComponentsocialLoginButtonプロパティにバインドします。

    1. 以下のいずれかの方法で、ソーシャルログインボタンにコールバックをバインドします:
      • 下の図に示すように、Inspectorパネルを使用します。
      • 以下のコードブロックをページスクリプトに挿入する。

    Inspectorパネルを使用してコールバックをバインドします:

    コード経由でコールバックをバインドします:

    Copy
    Full screen
    Small screen

    start() {
            this.socialLoginButton.node.on(Button.EventType.CLICK, this.onSocialLoginClicked, this);
    }
    

    お知らせ

    スクリプトの例では、onCompleteonErrorメソッドは標準のconsole.logメソッドを呼び出します。エラーが発生した場合、エラーコードと説明がerrorパラメータで渡されます。

    登録メールの再送リクエストのページを開いたり、登録が成功した場合にログインページを開くなど、他のアクションを追加することができます。

    クラススクリプト(SocialLoginComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Button, Component, director } from 'cc';
    import { NativeUtil } from 'db://xsolla-commerce-sdk/scripts/common/NativeUtil';
    import { Events } from 'db://xsolla-commerce-sdk/scripts/core/Events';
    import { Token } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('SocialLoginComponent')
    export class SocialLoginComponent extends Component {
    
        @property(Button)
        socialLoginButton: Button;
    
        start() {
            this.socialLoginButton.node.on(Button.EventType.CLICK, this.onSocialLoginClicked, this);
    
            director.getScene().on(Events.SOCIAL_AUTH_SUCCESS, this.handleSuccessfulSocialAuth, this );
            director.getScene().on(Events.SOCIAL_AUTH_ERROR, this.handleErrorSocialAuth, this );
            director.getScene().on(Events.SOCIAL_AUTH_CANCELED, this.handleCancelSocialAuth, this );
        }
    
        onSocialLoginClicked() {
            NativeUtil.authSocial('facebook');
        }
    
        handleSuccessfulSocialAuth(token:Token) {
            console.log(`Successful social authentication. Token - ${token.access_token}`);
        }
    
        handleCancelSocialAuth() {
            console.log('Social auth was canceled');
        }
    
        handleErrorSocialAuth(error:string) {
            console.log(error);
        }
    }
    

    アイテムカタログの表示

    このチュートリアルでは、SDKメソッドを使って、インゲームストアに以下のアイテムを表示する方法を紹介します:

    • 仮想アイテム
    • バンドル
    • 仮想通貨のパッケージ

    始める前に、アドミンページの項目を設定します:

    1. バーチャルアイテムとバーチャルアイテムのグループを設定します
    2. 仮想通貨のパッケージを設定します
    3. バンドルを設定します

    このチュートリアルでは、以下のロジックの実装について説明します:

    お知らせ

    カタログ内のすべてのアイテムの例は次のとおり:

    • 名称
    • 説明
    • 価格
    • 画像

    また、アイテムに関する他の情報がインゲームストアに保存されている場合は、その情報を表示することもできます。

    仮想アイテムの表示を実装する

    アイテムウィジェットを作成する

    1. プレハブを作成します。これを行うには、フォルダーのコンテキストメニューからCreate > Node Prefabを選択します。
    2. 作成したプレハブを開きます。
    3. 以下の画像に示すように、UITransformコンポーネントをプレハブのルートに追加し、コンテンツサイズを設定します。

    1. 以下のUI要素をプレハブ子オブジェクトとして追加し、視覚化を構成します:
      • ウィジェットの背景画像
      • アイテム名
      • アイテム説明
      • アイテム価格
      • アイテムイメージ

    ウィジェット構造の例:

    アイテムウィジェットスクリプトを作成する

    1. StoreItemComponentを作成し、以下のプロパティを追加します:
      • iconSprite
      • itemNameLabel
      • itemDescriptionLabel
      • priceLabel

    1. スクリプトの例に示すように、initメソッドと初期化ロジックをStoreItemComponentクラスに追加します。
    2. StoreItemComponentコンポーネントをプレハブのルートノードにアタッチします
    3. 図に示すように、プレハブ要素をStoreItemComponentのプロパティにバインドします:

    ウィジェットスクリプト(StoreItemComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
    import { StoreItem } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('StoreItemComponent')
    export class StoreItemComponent extends Component {
    
        @property(Sprite)
        iconSprite: Sprite;
    
        @property(Label)
        itemNameLabel: Label;
    
        @property(Label)
        itemDescriptionLabel: Label;
    
        @property(Label)
        priceLabel: Label;
    
        private _data: StoreItem;
    
        init(data: StoreItem) {
    
            this._data = data;
    
            this.itemNameLabel.string = data.name;
            this.itemDescriptionLabel.string = data.description;
    
            if (data.virtual_prices.length > 0) {
                this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
            } else {
                this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
            }
    
            assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                if(err == null) {
                const spriteFrame = new SpriteFrame();
                const texture = new Texture2D();
                texture.image = imageAsset;
                spriteFrame.texture = texture;
                this.iconSprite.spriteFrame = spriteFrame;
                } else {
                    console.log(`Can’t load image with URL ${data.image_url}`);
                }
            });
        }
    }
    

    ページのインターフェースを作成する

    アイテムカタログページのシーンを作成し、それにScrollView要素を追加します。

    ページ構造の例:

    ScrollViewを作成したStoreItemプレハブと一致させるには、そのサイズを設定します:

    1. ScrollViewノードと内部のviewノードのContentSizeパラメータの値を変更します。
    2. Layoutコンポーネントをcontentノードにバインドして設定します。この例では、次の設定が選択されています:
      • Type == vertical
      • ResizeMode == Container

    アイテムカタログスクリプトコンポーネントを作成する

    1. ItemsCatalogComponentを作成し、以下のプロパティを追加します:
      • itemsScrollView
      • storeItemPrefab

    1. スクリプトの例に示すように、startライフサイクル関数と初期化ロジックをItemsCatalogComponentクラスに追加します。
    2. ItemsCatalogComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、プレハブ要素をItemsCatalogComponentのプロパティにバインドします:

    クラススクリプト(ItemsCatalogComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
    import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
    import { StoreItemComponent } from './StoreItemComponent';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('ItemsCatalogComponent')
    export class ItemsCatalogComponent extends Component {
    
        @property(ScrollView)
        itemsScrollView: ScrollView;
    
        @property(Prefab)
        storeItemPrefab: Prefab;
    
        start() {
            XsollaCatalog.getCatalog(null, null, [], itemsData => {
                for (let i = 0; i < itemsData.items.length; ++i) {
                    let storeItem = instantiate(this.storeItemPrefab);
                    this.itemsScrollView.content.addChild(storeItem);
                    storeItem.getComponent(StoreItemComponent).init(itemsData.items[i]);
                }
            });
        }
    }
    

    スクリプトの動作結果の例:

    バンドルの表示の実装

    バンドルウィジェットを作成する

    1. プレハブを作成します。これを行うには、フォルダーのコンテキストメニューからCreate > Node Prefabを選択します。
    2. 作成したプレハブを開きます。
    3. 以下の画像に示すように、UITransformコンポーネントをプレハブのルートに追加し、コンテンツサイズを設定します。

    1. 以下のUI要素をプレハブ子オブジェクトとして追加し、視覚化を構成します:
      • ウィジェットの背景画像
      • バンドル名
      • バンドルの説明
      • バンドル価格
      • バンドルイメージ
      • バンドルコンテンツの説明(アイテムおよびその数量)

    ウィジェット構造の例:

    バンドルウィジェットスクリプトを作成する

    1. BundleItemComponentを作成し、以下のプロパティを追加します:
      • iconSprite
      • bundleNameLabel
      • bundleDescriptionLabel
      • priceLabel
      • contentDescriptionlabel

    1. スクリプトの例に示すように、initメソッドと初期化ロジックをBundleItemComponentクラスに追加します。
    2. BundleItemComponentをプレハブのルートノードにアタッチします
    3. 図に示すように、プレハブ要素をBundleItemComponentのプロパティにバインドします:

    ウィジェットスクリプト(BundleItemComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
    import { StoreBundle } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('BundleItemComponent')
    export class BundleItemComponent extends Component {
    
        @property(Sprite)
        iconSprite: Sprite;
    
        @property(Label)
        bundleNameLabel: Label;
    
        @property(Label)
        bundleDescriptionLabel: Label;
    
        @property(Label)
        priceLabel: Label;
    
        @property(Label)
        contentDescriptionLabel: Label;
    
        init(data: StoreBundle) {
    
            this.bundleNameLabel.string = data.name;
            this.bundleDescriptionLabel.string = data.description;
    
            if (data.virtual_prices.length > 0) {
                this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
            } else {
                this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
            }
    
            assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                if(err == null) {
                const spriteFrame = new SpriteFrame();
                const texture = new Texture2D();
                texture.image = imageAsset;
                spriteFrame.texture = texture;
                this.iconSprite.spriteFrame = spriteFrame;
                } else {
                    console.log(`Can’t load image with URL ${data.image_url}`);
                }
            });
    
            this.contentDescriptionLabel.string = 'This bundle includes '+ data.content.length + ' items: ';
            var bandles = data.content.map(bundle => bundle.name).join(', ');
            this.contentDescriptionLabel.string += bandles;
        }
    }
    

    ページのインターフェースを作成する

    バンドルカタログページのシーンを作成し、それにScrollView要素を追加します。

    ページ構造の例:

    ScrollViewを作成したBundleItemプレハブと一致させるには、そのサイズを設定します:

    1. ScrollViewノードと内部のviewノードのContentSizeパラメータの値を変更します。
    2. Layoutコンポーネントをcontentノードにバインドして設定します。この例では、次の設定が選択されています:
      • Type == vertical
      • ResizeMode == Container

    バンドルカタログスクリプトコンポーネントを作成する

    1. BundlesCatalogComponentを作成し、以下のプロパティを追加します:
      • itemsScrollView
      • bundleItemPrefab

    1. スクリプトの例に示すように、startライフサイクル関数と初期化ロジックをBundlesCatalogComponentクラスに追加します。
    2. BundlesCatalogComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、プレハブ要素をBundlesCatalogComponentのプロパティにバインドします:

    クラススクリプト(BundlesCatalogComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
    import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
    import { BundleItemComponent } from './BundleItemComponent';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('BundlesCatalogComponent')
    export class BundlesCatalogComponent extends Component {
    
        @property(ScrollView)
        itemsScrollView: ScrollView;
    
        @property(Prefab)
        bundleItemPrefab: Prefab;
    
        start() {
            XsollaCatalog.getBundleList(null, null, [], itemsData => {
            for (let i = 0; i < itemsData.items.length; ++i) {
                    let bundleItem = instantiate(this.bundleItemPrefab);
                    this.itemsScrollView.content.addChild(bundleItem);
                    bundleItem.getComponent(BundleItemComponent).init(itemsData.items[i]);
                }
            });
        }
    }
    

    スクリプトの動作結果の例:

    仮想通貨パッケージカタログの表示を実装する

    仮想通貨パッケージのウィジェットを作成する

    1. プレハブを作成します。これを行うには、フォルダーのコンテキストメニューからCreate > Node Prefabを選択します。
    2. 作成したプレハブを開きます。
    3. 以下の画像に示すように、UITransformコンポーネントをプレハブのルートに追加し、コンテンツサイズを設定します。

    1. 以下のUI要素をプレハブ子オブジェクトとして追加し、視覚化を構成します:
      • ウィジェットの背景画像
      • 通貨名
      • 通貨説明
      • 通貨価格
      • 通貨イメージ

    ウィジェット構造の例:

    仮想通貨パッケージ用ウィジェットスクリプトを作成する

    1. CurrencyPackageItemComponentを作成し、以下のプロパティを追加します:
      • iconSprite
      • currencyNameLabel
      • currencyDescriptionLabel
      • priceLabel

    1. スクリプトの例に示すように、initメソッドと初期化ロジックをCurrencyPackageItemComponentクラスに追加します。
    2. CurrencyPackageItemComponentコンポーネントをプレハブのルートノードにアタッチします
    3. 図に示すように、プレハブ要素をCurrencyPackageItemComponentのプロパティにバインドします:

    ウィジェットスクリプト(CurrencyPackageItemComponent)の例:

    Copy
    Full screen
    Small screen

    import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
    import { VirtualCurrencyPackage } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
    const { ccclass, property } = _decorator;
    
    
    @ccclass('CurrencyPackageItemComponent')
    export class CurrencyPackageItemComponent extends Component {
    
        @property(Sprite)
        iconSprite: Sprite;
    
        @property(Label)
        currencyNameLabel: Label;
    
        @property(Label)
        currencyDescriptionLabel: Label;
    
        @property(Label)
        priceLabel: Label;
    
        init(data: VirtualCurrencyPackage) {
    
            this.currencyNameLabel.string = data.name;
            this.currencyDescriptionLabel.string = data.description;
    
            if (data.virtual_prices.length > 0) {
                this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
            } else {
                this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
            }
    
            assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                if(err == null) {
                const spriteFrame = new SpriteFrame();
                const texture = new Texture2D();
                texture.image = imageAsset;
                spriteFrame.texture = texture;
                this.iconSprite.spriteFrame = spriteFrame;
                } else {
                    console.log(`Can’t load image with URL ${data.image_url}`);
                }
            });
        }
    }
    

    ページのインターフェースを作成する

    仮想通貨パッケージカタログページのシーンを作成し、それにScrollView要素を追加します。

    ページ構造の例:

    ScrollViewを作成したCurrencyPackageItemプレハブと一致させるには、そのサイズを設定します:

    1. ScrollViewノードと内部のviewノードのContentSizeパラメータの値を変更します。
    2. Layoutコンポーネントをcontentノードにバインドして設定します。この例では、次の設定が選択されています:
      • Type == vertical
      • ResizeMode == Container

    通貨パッケージカタログスクリプトコンポーネントを作成する

    1. CurrencyPackagesCatalogComponentを作成し、以下のプロパティを追加します:
      • itemsScrollView
      • currencyPackageItemPrefab

    1. スクリプトの例に示すように、startライフサイクル関数と初期化ロジックをCurrencyPackagesCatalogComponentクラスに追加します。
    2. CurrencyPackagesCatalogComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
    3. 図に示すように、プレハブ要素をCurrencyPackagesCatalogComponentのプロパティにバインドします:

    クラススクリプト(CurrencyPackagesCatalogComponent)の例:

    Copy
    Full screen
    Small screen

      import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
      import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
      import { CurrencyPackageItemComponent } from './CurrencyPackageItemComponent';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('CurrencyPackagesCatalogComponent')
      export class CurrencyPackagesCatalogComponent extends Component {
      
          @property(ScrollView)
          itemsScrollView: ScrollView;
      
          @property(Prefab)
          currencyPackageItemPrefab: Prefab;
      
          start() {
              XsollaCatalog.getVirtualCurrencyPackages(null, null, [], itemsData => {
              for (let i = 0; i < itemsData.items.length; ++i) {
                      let currencyPackageItem = instantiate(this.currencyPackageItemPrefab);
                      this.itemsScrollView.content.addChild(currencyPackageItem);
                      currencyPackageItem.getComponent(CurrencyPackageItemComponent).init(itemsData.items[i]);
                  }
              });
          }
      }
      

      スクリプトの動作結果の例:

      仮想アイテムを実際通貨で販売する

      ここでは、SDKメソッドを使用して、仮想アイテムを使用した実際通貨のアイテム販売を実装する方法について説明します。

      始める前に、カタログに仮想アイテムの表示を実装します。以下の例では、仮想アイテムの購入を実装する方法を説明します。他のアイテムタイプの設定も同様です。

      このチュートリアルでは、以下のロジックの実装について説明します:

      注意

      ログインするスクリプトの例では、デモアカウントの資格情報を使用します(ユーザー名:xsolla、パスワード:xsolla)。このアカウントはデモプロジェクトでのみ使用できます。

      スクリプトサンプルには、カタログのアイテムをページごとに表示する(ページネーション)実装は含まれていません。getCatalog SDKメソッドのoffsetおよびlimitパラメータを使用してページネーションを実装します。1 ページのアイテムの最大数は50です。カタログに50を超えるアイテムがある場合は、ページネーションが必要です。

      アイテムウィジェットを完成する

      アイテムウィジェットに直接販売ボタンを追加し、その視覚化を構成します。

      お知らせ
      この例では、変更されたクラスはRC_StoreItemComponentに変更されています。

      ウィジェット構造の例:

      アイテムウィジェットスクリプトを完成する

      1. コードを使用してコールバック関数を直接販売ボタンにバインドするには、buyButtonプロパティをRC_StoreItemComponentに追加します。
      2. メソッドをBuyButtonをクリックしたときに呼び出されるRC_StoreItemComponentクラスを追加し、スクリプトの例に示すように、クリックイベントを処理するロジックを追加します。
      3. 以下のいずれかの方法でコールバックを直接販売ボタンにバインドします:

        • 下の図に示すように、Inspectorパネルを使用する。
        • 以下のコードブロックをページスクリプトに挿入する。

      Inspectorパネルを使用してコールバックをバインドします:

      コード経由でコールバックをバインドします:

      Copy
      Full screen
      Small screen

      start() {
          this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
        }
      

      ウィジェットスクリプト(RC_StoreItemComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, assetManager, Button, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
      import { StoreItem, XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
      import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
      import { OrderTracker } from 'db://xsolla-commerce-sdk/scripts/common/OrderTracker';
      import { BrowserUtil } from 'db://xsolla-commerce-sdk/scripts/common/BrowserUtil';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('RC_StoreItemComponent')
      export class RC_StoreItemComponent extends Component {
      
          @property(Sprite)
          iconSprite: Sprite;
      
          @property(Label)
          itemNameLabel: Label;
      
          @property(Label)
          itemDescriptionLabel: Label;
      
          @property(Label)
          priceLabel: Label;
      
          @property(Button)
          buyButton: Button;
      
          private _data: StoreItem;
      
          start() {
              this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
          }
      
          init(data: StoreItem) {
      
              this._data = data;
      
              this.itemNameLabel.string = data.name;
              this.itemDescriptionLabel.string = data.description;
      
              if (data.virtual_prices.length > 0) {
                  this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
              } else {
                  this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
              }
      
              assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                  if(err == null) {
                  const spriteFrame = new SpriteFrame();
                  const texture = new Texture2D();
                  texture.image = imageAsset;
                  spriteFrame.texture = texture;
                  this.iconSprite.spriteFrame = spriteFrame;
                  } else {
                      console.log(`Can’t load image with URL ${data.image_url}`);
                  }
              });
          }
      
          onBuyClicked() {
              XsollaCatalog.fetchPaymentToken(TokenStorage.getToken().access_token, this._data.sku, 1, undefined, undefined, undefined, undefined, undefined, result => {
                  OrderTracker.checkPendingOrder(result.token, result.orderId, () => {
                      console.log('success purchase!');
                  }, error => {
                      console.log(`Order checking failed - Status code: ${error.status}, Error code: ${error.code}, Error message: ${error.description}`);
                  });
                  BrowserUtil.openPurchaseUI(result.token);
              }, error => {
                  console.log(error.description);
              });
          }
      }
      

      アイテムカタログスクリプトコンポーネントを完了する

      お知らせ
      スクリプト例では、変更されたクラスはRC_ItemsCatalogComponentに変更されています。

      スクリプトの例に示すように、有効な認可トークンを取得するためのロジックをRC_ItemsCatalogComponentクラスのstartメソッドに追加します。

      クラススクリプト(RC_ItemsCatalogComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
      import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
      import { RC_StoreItemComponent } from './RC_StoreItemComponent';
      import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
      import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
      const { ccclass, property } = _decorator;
      
      
      
      
      @ccclass('RC_ItemsCatalogComponent')
      export class RC_ItemsCatalogComponent extends Component {
      
          @property(ScrollView)
          itemsScrollView: ScrollView;
      
      
          @property(Prefab)
          storeItemPrefab: Prefab;
      
      
          start() {
              XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
                  TokenStorage.saveToken(token, false);
                  XsollaCatalog.getCatalog(null, null, [], itemsData => {
                      for (let i = 0; i < itemsData.items.length; ++i) {
                              let storeItem = instantiate(this.storeItemPrefab);
                              this.itemsScrollView.content.addChild(storeItem);
                              storeItem.getComponent(RC_StoreItemComponent).init(itemsData.items[i]);
                          }
                      });
              });
          }
      }
      

      スクリプトの動作結果の例:

      仮想アイテムを仮想通貨で販売する

      ここでは、SDKメソッドを使用して、仮想アイテムを使用した仮想通貨のアイテム販売を実装する方法について説明します。

      始める前に、カタログに仮想アイテムを表示する機能を実装します。以下の例では、仮想アイテムの購入を実装する方法を説明します。他のアイテムタイプの設定も同様です。

      このチュートリアルでは、以下のロジックの実装について説明します:

      注意

      ログインするスクリプトの例では、デモアカウントの資格情報を使用します(ユーザー名:xsolla、パスワード:xsolla)。このアカウントはデモプロジェクトでのみ使用できます。

      スクリプトサンプルには、カタログのアイテムをページごとに表示する(ページネーション)実装は含まれていません。getCatalog SDKメソッドのoffsetおよびlimitパラメータを使用してページネーションを実装します。1ページのアイテムの最大数は50です。カタログに50を超えるアイテムがある場合は、ページネーションが必要です。

      アイテムウィジェットを完成する

      アイテムウィジェットに直接販売ボタンを追加し、その視覚化を構成します。

      お知らせ
      この例では、変更されたクラスはVC_StoreItemComponentに変更されています。

      ウィジェット構造の例:

      アイテムウィジェットスクリプトを完成する

      1. コードを使用してコールバック関数を直接販売ボタンにバインドするには、buyButtonプロパティをVC_StoreItemComponentに追加します。
      2. メソッドをBuyButtonをクリックしたときに呼び出されるVC_StoreItemComponentクラスを追加し、スクリプトの例に示すように、クリックイベントを処理するロジックを追加します。
      3. 以下のいずれかの方法でコールバックを直接販売ボタンにバインドします:

        • 下の図に示すように、Inspectorパネルを使用する。
        • 以下のコードブロックをページスクリプトに挿入する。

      Inspectorパネルを使用してコールバックをバインドします:

      コード経由でコールバックをバインドします:

      Copy
      Full screen
      Small screen

      start() {
          this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
        }
      

      ウィジェットスクリプト(VC_StoreItemComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, assetManager, Button, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
      import { StoreItem, XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
      import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
      import { OrderTracker } from 'db://xsolla-commerce-sdk/scripts/common/OrderTracker';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('VC_StoreItemComponent')
      export class VC_StoreItemComponent extends Component {
      
          @property(Sprite)
          iconSprite: Sprite;
      
          @property(Label)
          itemNameLabel: Label;
      
          @property(Label)
          itemDescriptionLabel: Label;
      
          @property(Label)
          priceLabel: Label;
      
          @property(Button)
          buyButton: Button;
      
          private _data: StoreItem;
      
          start() {
              this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
          }
      
          init(data: StoreItem) {
      
              this._data = data;
      
              this.itemNameLabel.string = data.name;
              this.itemDescriptionLabel.string = data.description;
      
              if (data.virtual_prices.length > 0) {
                  this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
              } else {
                  this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
              }
      
              assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                  if(err == null) {
                  const spriteFrame = new SpriteFrame();
                  const texture = new Texture2D();
                  texture.image = imageAsset;
                  spriteFrame.texture = texture;
                  this.iconSprite.spriteFrame = spriteFrame;
                  } else {
                      console.log(`Can’t load image with URL ${data.image_url}`);
                  }
              });
          }
      
          onBuyClicked() {
              XsollaCatalog.purchaseItemForVirtualCurrency(TokenStorage.getToken().access_token, this._data.sku, this._data.virtual_prices[0].sku, orderId => {
                  OrderTracker.checkPendingOrder(TokenStorage.getToken().access_token, orderId, () => {
                      console.log('success purchase!');
                  }, error => {
                      console.log(`Order checking failed - Status code: ${error.status}, Error code: ${error.code}, Error message: ${error.description}`);
                  });
              }, error => {
                  console.log(error.description);
              });
          }
      }
      

      アイテムカタログスクリプトコンポーネントを完了する

      お知らせ
      スクリプト例では、変更されたクラスはVC_ItemsCatalogComponentに変更されています。

      スクリプトの例に示すように、有効な認可トークンを取得するためのロジックをVC_ItemsCatalogComponentクラスのstartメソッドに追加します。

      クラススクリプト(VC_ItemsCatalogComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
      import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
      import { VC_StoreItemComponent } from './VC_StoreItemComponent';
      import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
      import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('VC_ItemsCatalogComponent')
      export class VC_ItemsCatalogComponent extends Component {
      
          @property(ScrollView)
          itemsScrollView: ScrollView;
      
          @property(Prefab)
          storeItemPrefab: Prefab;
      
          start() {
              XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
                  TokenStorage.saveToken(token, false);
                  XsollaCatalog.getCatalog(null, null, [], itemsData => {
                      for (let i = 0; i < itemsData.items.length; ++i) {
                              let storeItem = instantiate(this.storeItemPrefab);
                              this.itemsScrollView.content.addChild(storeItem);
                              storeItem.getComponent(VC_StoreItemComponent).init(itemsData.items[i]);
                          }
                      });
              });
          }
      }
      

      スクリプトの動作結果の例:

      仮想通貨残高の表示

      このチュートリアルでは、SDKメソッドを使って、アプリ内で仮想通貨の残高を表示する方法を紹介します。

      残高表示用のウィジェットを作成する

      1. プレハブを作成します。これを行うには、フォルダーのコンテキストメニューからCreate > Node Prefabを選択します。
      2. 作成したプレハブを開きます。
      3. 以下の画像に示すように、UITransformコンポーネントをプレハブのルートに追加し、コンテンツサイズを設定します。

      1. 以下のUI要素をプレハブ子オブジェクトとして追加し、視覚化を構成します:
        • ウィジェットの背景画像
        • 通貨名
        • 通貨数量
        • 通貨イメージ

      ウィジェット構造の例:

      残高表示のためのウィジェットスクリプトを作成する

      1. CurrencyBalanceItemComponentを作成し、以下のプロパティを追加します:
        • iconSprite
        • currencyNameLabel
        • quantityLabel

      1. スクリプトの例に示すように、initメソッドと初期化ロジックをCurrencyBalanceItemComponentクラスに追加します。
      2. CurrencyBalanceItemComponentコンポーネントをプレハブのルートノードにアタッチします
      3. 図に示すように、プレハブ要素をCurrencyBalanceItemComponentのプロパティにバインドします:

      ウィジェットスクリプト(CurrencyBalanceItemComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
      import { VirtualCurrencyBalance } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('CurrencyBalanceItemComponent')
      export class CurrencyBalanceItemComponent extends Component {
      
          @property(Sprite)
          iconSprite: Sprite;
      
          @property(Label)
          currencyNameLabel: Label;
      
          @property(Label)
          quantityLabel: Label;
      
          init(data: VirtualCurrencyBalance) {
      
              this.currencyNameLabel.string = data.name;
              this.quantityLabel.string = data.amount.toString();
      
              assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                  if(err == null) {
                  const spriteFrame = new SpriteFrame();
                  const texture = new Texture2D();
                  texture.image = imageAsset;
                  spriteFrame.texture = texture;
                  this.iconSprite.spriteFrame = spriteFrame;
                  } else {
                      console.log(`Can’t load image with URL ${data.image_url}`);
                  }
              });
          }
      }
      

      ページのインターフェースを作成する

      仮想通貨残高ページのシーンを作成し、それにScrollView要素を追加します。

      ページ構造の例:

      ScrollViewを作成したCurrencyBalanceItemプレハブと一致させるには、そのサイズを設定します:

      1. ScrollViewノードと内部のviewノードのContentSizeパラメータの値を変更します。
      2. Layoutコンポーネントをcontentノードにバインドして設定します。この例では、次の設定が選択されています:
        • Type == vertical
        • ResizeMode == Container

      通貨残高スクリプトコンポーネントを作成する

      1. CurrencyBalanceComponentを作成し、以下のプロパティを追加します:
        • itemsScrollView
        • currencyBalanceItemPrefab

      1. スクリプトの例に示すように、startライフサイクル関数と初期化ロジックをCurrencyBalanceComponentクラスに追加します。
      2. CurrencyBalanceComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
      3. 図に示すように、プレハブ要素をCurrencyBalanceItemComponentのプロパティにバインドします:

      お知らせ
      ログインするスクリプトの例では、デモアカウントの資格情報を使用します(ユーザー名:xsolla、パスワード:xsolla)。このアカウントはデモプロジェクトでのみ使用できます。

      クラススクリプト(CurrencyBalanceComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
      import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
      import { XsollaInventory } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
      import { CurrencyBalanceItemComponent } from './CurrencyBalanceItemComponent';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('CurrencyBalanceComponent')
      export class CurrencyBalanceComponent extends Component {
      
          @property(ScrollView)
          itemsList: ScrollView;
      
          @property(Prefab)
          currencyBalanceItemPrefab: Prefab;
      
          start() {
              XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
                  XsollaInventory.getVirtualCurrencyBalance(token.access_token, null, itemsData => {
                      for (let i = 0; i < itemsData.items.length; ++i) {
                              let currencyBalanceItem = instantiate(this.currencyBalanceItemPrefab);
                              this.itemsList.content.addChild(currencyBalanceItem);
                                   currencyBalanceItem.getComponent(CurrencyBalanceItemComponent).init(itemsData.items[i]);
                          }
                      });
              });
      
          }
      }
      

      スクリプトの動作結果の例:

      インベントリでアイテムの表示

      このチュートリアルでは、SDKのメソッドを使ってユーザーのインベントリにアイテムを表示する方法を紹介します。

      アイテムウィジェットを作成する

      1. プレハブを作成します。これを行うには、フォルダーのコンテキストメニューからCreate > Node Prefabを選択します。
      2. 作成したプレハブを開きます。
      3. 以下の画像に示すように、UITransformコンポーネントをプレハブのルートに追加し、コンテンツサイズを設定します。

      1. 以下のUI要素をプレハブ子オブジェクトとして追加し、視覚化を構成します:
        • ウィジェットの背景画像
        • インベントリアイテム名
        • インベントリアイテム説明
        • アイテム数量
        • アイテムイメージ

      ウィジェット構造の例:

      アイテムウィジェットスクリプトを作成する

      1. InventoryItemComponentを作成し、以下のプロパティを追加します:
        • iconSprite
        • itemNameLabel
        • itemDescriptionLabel
        • quantityLabel

      1. スクリプトの例に示すように、initメソッドと初期化ロジックをInventoryItemComponentクラスに追加します。
      2. InventoryItemComponentコンポーネントをプレハブのルートノードにアタッチします
      3. 図に示すように、プレハブ要素をInventoryItemComponentのプロパティにバインドします:

      ウィジェットスクリプト(InventoryItemComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
      import { InventoryItem } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
      const { ccclass, property } = _decorator;
      
      @ccclass('InventoryItemComponent')
      export class InventoryItemComponent extends Component {
      
          @property(Sprite)
          iconSprite: Sprite;
      
          @property(Label)
          itemNameLabel: Label;
      
          @property(Label)
          itemDescriptionLabel: Label;
      
          @property(Label)
          quantityLabel: Label;
      
          init(data: InventoryItem) {
      
              this.itemNameLabel.string = data.name;
              this.itemDescriptionLabel.string = data.description;
              this.quantityLabel.string = data.quantity.toString();
      
              assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
                  if(err == null) {
                  const spriteFrame = new SpriteFrame();
                  const texture = new Texture2D();
                  texture.image = imageAsset;
                  spriteFrame.texture = texture;
                  this.iconSprite.spriteFrame = spriteFrame;
                  } else {
                      console.log(`Can’t load image with URL ${data.image_url}`);
                  }
              });
          }
      }
      

      ページのインターフェースを作成する

      インベントリページのシーンを作成し、それに ScrollView要素を追加します。

      ページ構造の例:

      ScrollViewを作成したInventoryItemプレハブと一致させるには、そのサイズを設定します:

      1. ScrollViewノードと内部のviewノードのContentSizeパラメータの値を変更します。
      2. Layoutコンポーネントをcontentノードにバインドして設定します。この例では、次の設定が選択されています:
        • Type == vertical
        • ResizeMode == Container

      インベントリーページスクリプトコンポーネントを作成する

      1. InventoryItemsComponentを作成し、以下のプロパティを追加します:
        • itemsScrollView
        • inventoryItemPrefab

      1. スクリプトの例に示すように、startライフサイクル関数と初期化ロジックをInventoryItemsComponentクラスに追加します。
      2. InventoryItemsComponentをシーン上のノードに追加します。新しいノードを追加することも、SDK初期化中に追加したXsollaSettingsManagerコンポーネントで既存のノードを使用することもできます。
      3. 図に示すように、プレハブ要素をInventoryItemsComponentのプロパティにバインドします:

      お知らせ
      ログインするスクリプトの例では、デモアカウントの資格情報を使用します(ユーザー名:xsolla、パスワード:xsolla)。このアカウントはデモプロジェクトでのみ使用できます。

      クラススクリプト(InventoryItemsComponent)の例:

      Copy
      Full screen
      Small screen

      import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
      import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
      import { XsollaInventory } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
      import { InventoryItemComponent } from './InventoryItemComponent';
      const { ccclass, property } = _decorator;
      
      
      @ccclass('InventoryItemsComponent')
      export class InventoryItemsComponent extends Component {
      
          @property(ScrollView)
          itemsScrollView: ScrollView;
      
          @property(Prefab)
          inventoryItemPrefab: Prefab;
      
          start() {
              XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
                  XsollaInventory.getInventory(token.access_token, null, itemsData => {
                      for (let i = 0; i < itemsData.items.length; ++i) {
                              let inventoryItem = instantiate(this.inventoryItemPrefab);
                              this.itemsScrollView.content.addChild(inventoryItem);
                              inventoryItem.getComponent(InventoryItemComponent).init(itemsData.items[i]);
                          }
                      });
              });
      
          }
      }
      

      スクリプトの動作結果の例:

      進捗状況
      ご意見ありがとうございました!
      最終更新日: 2023年9月14日

      誤字脱字などのテキストエラーを見つけましたか? テキストを選択し、Ctrl+Enterを押します。

      内容
      問題を報告する
      当社は常にコンテンツを見直しています。お客様のご意見は改善に役立ちます。
      フォローアップ用のメールをご提供してください
      ご意見ありがとうございました!