Integration

Integration

 

 

Get Started

In this documentation, you can discover how to implement Games in your App or Website using Flarie Studio. 

The Game Url

Your Game Url is generated in Flarie Studio.

https://game.flarie.com/games/{gameName}/{gameUid}?{optionalParameters}

{gameName} 
The static Flarie game name. Automatically populated from Flarie Studio.

{gameUid} 
The unique identifier for your game. Automatically populated from Flarie Studio.

{optionalParameters} 
you can add player information to your game through the URL, e.g. if you distribute the game on your website or in your app you can automatically add a unique identifier that you have on your user to make it easier to match your game data with your existing user data in Flarie Studio.

To add player information to the URL, simply add the desired parameters as URL Parameters in the Userbase section in Game Settings and append them to your URL. You can also specify if the parameter should be the identifier, meaning scores will be grouped by that value. Identifier is required to use the URL Parameter type of UUID. 

Example: 
https://game.flarie.com/games/{gameName}/{gameUid}?uuid=xxxx-yyyy-zzzz

 

Making the Game View look perfect

To make sure the game looks good on all devices the games have a fixed ratio of 9:16. If you have a greater screen resolution on the device, the game view will always center itself both vertically and horizontally on the screen. If you are running your game in your app you can set your webview to have constraints to cover the whole screen or create a webview with the correct aspect ratio of 9:16 and then have your own custom background to frame the game. 

 

Add Game to Web

Website

Depending on your needs we have two examples on how you can integrate your game on your website.

  • Embed Code

  • Fullscreen iframe

 

[WEB] Embed Code

<script id="embed-script-v1" type="application/javascript" height="90vh" expander="true" src="https://play.flarie.com/embed.js" embed-url="{your-game-url}"> </script>

Optional attributes

Attribute

Description

top

Set an optional marginTop to the gameView.Example: top='50px'. Default is 0px.

height

Set an optional height to the gameView.
Example: height='90vh'. Default is 100%.

width

Set an optional width to the gameView.Example: width='50vw'. Default is 100%.

expander

Activate an expander button that will trigger fullscreen mode. Example: expander='true'. Default value is false.

expander-img-minimize

Override the default expander minimize image. Example: expander-img-minimize='your-image-url.png'

expander-img-fullscreen

Override the default expander fullscreen image.
Example: expander-img-fullscreen='your-image-url.png'

 

[WEB] Fullscreen iframe


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no minimal-ui'/>
    <meta name='apple-mobile-web-app-capable' content='yes'/>
    <meta name='screen-orientation' content='portrait'/>
    <meta http-equiv='ScreenOrientation' content='autoRotate:disabled'>
    <style>
      body, html{
        height: 100%;
        margin:0;
        padding:0;
        overflow:hidden;
      }
      #iframe-game {
        overflow:hidden;
        display:block;
        position: absolute;
        height: 100%;
        width: 100%;
        margin:0;
        padding:0;
        border:0;
      }
    </style>
  </head>
  <body>
    <iframe id="iframe-game" src="YOUR_GAME_URL"></iframe>
  </body>
</html>

 

Add Game to App

App

To run Flarie Studio games in your app you need to create a webview that supports custom interfaces and load your game url in the webview. WKWebView would be our recommended option for iOS. 

[recommendation] - in Flarie Studio you can enable Instruction Views. These Instruction View may include tutorial videos. set allowsInlineMediaPlayback in order to prevent the video going into full screen mode.

 

[App] iOS - Swift

import WebKit

class webGames: UIViewController, WKScriptMessageHandler, WKUIDelegate {

  var webView: WKWebView!
  var contentController = WKUserContentController()

  override func viewDidLoad() {
    // this will add support for the callback “gameOver”, meaning you will receive a notification every time the user ends a gameRound
    contentController.add(self, name: "gameOver")

    let config = WKWebViewConfiguration()
    config.allowsInlineMediaPlayback = true // recommended to prevent full screen video
    config.userContentController = contentController

    webView = WKWebView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height), configuration: config)
    self.view.addSubview(webView)

    // don’t forget to set the WKUIDelegate otherwise the target='_blank' won’t work
    webView.uiDelegate = self

    let gameUrl = Foundation.URL(string: "YOUR_GAME_URL")
    let gameUrlRequest = URLRequest(url: gameUrl!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
    webView.load(gameUrlRequest)
  }

  func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
      if (message.name == "gameOver") {
          print("data: \(message.body)")
          return
      }
  }

  // allow target _blank for external urls
  func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if let frame = navigationAction.targetFrame,
        frame.isMainFrame {
        return nil
    }

    if let url = navigationAction.request.url {
        // this will allow target _blank on urls
        UIApplication.shared.open(URL(string: "\(url)")!)
    } else {
        webView.load(navigationAction.request)
    }
    return nil
  }
}
 

[APP] Android - Java


public class Demo {
    WebView webView;
    
