Use In-Game Store with BaaS authorization
You can use In-Game Store with the BaaS authorization system to sell in-game items. In this case, the interaction is as follows:
- The user logs in to your application via the BaaS authorization system.
- The BaaS service requests the user JSON Web Token (JWT) from Xsolla servers by passing the user ID.
- The Xsolla servers return the user JWT to the BaaS service.
- The BaaS service passes the user JWT to the application.
- The application uses the user JWT to interact with Xsolla servers using the API.
Note
If you haven’t implemented the logic for user authorization, you can integrate Xsolla Login and set up storage of user data in PlayFab or Firebase. This allows you to use the Login API to authenticate users and receive JWTs to interact with the APIs of other Xsolla products.
- In Publisher Account, connect the standard Login project to your project.
- Set up a server OAuth 2.0 client.
- Add ready-made functions to your project by following the instructions for Firebase and PlayFab.
Set up server OAuth 2.0 client
- Open your project in Publisher Account and go to the Login section.
- Click Configure in the pane of a Login project.
- Go to the Security block and select the OAuth 2.0 section.
- Click Add OAuth 2.0.
- Specify OAuth 2.0 redirect URIs.
- Check the Server (server-to-server connection) box.
- Click Connect.
- Copy and save the client ID and secret key.
Add Cloud Function to Firebase project
- Initialize your Firebase project.
- Import and configure the receive function for the user JWT, where:
<ProjectID>
is the project ID, and can be found in your Publisher Account next to the name of your project.<LoginID>
is the Login ID that can be obtained by opening Publisher Account, go to the Login > Dashboard > your Login project section, and click Copy ID next to the name of the Login project.<OAuthClientID>
is the client ID received when you set up the server OAuth 2.0 client.<OAuthSecretKey>
is the secret key that is received when you set up the server OAuth 2.0 client.
Function code for receiving the user JWT:
Copy
- javascript
const projectId = "<ProjectID>";
const loginProjectId = "<LoginID>";
const serverOauthClientId = <OAuthClientID>;
const serverOauthClientSecret = "<OAuthSecretKey>";
exports.getXsollaLoginToken = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
"failed-precondition",
"The function must be called while authenticated."
);
}
const postData =
"grant_type=client_credentials" +
`&client_secret=${serverOauthClientSecret}`+
`&client_id=${serverOauthClientId}`;
const options = {
hostname: "login.xsolla.com",
port: 443,
path: "/api/oauth2/token",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": postData.length,
},
};
return new Promise( (resolve, reject) => {
const req = https.request(options, (res) => {
if (res.statusCode !== 200) {
reject(
new functions.https.HttpsError(
"internal",
"Server 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 server token response"
)
);
}
getClientToken(context.auth.uid, body.access_token, resolve, reject);
});
});
req.on("error", (e) => {
reject(new functions.https.HttpsError(
"internal",
"Internal error while server token flow"
));
});
req.write(postData);
req.end();
});
});
// eslint-disable-next-line require-jsdoc
function getClientToken(userId, serverToken, resolve, reject) {
const postData = JSON.stringify(
{
"server_custom_id": userId,
}
);
const path =
"/api/users/login/server_custom_id?" +
`projectId=${loginProjectId}&` +
`publisher_project_id=${projectId}`;
const options = {
hostname: "login.xsolla.com",
port: 443,
path: path,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": postData.length,
"X-Server-Authorization": serverToken,
},
};
const req = https.request(options, (res) => {
if (res.statusCode !== 200) {
reject(
new functions.https.HttpsError(
"internal",
"Client 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 client token response"
)
);
}
resolve({
"token": body.token,
});
});
});
req.on("error", (e) => {
reject(new functions.https.HttpsError(
"internal",
"Internal error while client token flow"
));
});
req.write(postData);
req.end();
}
- Deploy the function to a production environment as per this example.
- Add client-side logic to call a function from your application. Specify
getXsollaLoginToken
as the function name. Passing parameters is not required. - In the application, implement methods for working with the API yourself or use Xsolla SDKs.
Add Cloud Script to PlayFab project
- Create a JS file with the function code for receiving the user JWT, where:
<ProjectID>
is the project ID, and can be found in your Publisher Account next to the name of your project.<LoginID>
is the Login ID that can be obtained by opening Publisher Account, go to the Login > Dashboard > your Login project section, and click Copy ID next to the name of the Login project.<OAuthClientID>
is the client ID received when you set up the server OAuth 2.0 client.<OAuthSecretKey>
is the secret key that is received when you set up the server OAuth 2.0 client.
Note
If you are already using Cloud Scripts in your project, add the function for receiving the user JWT to the end of the code.
Copy
- javascript
handlers.GetXsollaLoginToken = function (args) {
// TODO replace with production credentials
const projectId = <ProjectID>;
const loginProjectId = "<LoginID>";
const serverOauthClientId = <OAuthClientID>;
const serverOauthClientSecret = "<OAuthSecretKey>";
const getServerTokenBody =
"grant_type=client_credentials" +
`&client_secret=${serverOauthClientSecret}` +
`&client_id=${serverOauthClientId}`;
const serverTokenResponse = JSON.parse(
http.request(
"https://login.xsolla.com/api/oauth2/token",
"post",
getServerTokenBody,
"application/x-www-form-urlencoded",
{})
);
let serverToken = ""
if ('access_token' in serverTokenResponse) {
serverToken = serverTokenResponse.access_token;
} else {
return {
"error_message": "Server token not received"
}
}
const getUserTokenHeaders = {
"X-Server-Authorization": serverToken
}
const getUserTokenBody = JSON.stringify(
{
"server_custom_id": currentPlayerId,
}
);
const getUserTokenPath =
"/api/users/login/server_custom_id?" +
`projectId=${loginProjectId}&` +
`publisher_project_id=${projectId}`;
const userTokenResponse = JSON.parse(
http.request(
"https://login.xsolla.com" + getUserTokenPath,
"post",
getUserTokenBody,
"application/json",
getUserTokenHeaders)
);
if ('token' in userTokenResponse) {
return {
"token": userTokenResponse.token
}
} else {
return {
"error_message": "User token not received"
}
}
}
- Go to PlayFab project settings.
- Upload the Cloud Script file.
- Run the Cloud Script in a production environment.
- Add client-side logic to call a function from your application. Specify
GetXsollaLoginToken
as the function name. Passing parameters is not required.
Example of calling the receive function for the user JWT:
Copy
kotlin
- kotlin
- C#
- C++
val tokenRequest = PlayFabClientModels.ExecuteCloudScriptRequest()
tokenRequest.FunctionName = "GetXsollaLoginToken"
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 = "GetXsollaLoginToken"
};
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("GGetXsollaLoginToken");
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.
- In the application, implement methods for working with the API yourself or use Xsolla SDKs.
Was this article helpful?
Thank you for your feedback!
We’ll review your message and use it to help us improve your experience.Useful links
Last updated: October 3, 2024Found a typo or other text error? Select the text and press Ctrl+Enter.