0
\$\begingroup\$

Some time ago I wanted to be able to create a token in Unity and send it to a Laravel Controller for saving logins and user game data to an account.

I eventually got this working so I am sharing my approach.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

It is a combination of this tutorial on YouTube: How to Use UnityWebRequest - Replacement for WWW Class - Unity Tutorial and this answer on a similar question: UnityWebRequest POST to PHP not work

The technology I am using:

  • Laravel Framework 7.15.0 (PHP)
  • Unity: 2019.3.11f1 (script is C#)

Now I am just sending basic forms not images etc - so I haven't tried anything complex but this sends a get to one URL on Laravel which returns the CSRF token.

This is then added as an additional field to the post request.

I am clicking the 2 buttons pretty quickly - I would suggest (and will implement this myself later) that you don't ask for the token until your ready to submit the form - to avoid it expiring if your form is quite long etc.

The C# Script (Unity)

Both the functions are set as ON Click() on the buttons in a simple UI Canvas in Unity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class BasicWebCall : MonoBehaviour
{
    public Text messageText;
    public InputField scoreToSend;
    private string csrf_token;

    readonly string getURL = "http://mazegames.test/leaderboard/1";
    readonly string postURL = "http://mazegames.test/register/1";

    private void Start()
    {
        messageText.text = "Press buttons to interact with web server";
    }

    public void OnButtonGetScore()
    {
        messageText.text = "Getting Token";
        StartCoroutine(SimpleGetRequest());
    }

    IEnumerator SimpleGetRequest()
    {
        UnityWebRequest www = UnityWebRequest.Get(getURL);

        yield return www.SendWebRequest();

        if(www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            messageText.text = "Token Received: " + www.downloadHandler.text;
            csrf_token = www.downloadHandler.text;
        }
    }

    public void OnButtonSendScore()
    {
        if (scoreToSend.text == string.Empty)
        {
            messageText.text = "Error: No high score to send.\nEnter a value in the input field.";
        }
        else
        {
            messageText.text = "Sending Post Request";
            StartCoroutine(SimplePostRequest(scoreToSend.text));
        }
    }

    IEnumerator SimplePostRequest(string curScore)
    {

        Dictionary<string, string> wwwForm = new Dictionary<string, string>();
        wwwForm.Add("_token", csrf_token);
        UnityWebRequest www = UnityWebRequest.Post(postURL, wwwForm);
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
        }

        else
        {
            messageText.text = www.downloadHandler.text;
        }
    }
}

Laravel routes/web.php

Obviously you need to configure your end points to receive your data, validate and store it if necessary. In this example its just validating the token as part of the post request.

Route::post('register/{game_id}', function($game_id) {
    return "Game On!";
});

Route::get('leaderboard/{game_id}', function($game_id) {
    return csrf_token();
});

And that is pretty much it - hope this helps someone else.

Request Token on Submission

To only get the token when your submitting the form, literally all you have to do is put this line:

StartCoroutine(SimpleGetRequest());

above the line:

StartCoroutine(SimplePostRequest(scoreToSend.text));

so that is looks like this:

StartCoroutine(SimpleGetRequest());
StartCoroutine(SimplePostRequest(scoreToSend.text));

Obviously you could then remove the function SimpleGetRequest altogether.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .