question

Kim Strasser avatar image
Kim Strasser asked

CloudScript: POST method for RegisterPlayFabUser and AddUsernamePassword?

I want to call RegisterPlayFabUser and AddUsernamePassword from my CloudScript to create/update the player's username, password and e-mail address. I have tried it with a POST method but it's not working. I get an exception.

Is it possible to create/update the player's username, password and e-mail address in CloudScript?

Raw event JSON
{
    "EventName": "player_executed_cloudscript",
    "Source": "CloudScript",
    "FunctionName": "VerifyUsernamePassword",
    "CloudScriptExecutionResult": {
        "FunctionName": "VerifyUsernamePassword",
        "Revision": 66,
        "FunctionResult": null,
        "FunctionResultTooLarge": null,
        "Logs": [],
        "LogsTooLarge": null,
        "ExecutionTimeSeconds": 0.022820399999999998,
        "ProcessorTimeSeconds": 0,
        "MemoryConsumedBytes": 43752,
        "APIRequestsIssued": 1,
        "HttpRequestsIssued": 0,
        "Error": {
            "Error": "JavascriptException",
            "Message": "JavascriptException",
            "StackTrace": "ReferenceError: PlayFabID is not defined\n    at handlers.VerifyUsernamePassword (BFD0A-main.js:80:96)"
        }
    },
    "EventNamespace": "com.playfab",
    "EntityType": "player",
    "TitleId": "BFD0A",
    "EntityId": "1066CF1F71C39EC1",
    "EventId": "dcdbaeaacd364dc09847745399550ccf",
    "SourceType": "BackEnd",
    "Timestamp": "2019-10-10T13:24:10.6302392Z",
    "History": null,
    "CustomTags": null,
    "Reserved": null,
    "PlayFabEnvironment": {
        "Vertical": "master",
        "Cloud": "main",
        "Application": "logicserver",
        "Commit": "a881f0a"
    }
}

CloudScript POST method for AddUsernamePassword:

handlers.VerifyUsernamePassword = function (args, context)
{
     var resultprofile = server.GetPlayerProfile(
       {
           PlayFabID: currentPlayerId
       });
       
     var result = AddUsernamePasswordFromCloudScript(args.Email, args.Username, args.Password, PlayFabID);
      return result;
}


function AddUsernamePasswordFromCloudScript(email, username, password, playFabId)
{
    var contentBodyTemp = {
        "PlayFabId": playFabId,
        "Email": email,
        "Username": username,
        "Password": password
    };
    
    let url = "https://BFD0A.playfabapi.com/Admin/AddUsernamePassword";
    let method = "POST";
    let contentBody = `{"PlayFabId": "${playFabId}", "Email": "${email}", "Username": "${username}", "Password": "${password}"}`;
    let contentType = "application/json";
    let headers = { "X-SecretKey": "..." };
    let responseString = http.request(url, method, contentBody, contentType, headers);
    let responseJSONObj = JSON.parse(responseString);
    return (responseJSONObj);
}

Client Code:

private async Task UpdateUsernamePasswordCloud()
{
    var result = await PlayFabClientAPI.ExecuteCloudScriptAsync(new ExecuteCloudScriptRequest()
    {
        FunctionName = "VerifyUsernamePassword",
        FunctionParameter = new { Email = "player1test@gmail.com", Username = "Player1username", Password = "Player1password!!!" },
        GeneratePlayStreamEvent = true
    });

    if (result.Error != null)
        Console.WriteLine(result.Error.Error.ToString());
    else
    {
        if (result.Result.Logs.Count() > 0)
            Console.WriteLine(result.Result.Logs[0].Message);
    }
}

UPDATE:

Here is my new client and CloudScript code. The CloudScript code for AddUsernamePassword works.

But I get an exception in my client code if I want to call RegisterPlayFabUser in CloudScript.

Why is the player not logged in if I call RegisterPlayFabUser in CloudScript?

PlayFab.PlayFabException has been thrown
Must be logged in to call this method

Client code:

private async Task UpdateUsernamePasswordCloud()
{
    var result = await PlayFabClientAPI.ExecuteCloudScriptAsync(new ExecuteCloudScriptRequest()
    {
        FunctionName = "AddUsernamePassword",
        FunctionParameter = new { SessionTicket = playersessionTicket, Email = "player11test@gmail.com", Username = "Player11username", Password = "Player11password!!!" },
        GeneratePlayStreamEvent = true
    });

    if (result.Error != null)
        Console.WriteLine(result.Error.Error.ToString());
    else
    {
        if (result.Result.Logs.Count() > 0)
            Console.WriteLine(result.Result.Logs[0].Message);
    }
}

private async Task RegisterPlayFabUserCloud()
{
    var result = await PlayFabClientAPI.ExecuteCloudScriptAsync(new ExecuteCloudScriptRequest()
    {
        FunctionName = "RegisterPlayFabUser",
        FunctionParameter = new { SessionTicket = playersessionTicket, Email = "player1test@gmail.com", Username = "Player1username", Password = "Player1password!!!" },
        GeneratePlayStreamEvent = true
    });

    if (result.Error != null)
        Console.WriteLine(result.Error.Error.ToString());
    else
    {
        if (result.Result.Logs.Count() > 0)
            Console.WriteLine(result.Result.Logs[0].Message);
    }
}

CloudScript:

handlers.AddUsernamePassword = function (args, context)
{
     var resultprofile = server.GetPlayerProfile(
       {
           PlayFabID: currentPlayerId
       });
       
     var result = AddUsernamePasswordFromCloudScript(args.SessionTicket, args.Email, args.Username, args.Password, currentPlayerId);

      return result;
}

