question

Kim Strasser avatar image
Kim Strasser asked

CloudScript: How can I find out if the country code is valid?

In my game the player can choose his country in a list. After the player has chosen his country, I call my CloudScript UpdateCountryReadOnlyData to create the country data in the player's profile.

Is it possible to find out in my CloudScript code if the country code "PlayerDataCountryCode" is a valid country code?

For example:

If PlayerDataCountryCode = US, then create the country data in the player's profile because "US" is a valid country code.

case US:
    NewCountry = "United States";

If PlayerDataCountryCode = XX, then don't create the country data in the player's profile because "XX" is not a valid country code of this list: https://api.playfab.com/playstream/events/datatype/CountryCode

How can I find out if "PlayerDataCountryCode" is in this list?

Client code:

	private async Task UpdateCountry()
        {
            var result = await PlayFabClientAPI.ExecuteCloudScriptAsync(new ExecuteCloudScriptRequest()
            {
                FunctionName = "UpdateCountryReadOnlyData",
                FunctionParameter = new { PlayerDataCountryCode = "US" },
                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);
                    Console.WriteLine("Country is " + result.Result.FunctionResult);
                }
                else
                    Console.WriteLine("Country is " + result.Result.FunctionResult);

            }
        }

CloudScript:

handlers.UpdateCountryReadOnlyData = function (args, context)
{
   var resultdata = server.GetUserReadOnlyData({PlayFabId: currentPlayerId, Keys: "Country"}); // first search for the current country info
   var CurrentCountry = ""; 
   var NewCountryCodeIsvalid = false;
   var countrycode = args.PlayerDataCountry;
   var NewCountry = ChooseaCountry(args.PlayerDataCountry);
   
   if(resultdata.Data.hasOwnProperty("Country"))
   { // if country info already exists in readonly data 
          if ((resultdata.Data.Country.Value != null) && (resultdata.Data.Country.Value != ""))
          { // make sure the value is not null or ""
                CurrentCountry = resultdata.Data.Country.Value;
                log.info("Already has country info, current country is:" + CurrentCountry.toString()); // if country value already exists, notify the client that Country info already been set
          }
          else
          { // if country value is null or "", set the Country value
               server.UpdateUserReadOnlyData({
               PlayFabId: currentPlayerId,
               Data: {
               "Country": NewCountry
               }
               });
          
          if (NewCountryCodeIsvalid == false)
              log.info(NewCountry.toString() + " " + "is not a valid country name. Please enter a valid country name.");
          }
   }
   else
   {// if country  hasn't been set yet, set it for the user
       server.UpdateUserReadOnlyData({
           PlayFabId: currentPlayerId,
           Data: {
               "Country": NewCountry
           }
        });
        
        if (NewCountryCodeIsvalid == false)
           log.info(NewCountry.toString() + " " + "is not a valid country name. Please enter a valid country name.");
   }
   
   return server.GetUserReadOnlyData({PlayFabID: currentPlayerId, Keys: "Country"}).Data.Country.Value; // return the current country info to the clients.
}


function ChooseaCountry(countrycode)
{
    switch (countrycode)
    {
    case "US":
        NewCountryCodeIsvalid = true;
        return("United States");
        break;
    case "DE":
        NewCountryCodeIsvalid = true;
        return("Germany");
        break;
    case "FR":
        NewCountryCodeIsvalid = true;
        return("France");
        break;
    default: // if the countrycode is not valid, for example if the countrycode is "XX"
        NewCountryCodeIsvalid = false;
        return("");
        break;
    }
}
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

PlayFab doesn’t provide such country code validation API, so we need to implement this feature manually. If you check C# PlayFab SDK, you will find that CountryCode is provided as the enum in the SDK. So, in the client, we can use Enum.IsDefined function to verify the CountryCode directly like the following code.

  public bool VerifyCountrycode(string myCountryCode)
    { 
        return Enum.IsDefined(typeof(PlayFab.ClientModels.CountryCode), myCountryCode);
    }

Generally, we can’t use SDK on CloudScript. So you can refer to the client’s SDK and define CountryCode as a collection by yourself, then implement the corresponding feature using Js. If you want to use SDK on CloudScript actually we provide a repository SdkTestingCloudScript. It provides some Typescript samples which can convert to Js, the CountryCode is defined in the .d.ts file. You can try to use it if you want.

6 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 have tried it with switch-case in CloudScript because I don't know how Typescript works. But it's not working, even if I use a valid country code like "US". I always get this message: " is not a valid country name. Please enter a valid country name.

Do you know what I'm doing wrong?

Raw event JSON
{
    "EventName": "player_executed_cloudscript",
    "Source": "CloudScript",
    "FunctionName": "UpdateCountryReadOnlyData",
    "CloudScriptExecutionResult": {
        "FunctionName": "UpdateCountryReadOnlyData",
        "Revision": 45,
        "FunctionResult": null,
        "FunctionResultTooLarge": null,
        "Logs": [
            {
                "Level": "Info",
                "Message": " is not a valid country name. Please enter a valid country name.",
                "Data": null
            }
        ],
        "LogsTooLarge": null,
        "ExecutionTimeSeconds": 0.0597298,
        "ProcessorTimeSeconds": 0,
        "MemoryConsumedBytes": 43608,
        "APIRequestsIssued": 3,
        "HttpRequestsIssued": 0,
        "Error": null
    },
    "EventNamespace": "com.playfab",
    "EntityType": "player",
    "TitleId": "BFD0A",
...
0 Likes 0 ·
Seth Du avatar image Seth Du ♦ Kim Strasser commented ·

In the 6th line of your cloud script code:

var countrycode = args.PlayerDataCountry;

please try to replace it with:

var countrycode = args.PlayerDataCountryCode;

because what you defined in the request of API call is PlayerDataCountryCode.

FunctionParameter=new{PlayerDataCountryCode="US"}
0 Likes 0 ·
Kim Strasser avatar image Kim Strasser Seth Du ♦ commented ·

Thanx. I had overlooked this typo. But I still have a problem with my CloudScript.

var NewCountryCodeIsvalid is always false, it never changes to true, even if the countrycode is "US". I want that NewCountryCodeIsvalid changes to true in the switch-case block if the countrycode is "US", "DE" or "FR". On the other hand, if the countrycode is different than "US", "DE" or "FR", than NewCountryCodeIsvalid should be false.

I use "NewCountryCodeIsvalid" because I need to know if the countrycode exists or not exists.

What am I doing wrong in my CloudScript?

var NewCountryCodeIsvalid = false;
var NewCountry = ChooseaCountry(args.PlayerDataCountryCode);

function ChooseaCountry(countrycode)
{
    switch (countrycode)
    {
    case "US":
        NewCountryCodeIsvalid = true;
        return("United States");
        break;
    case "DE":
        NewCountryCodeIsvalid = true;
        return("Germany");
        break;
    case "FR":
        NewCountryCodeIsvalid = true;
        return("France");
        break;
    default: // if the countrycode is not valid, for example if the countrycode is "XX"
        NewCountryCodeIsvalid = false;
        return("");
        break;
    }
}
0 Likes 0 ·
Show more comments
Show more comments

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.