Use In-Game Store with BaaS authorization

You can use In-Game Store together with the BaaS authorization system to sell in-game items. In this case, the interaction will be as follows:

  1. The user logs in to your application via the BaaS authorization system.
  2. The BaaS service requests the Pay Station access token from Xsolla servers, passing the user ID.
  3. The Xsolla servers return the Pay Station access token to the BaaS service.
  4. The BaaS service passes the Pay Station access token to the application.
  5. The application uses the Pay Station access token to interact with the Xsolla servers using the API.

To get the Pay Station access token, add ready-made functions to your project by following the instructions for Firebase and PlayFab.

Add Cloud Function to Firebase project

  1. Initialize your Firebase project.
  2. Import and configure the receive function for the Pay Station access token, where:
    • <MerchantID>Merchant ID found in Publisher Account in the Project Settings > Webhooks section.
    • <ProjectID>Project ID found in Publisher Account in the Project Settings > Project ID section.
    • <ApiKey>API key found in Publisher Account in Company settings > API key section.

Function code for receiving the Pay Station access token:

Copy
Full screen
Small screen
const merchantId = "<MerchantID>";
const projectId = "<ProjectID>";
const apiKey = "<ApiKey>";

exports.getXsollaAccessToken = functions.https.onCall((data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError(
        "failed-precondition",
        "The function must be called while authenticated."
    );
  }

  const userId = context.auth.uid;
  const userEmail = context.auth.token.email || null;

  const authHeader = Buffer.from(`${merchantId}:${apiKey}`).toString("base64");

  const postData = JSON.stringify(
      {
        "user": {
          "id": {
            "value": userId,
          },
          "email": {
            "value": userEmail,
          },
        },
        "settings": {
          "project_id": Number(projectId),
        },
      }
  );

  const options = {
    hostname: "api.xsolla.com",
    port: 443,
    path: `/merchant/v2/merchants/${merchantId}/token`,
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Content-Length": postData.length,
      "Authorization": `Basic ${authHeader}`,
    },
  };

  return new Promise( (resolve, reject) => {
    const req = https.request(options, (res) => {
      if (res.statusCode != 200) {
        reject(
            new functions.https.HttpsError("internal", "Token not received")
        );
      }
      let body = [];
      res.on("data", (d) => {
        body.push(d);
      });
      res.on("end", () => {
        try {
          body = JSON.parse(Buffer.concat(body).toString());
        } catch (e) {
          reject(
              new functions.https.HttpsError("internal", "Malformed response")
          );
        }
        resolve({
          "token": body.token,
        });
      });
    });
    req.on("error", (e) => {
      reject(new functions.https.HttpsError("internal", "Internal error"));
    });

    req.write(postData);
    req.end();
  });
});

  1. Deploy the function to a production environment as per this example.
  2. Add client-side logic to call a function from your application. Specify getXsollaAccessToken as the function name. Passing the parameters is not required.
  3. In the application, implement methods for working with the API yourself or use the Xsolla SDKs.

Add Cloud Script to PlayFab project

  1. Create a JS file with the function code for receiving the Pay Station access token, where:
    • <MerchantID>Merchant ID found in Publisher Account in the Project Settings > Webhooks section.
    • <ProjectID>Project ID found in the Publisher Account in the Project Settings > Project ID section.
    • <your_authorization_basic_key> — the Merchant ID:API key pair encoded according to the Base64 standard. API key found in Publisher Account in Company settings > API key section.

Note
If you are already using Cloud Scripts in your project, add the function for receiving the Pay Station access token to the end of the code.

Function code for receiving the Pay Station access token:

Copy
Full screen
Small screen
handlers.GetXsollaAccessToken = function (args) {

    // TODO replace with production credentials
    const merchantId = <MerchantID>; // Merchant ID from the Publisher Account
    const projectId = <ProjectID>; // Project ID from the Publisher Account
    const authHeader = '<your_authorization_basic_key>' // Base64(merchant_id:api_key)

    const headers = {
        "Authorization": `Basic ${authHeader}`
    };

    const body = {
        user: {
            id: {
                value: currentPlayerId
            },
            playfab_id: {
                value: currentPlayerId
            }
        },
        settings: {
            project_id: projectId
        }
    };

    const url = `https://api.xsolla.com/merchant/v2/merchants/${merchantId}/token`;
    const httpMethod = "post";
    const content = JSON.stringify(body);
    const contentType = "application/json";

    const response = JSON.parse(http.request(url, httpMethod, content, contentType, headers));

    if ('token' in response) {
        return {
            "token" : response.token
        }
    } else {
        return {
            "error_message" : response.message
        }
    }
}

  1. Go to PlayFab project settings.
  2. Upload the Cloud Script file.
  3. Run the Cloud Script in a production environment.
  4. Add client-side logic to call a function from your application. Specify GetXsollaAccessToken as the function name. Passing the parameters is not required.

An example of calling the receive function for the Pay Station access token:

Copy
Full screen
Small screen
kotlin
  • kotlin
  • C#
  • C++
val tokenRequest = PlayFabClientModels.ExecuteCloudScriptRequest()
tokenRequest.FunctionName = "GetXsollaAccessToken"
val res = PlayFabClientAPI.ExecuteCloudScript(tokenRequest)
val result = res.Result.FunctionResult as Map<*, *>
val token = result["token"]
val errorMessage = result["error_message"]
var tokenRequest = new ExecuteCloudScriptRequest{
  FunctionName = "GetXsollaAccessToken"
};

PlayFabClientAPI.ExecuteCloudScript(
  tokenRequest,
  scriptResult =>
  {
     var functionResult = scriptResult.FunctionResult as Dictionary<string, string>;
     var token = functionResult["token"];
  },
  playfabError => { Debug.LogError($"GetXsollaAccessToken error: {playfabError.ErrorMessage}"); });
void UMyClass::GetXsollaToken()
{
    FClientExecuteCloudScriptRequest tokenRequest;
    tokenRequest.FunctionName = TEXT("GetXsollaAccessToken");

    UPlayFabClientAPI::FDelegateOnSuccessExecuteCloudScript onSuccess;
    onSuccess.BindUFunction(this, "OnTokenRecieved");

    UPlayFabClientAPI::FDelegateOnFailurePlayFabError onFailure;
    onSuccess.BindUFunction(this, "OnError");

    UPlayFabClientAPI::ExecuteCloudScript(tokenRequest, onSuccess, onFailure, nullptr);
}

void UMyClass::OnTokenRecieved(FClientExecuteCloudScriptResult result, UObject* customData)
{
    const FString& token = result.FunctionResult->GetStringField(TEXT("token"));

    // do something with a token
}

void UMyClass::OnError(FPlayFabError error, UObject* customData)
{
    // handle errors
}

Note
In this example, we use the PlayFab SDK methods to make a request to the Cloud Script. You can implement the request and response processing yourself without adding the PlayFab SDK to your project.

  1. In the application, implement methods for working with the API yourself or use Xsolla SDKs.

Was this article helpful?
Thank you!
Is there anything we can improve? Message
We’re sorry to hear that
Please explain why this article wasn’t helpful to you. Message
Thank you for your feedback!
We’ll review your message and use it to help us improve your experience.
Rate this page
Rate this page
Is there anything we can improve?

Don’t want to answer

Thank you for your feedback!

Useful links

Last updated: July 31, 2021

Found a typo or other text error? Select the text and press Ctrl+Enter.

Report a problem
We always review our content. Your feedback helps us improve it.
Provide an email so we can follow up
Thank you for your feedback!