    private void setupWebView() {
        webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new WebAppInterface(context), "Android");
        webView.loadUrl("YOUR_GAME_URL");
    }

    private Handler handler = new Handler();
    
    public class WebAppInterface {
        @JavascriptInterface
        public void gameOver(final String message) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("", "Data: " + message);
                }
            });
        }
    }
}

 

Callbacks & Methods

We support callbacks and methods for app and iframe integrations. 
You can use these callbacks and methods to create more customization in your app, for example your own loading screen or a custom restart view for your game. You can also use them to save data passed back to you from the game to create custom experiences in your app, such as unlocking certain features of your apps using games. 

 

Callbacks

Callbacks contain an interface name that you may listen to. Once the data is being sent the body of the message will contain the json data passed to your interface. 

 

Iframe  Example

<script>
  window.addEventListener("message", function(event) {
        switch(event.data.type) {
            case "loading":
                console.log("Event: Loading received: " + event.data.value);
                break;
            case "gameStarted":
                console.log("Event: GameStarted received: " + event.data.value);
                break;
            case "gameOver":
                console.log("Event: GameOver received: " + event.data.value);
                break;
            case "gameClick":
                console.log("Event: gameClick received: " + event.data.value);
                break;
            default:
                break;
        }
  });
</script>

 

Callback: Loading

If you wish to build a custom loading screen for your game you can use our callback for Loading. 

When the progress value reaches 100 you are ready to hide your custom loading screen and present the game. 

Interface: loading Example: {"loading": {"progress":  _value}};

Parameter

Type

Description

_value

int

Progress of your loading, 0-100

 

Callback: Game Started 

When the user starts a game round the data will be passed to your app’s interface.

Interface: gameStartedExample: {"gameStarted": {"state":  true}};

Parameter

Type

Description

state

Bool

State is sent as true

 

Callback: Game Started 

When the user starts a game round the data will be passed to your app’s interface.

Interface: gameOverExample: {"game": {"time":  _gameTime, "score": _score}};

Parameter

Type

Description

_gameTime

int

Time spent of the game round (seconds)

_score

int

Score of the game round

 

Callback: Game Click 

When the user clicks on a CTA within a game this event will be called.

Interface: gameClick
Example: {"gameClick": {"state": true}};

Parameter

Type

Description

state

Bool

State is sent as true

 

Methods

Can be called from your app to trigger actions in the game.

 

Method: Start Game

If you wish to build your custom Start Game-button in your own restart view. 

Example:
iOS Swift: yourWebView.evaluateJavascript("startGame()");
Android Java: yourWebView.loadUrl("javascript:startGame()");

 

Method: Game Over

If you wish to manually end a game round for the user, e.g. when the user closes or leaves your app and you wish to retrieve the game data for that current round you can manually call the endGame method. 

Example:
iOS Swift:  yourWebView.evaluateJavascript("gameOver()");
Android Java: yourWebView.loadUrl("javascript:gameOver()");


Method: Turn Sound On

You can set if the sound should be on or off as default on the Settings page in Flarie Studio. If you want to create your own custom restart view with sound settings in your app you can use this method to turn the sound on. 

Example:
iOS Swift:  yourWebView.evaluateJavascript("turnSoundOn()");
Android Java:  yourWebView.loadUrl("javascript:turnSoundOn()");

Method: Turn Sound Off

You can set if the sound should be on or off as default on the Settings page in Flarie Studio. If you want to create your own custom restart view with sound settings in your app you can use this method to turn the sound off. 

Example:
iOS Swift: yourWebView.evaluateJavascript("turnSoundOff()");
Android Java: yourWebView.loadUrl("javascript:turnSoundOff()");

 

Method: Pause Controller

You can call this method to display the pauseController. With the pauseController the user can pause the game to see game instructions and also resume or end the game round. The pauseController will automatically hide again when the game ends. 

Example:
iOS Swift: yourWebView.evaluateJavascript("showPauseController()");Android Java: yourWebView.loadUrl("javascript:showPauseController()");

 

Webhook

Flarie Studio is equipped with a powerful Data Integration - Webhook feature that empowers you to seamlessly respond to events and design personalised processes. Whether it’s reward users in your own platform, tracking user activity and engagement, or consolidating your analytics - this feature streamlines the process. 

In order to get going with Data Integration you simply create a Webhook in your Flarie Studio account, provide a Webhook URL where Flarie will POST the data. Choose your events that you would like to monitor and determine the specific Games, Game Centers or Rewards where these events should trigger.

You may find payload examples for each Webhook Event in your Flarie Studio account.

 

Authentication (optional)

Enable Access Key and Secret Key in Flarie Studio to get authentication sent in the header of the webhook request.

Learn more about Access Key here

Learn more about Secret Key here

  • If Access Key is enabled, the Authorization header will be added to the request: 
    Authorization: Bearer {accessKey}

     

     

  • If Secret Key is enabled, the X-Signature header will be added to the request:
    X-Signature: SHA-256 HMAC signature generated using the Secret Key and the JSON payload
    The X-Signature header contains the SHA-256 HMAC (Hash-based Message Authentication Code)  signature generated by using the Secret Key to hash the JSON payload. This signature is used for verifying the integrity and authenticity of the webhook payload.

     