function AddUsernamePasswordFromCloudScript(sessionticket, email, username, password, playFabId)
{
    var contentBodyTemp = {
        "PlayFabId": playFabId,
        "Email": email,
        "Username": username,
        "Password": password
    };
    
    let url = "https://BFD0A.playfabapi.com/Client/AddUsernamePassword";
    let method = "POST";
    let contentBody = `{"PlayFabId": "${playFabId}", "Email": "${email}", "Username": "${username}", "Password": "${password}"}`;
    let contentType = "application/json";
    let headers = { "X-Authentication": sessionticket };
    let responseString = http.request(url, method, contentBody, contentType, headers);
    let responseJSONObj = JSON.parse(responseString);
    return (responseJSONObj);
}

handlers.RegisterPlayFabUser = function (args, context)
{
     var resultprofile = server.GetPlayerProfile(
       {
           PlayFabID: currentPlayerId
       });
       
     var result = RegisterPlayFabUserFromCloudScript(args.SessionTicket, args.Email, args.Username, args.Password, currentPlayerId);

      return result;
}

function RegisterPlayFabUserFromCloudScript(sessionticket, email, username, password, playFabId)
{
    var contentBodyTemp = {
        "TitleId": BFD0A,
        "RequireBothUsernameAndEmail": true,
        "PlayFabId": playFabId,
        "Email": email,
        "Username": username,
        "Password": password
    };
    
    let url = "https://BFD0A.playfabapi.com/Client/RegisterPlayFabUser";
    let method = "POST";
    let contentBody = `{"TitleId": "${BFD0A}", "RequireBothUsernameAndEmail": "${true}", "PlayFabId": "${playFabId}", "Email": "${email}", "Username": "${username}", "Password": "${password}"}`;
    let contentType = "application/json";
    let headers = { "X-Authentication": sessionticket };
    let responseString = http.request(url, method, contentBody, contentType, headers);
    let responseJSONObj = JSON.parse(responseString);
    return (responseJSONObj);
}
CloudScript
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Sarah Zhang avatar image
Sarah Zhang answered

It’s possible. The first thing is RegisterPlayFabUser and AddUsernamePassword these two functions only have Client API, so we can’t use "https://[TitleId].playfabapi.com/Admin/[functionName]" to access them. You can search for the functions in the API references to confirm which access levels they can use before you try to call them.

Hence, if you want to send AddUsernamePassword request with the POST method on the CloudScript. You should add X-Authentication field in the request, this field’s value is required and it should be the player’s session ticket value.

You can refer to the following POST request. It is suitable for all nonanonymous calls of Classic Client API. In addition, “X-SecretKey: <developer_secret_key>” is suitable for Classic Server and Admin API.

POST https://{
                {TitleID}}.playfabapi.com/Client/AddUsernamePassword 
Content-Type: application/json 
X-Authentication: <user_session_ticket_value>
{ 
"Username": "theuser", 
"Email": "me@here.com", 
"Password": "thepassword"
}

RegisterPlayFabUser doesn't need it and “X-SecretKey: <developer_secret_key>”. The session ticket will be returned in its response. Like the following sample.

POST https://{
                {TitleID}}.playfabapi.com/Client/RegisterPlayFabUser
    Content-Type: application/json
{
  "Username": "theuser",
  "Email": "me@here.com",
  "Password": "thepassword",
  "TitleId": "1"
}
        
----------------------------------------------------------------------------------------

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
  "code": 200,
  "status": "OK",
  "data": {
    "PlayFabId": "50DF92E291CCD4C3",
    "SessionTicket": "50DF92E291CCD4C3---A54F-8D3909FF54DEE10-B7817722BC94E536.A6DCCFE1C9709ABB",
    "Username": "username"
  }
}

The player’s session ticket can also be got in the result callback function of LoginwithXXXX request. Like the following code. (Unity Client)

  public void loginOnClick()
    {
        var request = new LoginWithCustomIDRequest { CustomId = Idtext.text, CreateAccount = true };
        PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);
    }


    private void OnLoginSuccess(LoginResult result)
    {
        string playersessionTicket = result.SessionTicket;
    }

Then you can add this field in the client’s args or get it on CloudScript. Also add it in the AddUsernamePasswordFromCloudScript function.

//Client
FunctionParameter=new{
SessionTicket= playerSessionTicket, Email="player1test@gmail.com",Username="Player1username",Password="Player1password!!!"},

--------------------------------------------------------------------------------------
//CouldScript
...
var result = AddUsernamePasswordFromCloudScript(args.sessionTicket, args.Email, args.Username, args.Password, PlayFabID);
...
function AddUsernamePasswordFromCloudScript(sessionTicket, email, username, password, playFabId) 
{ 
... 
let headers = { "X-Authentication": sessionTicket };
...
}
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Kim Strasser avatar image Kim Strasser commented ·

I added my new client and CloudScript code in the question above. The CloudScript code for AddUsernamePassword works. But I get an exception in my client code if I want to call RegisterPlayFabUser in CloudScript.

Why is the player not logged in if I call RegisterPlayFabUser in CloudScript? Is something wrong with my CloudScript?

PlayFab.PlayFabException has been thrown
Must be logged in to call this method
0 Likes 0 ·
Sarah Zhang avatar image Sarah Zhang Kim Strasser commented ·

We will check this question in your new thread.

0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.