Show Sidebar

WebRPCs

WebRPCs are a flexible way to integrate external services with Photon Cloud. For instance with a WebRPC, Photon clients can ask the server to fetch data from an external web service. In the "Memory Demo", GetGameList WebRPC is used to fetch a list of saved games for the player. You can fetch an inventory, profiles or anything else as easily.

Content

Web Service Basics

The WebRPC architecture is simple. Photon Servers play a Proxy or Relay role between client and web server. WebRPCs can also be seen as an extension of webhooks or even custom client-driven webhooks.

To use WebRPCs, you need to implement a HTTP based service and configure the BaseURL in the Webhooks section of your application accordingly. Photon Webhooks and WebRPCs share the same BaseURL.

Please take the following development tips into consideration:

  • You can use any language or framework or web server to implement the service for the WebRPCs.
  • We use webscript.io as test service in many cases, because it's easy to access, use and maintain. However, keep in mind that this service is more a sandbox and not built for heavy traffic.
  • In all cases, try to minimize the data you send to keep things lean and cheap for players.

Request

From client side, Photon WebRPC is a Photon operation that is allowed when connected to either Master or Game servers. It requires a URI path string (a.k.a WebRPC method name) and optionally a second argument which contains the data to be sent to the web service (a.k.a WebRPC parameters). Those two arguments can be passed to the LoadBalancingClient.OpWebRpc method.

UriPath is the relative path of the WebRPC which should match the remote procedure name. It is also possible to send parameters in the URL itself. In this case, the query string should be included in the procedure name, appended to the relative path.

When the request is received by Photon servers, the procedure's name will be concatenated to the BaseURL to form the absolute path of the WebRPC's URL before forwarding it to the web service at that same URL.

Since the HTTP request method used is POST, if there are any parameters sent by client, Photon will pass them over as JSON POST data along with default properties:

  • AppId: AppId of your application as set from the game client and found in the Dashboard.

  • AppVersion: version of your application as set from the game client.

  • Region: the region to which the game client is connected to.

  • UserId: ID of the actor making the WebRPC.

Any other property found is part of the parameters sent by the client. If the WebRpcParameters type used in client is Dictionary<string, object> then all the key/value pairs will be sent in the root object of the post data. Otherwise, if it is any other JSON valid type, it will be included as a value of a new property RpcParams.

Example 1

Your BaseURL is http://my.service.org and the client calls WebRPC("method?id=1", parameters). The parameters are a Dictionary<string, object> that has a {{"key1": 1}, {"key2": "yx"}, {"key3": true}} as content. In this case, Photon will call http://my.service.org/method?id=1 and additionally POST the JSON:

Example 2

Your BaseURL is http://my.service.org and the client calls WebRPC("method?id=1", parameters). The parameters are an array of objects: object[] { 0, "xy", false }. In this case, Photon will call http://my.service.org/method?id=1 and additionally POST the JSON:

Example 3

Your BaseURL is http://my.service.org and the client calls WebRPC("method?id=1", parameters). The parameters are is a primitive simple type. Let's say a string "test". In this case, Photon will call http://my.service.org/method?id=1 and additionally POST the JSON:

Sending Secure Data

WebRPC also offers an option to securely transmit the encrypted object AuthCookie to the web service when available. This can be done by setting the appropriate webflag (SendAuthCookie = 0x02) when calling the WebRPC operation method from client code.

The AuthCookie could be retrieved after a successful authentication against a custom authentication provider. For more information please visit the custom authentication documentation page.

Response

A web service for WebRPCs must respond with a JSON object to allow Photon to send the result back to the clients. The expected response has to include ResultCode, Data and optionally a Message.

The ResultCode should be 0 for OK and any other code for errors. You can make them up to help the client handle the error and adding a readable string message is always a best practice.

The Data can be empty but if you send anything, it must be a valid JSON object.

Like all Photon operations, the WebRPC's OperationResponse has a ReturnCode. If the operation was successful it will have ErrorCode.Ok (0) value. Otherwise it will indicate ErrorCode.ExternalHttpCallFailed (32744). In case of error you can always check the OperationResponse.DebugMessage for more information.

Most client SDKs include a helper class WebRpcResponse to parse the WebRPC result for you. WebRpcResponse will make the web service's returned result code, data and optional message available as properties by retrieving their respective values from the following keys in the operation response parameters:

  • ParameterCode.WebRpcReturnCode (207) contains the ResultCode value as returned by the web service.
  • ParameterCode.WebRpcReturnMessage (206) contains any eventual message returned by the web server.
  • ParameterCode.WebRpcParameters (208) contains the data returned by the web server. Its expected type depends on the type of data sent from web server but it can only be valid JSON.

URL Tags

In Webhooks and WebRPC URLs, you can optionally set one or more "dynamic variables". Those variables will be replaced with their respective values in our backend before sending out any requests.