Below is an example of how you can verify the payload with the X-Signature

const crypto = require("node:crypto");

const payload = // your json payload in the request

const payloadString = JSON.stringify(payload);

const secretKey = "your-secret-key";

const calculatedSignature = crypto
  .createHmac("sha256", secretKey)
  .update(payloadString)
  .digest("hex");

const X_Signature = "X-Signature-in-the-header";

if (X_Signature === calculatedSignature) {
  console.log("Payload is authentic and unmodified")
} else {
  console.log("Payload is modified")
}

 

Game - Events

  • First Game Start
    Description:Event sent the first time the Player starts the Game.

    Payload: Event, User Base, Game

  • Form Submission - StartGame
    Description: Event sent time the form is submitted when the Player starts the Game. This event will be sent at the start of every Game Session.

    Payload: Event, User Base, Game

  • Game Start
    Description: Event sent every time the Player starts the Game.

    Payload: Event, User Base, Game

  • Challenge Completed
    Description: Event sent when the Player completes the challenge by reaching the set target in your Game, This event will only be sent once per Game Period.

    Payload: Event, User Base, Game, Game Score

  • Form Submission - Challenge Completed
    Description: Event sent when the Player submits the form after a Challenge has been completed. This event can be sent multiple times, since the Player can access the form and modify the details.

    Payload: Event, User Base, Game, Game Score

  • Game over
    Description: Event sent every time the Player completes a Game Round and submits a Game Score.

    Payload: Event, User Base, Game, Game Score

  • Winners - Prizes
    Description: Event sent with the generated winners (array) when a Game or Game Period expires.

    Payload: Event, [Prizes]

Game - Events

  • Game Center SignUp
    Description:Event sent when the Player successfully registers in your Game Center.

    Payload: Event, User Base, Game Center

  • Game Center Additional Form Submission
    Description:Event sent when the Player submits the form of additional parameters in your Game Center. This event will happen if you add parameters to your Game Center and the Player is already registered.

    Payload: Event, User Base, Game Center

  • Game Center Rewards
    Description:  Event sent when the Player purchase a Reward in the Game Center.

    Payload: Event, User Base, Game Center, Game Center Reward

 

[POST] Gamification

This guide is for external Gamification Condition - events created in Flarie Studio.

Example / Use Case

Company X run an e-commerce selling clothes online and want to increase their sales on t-shirts. To do so they incentives Customers by giving out 5 game attempt to a promotional competition with great prizes every time a Customer buy a t-shirt. 

Company X has created a Gamification Condition in Flarie Studio that is configured to give 5 game attempts to the customer every time this api is called. 

When the Customer purchase a t-shirt, Company X will trigger the api from their backend. 

Company X has a unique identifier on their end on every Customer. This is passed as the playerIdentifier in the api. When it’s time for the Customer to play in the competition the same playerIdentifier is passed to the game as a URL Parameter. 

[POST] https://prod-api.flarie.com/v1/public/gamification

Payload

{
  "accessKey": "string",
  "gamificationConditionId": "string",
  "playerIdentifier": "string"
}

 

Name Type Description

accesskey

string

Brand Access Key. You can generate your accessKey in Flarie Studio → Manage Brand Assets

gamificationConditionId

string

Gamification Condition Id. You will find your gamificationConditionId in your Flarie Studio Gamification Condition.

playerIdentifier

string

Player unique identifier

 

Response Message

Status code

Message

201

Created

400

Bad Request Your accessKey / gamificationConditionId / playerIdentifier is invalid.

403

Forbidden Your accessKey isn't permitted to access the gamificationConditionId

500

Internal Server Error

 

[GET] Gamification

This guide is for getting the number of attempts for a single playerIdentifier in a gamification.


[GET] https://prod-api.flarie.com/rest/gamification-service/v1/player-gamifications/player-identifiers/{playerIdentifier}/gamifications/{gamificationId}

 

URL Parameters

Name

Type

Description

playerIdentifier

string

The unique identifier of the player

gamificationId

string

The gamificationId of your gamification setup

Note! you need gamificationId, not the gamificationConditionId. You can locate your gamificationId in the URL on the edit gamification page.

 

Response(200)

{
  "playerIdentifier": "demo-player-identifier",
  "entityType": "PLAYER_GAMIFICATION",
  "gamificationId": "xxxxx-xxxxxx-xxxxxx-xxxxxxxx",
  "updatedAt": "2023-11-10 12:58:14",
  "createdAt": "2023-11-10 12:57:37",
  "SK": "xxxxx-xxxxxx-xxxxxx-xxxxxxxx",
  "attempts": 4,
  "PK": "PLAYER_GAMIFICATION#demo-player-identifier",
  "id": "090cb380-2663-4cae-a20d-85967d03c78c"
}