URL tags come in handy if you want to handle user segments of your application differently, each. Photon supports the following URL tags:

  • {AppVersion} will pass the application version as set by the client.
  • {AppId} will pass the ID of your application.
  • {Region} will pass the token for the cloud region the triggering client is connected to, e.g. "eu".
  • {Cloud} will pass the name of the cloud the triggering client is connected to, e.g. "public" or "enigmaticenterprise".

Examples of URL Tags use cases

  1. https://{Region}.mydomain.com/{AppId}?version={AppVersion}&cloud={Cloud} to e.g. route each region to different hosts, version and cloud passed as query parameters.
  2. https://mydomain.com/{Cloud}/{Region}/{AppId}/{AppVersion} passes all tags as well structured URI.

Why Choose WebRPC

Sending HTTP requests can be done without Photon. You can write a HTTP client yourself or use one available from an SDK or a library. However Photon WebRPCs offer more than just that. Here are some of its advantages:

  • It may be better to keep all logic inside a single connected client and handle a single "lifecycle" and "state machine". Photon client is what you need in this case.
  • WebRPC operation takes care of the JSON serialization for you in both ways.
  • "BaseURL" and method names support URL Tags feature.
  • You can verify the identity of the client sending the WebRPC using AuthCookie or exchange more sensitive data server-to-server. Read more about how to make use of this feature here.

GetGameList

This part explains the particular example GetGameList which is not a built-in nor an out-of-box feature in any of the Photon products.
If you still want to use one of the available samples provided in our GitHub page, pay attention to the spelling of the remote procedure name. It does not include an 's': GetGamesList.
Otherwise, you are free to choose any name you want or even any WebRPC implementation that suits you.

GetGameList is a special WebRPC as it was first introduced in the "Memory Demo" to demonstrate Photon's WebRPC feature. It is also special because almost any game need to fetch a list of previously saved games.

Its basic idea is to send a request to the web service and expect a list of games which could be rejoined by the calling user and continue to play. This presumes that the application should be properly configured: the BaseUrl should point to your web service and in order to persist games data IsPersistent should be set to true and GameClose webhook should be activated. The latter is important as the games data that should be returned by the web service rely on the Photon's serialized room State.

On the other hand, the web service should have access to the saved game data and should be ready to receive and process HTTP POST requests sent to the WebRPC's path (here GetGameList).

Since Photon sends the UserId in all WebRPC requests data, there is no need to add any custom parameter. The request is sent without extra arguments.

The web service should return the list of saved games in Data as a JSON object. Each saved game's GameId will have a key. The respective value is also a JSON object composed of two properties:

  • ActorNr: The exact same original ActorNr of the actor calling the WebRPC that was assigned to him/her when he/she joined that room for the first time. This could be loaded easily in case it was intentionally and separately saved earlier or it could be retrieved from the respective room's saved State object by looping on the ActorList and comparing UserIds.

  • Properties: The key:value pairs of CustomRoomProperties visible to the lobby that can be retrieved from CustomProperties property contained in the respective room's saved State.

Although WebRPC calls are permitted to both Master and Game servers, it makes more sense to call GetGameList when not joined to a room, i.e. from Master server.

Passing data to Web Service

WebRPC offers three different ways of passing data from client to web service. The three different types can either be used separately or combined. For instance if you want to extend GetGameList and retrieve a filtered list of saved games based on a specific opponent, you can do this in three different ways:

  1. RESTful way:

    Relative URI: /GetGameList/{opponentId}

  2. POST data:

    Relative URI: /GetGameList

    Request data:

  3. Query string (a.k.a. GET parameters):

    Relative URI: /GetGameList?opponentId={opponentId}

Of course the web service should be updated also according to the method chosen.

Data Types Conversion

In this section, only the type of data exchanged between Photon server and the web service is explained. For more information about data types between clients and Photon servers please refer to serialization in Photon page.

Photon Server -> Web Service

C# / .Net (Photon supported types) JavaScript / JSON
byte number
short
int
long
double
bool bool
string string
byte array (length < short.MaxValue) string (Base64 encoded)
array ([] of supported type, length < short.MaxValue) array
Hashtable (of supported types, count < short.MaxValue, preferably Photon implementation) object
Dictionary (keys and values of supported types, count < short.MaxValue) object
null null

Sample request data (types are concatenated)

As sent from Photon Server:

As read by Web Service:

Web Service -> Photon Server

Here is a table that matches each JavaScript/JSON type to its equivalent one in C#/.Net :

JavaScript / JSON C# / .Net
object Dictionary<string, object>
array object[]
number (integral) long
number (floating) double
string string
boolean bool
null (not a type) null
undefined (when sent) null

Sample response data (types are concatenated)

As sent from Web Service:

As read from Photon Server:

 To Document Top