Webhook and php

Hello,
I am working on cards game,other game logic is done but for disconnect by server,timout and rejoin.-player session management work remaining. Turnbased demo is very good for storing and fatching room data.
I want to develop webhooks in php,because my other services in php and i have no idea how to create and manage webhooks in php and assign in photon server settings.

Please give me some information or demo for this.

Thanks in advance...

Comments

  • JohnTubeJohnTube mod
    edited April 2016
    Hi @UnityGames,

    What is it exactly that you want to achieve using webhooks? Room State persistence?
    Are you looking for a sample of implementation or an example of configuration?

    There are several PHP frameworks out there and multiple DB solutions (SQL or noSQL). So the technical choice for a sample in PHP can't cover them all. However, we are thinking about updating existing samples on github and add new ones.
  • Hello,
    Yes,I want to store Room State persistence in my db.
    My question is:
    -Can I use php - webhook for storing room event(In Photon server)?

    if yes please give me some urls to create webhook in php and configuration to photon.

    Thanks
  • Of course, you can implement your own web service in PHP to intercept Photon webhooks. There are already customers who are doing this. Until we provide a sample using PHP, you can start working on your own and we think it is not that difficult once you understand basic concepts.

    For room state persistence you need to have at least, 2 implemented and configured endpoints for PathCreate and PathClose webhooks. You can have one or two PHP scripts to receive incoming HTTP POST requests, process them and return HTTP responses with JSON inside. In PathClose, type "Save" you should save room State in a database. In PathCreate, type "Load" you need to load room state from your database using GameId.

    Please follow webhooks documentation and tell us where you hit a dead end.
  • Hello,
    We create one webhook for GameCreate.
    Base Url and PathCreate Set properly but every time its give me error in unity
    Operation 227 failed in a server-side plugin. Check the configuration in the Dashboard. Message from server-plugin: Failed to create game on http://serverAddress/cardgame/GameCreate.php/Game_create?Unexpected Response '{"m":"3"}'.

    please help me...
  • JohnTubeJohnTube mod
    edited April 2016
    As explained in the docs, you should always return a JSON object containing at least ResultCode property. Example: {ResultCode:0, Message: 'OK'}. When loading the room state: {ResultCode:0, State: <roomState>}.
  • Hello,
    Every time response come from photon server is blank.
  • JohnTubeJohnTube mod
    edited April 2016
    Yes, currently Photon webhooks does not support returning data to client. However, there is a workaround:
    In PathEvent and PathGameProperties you can return data to client as follows:
    • You need to enable HasErrorInfo in webhooks configuration (HasErrorInfo = true).
    • In webhook response return {ResultCode:x, Message: '<data>'} where x is different than 0.
    • On client you will receive ErrorInfo event. Unfortunately, you need to tweak PUN a bit to be able to process that event. You can add this snippet to OnEvent in NetworkingPeer.cs line 2046:
    
    case EventCode.ErrorInfo: // 251
          if (PhotonNetwork.OnEventCall != null)
          {
                object content =  photonEvent[ParameterCode.Info];
                 PhotonNetwork.OnEventCall(photonEvent.Code, content, actorNr);
           } else
           {
               Debug.LogWarning("Warning: Unhandled event " + photonEvent + ". Set PhotonNetwork.OnEventCall.");
            }
    break;
  • Hello Guys,


    I have created one PHP script that accepts JSON string returns from photon server and add required information to our mysql database. How ever when we have configured this webhook on photon server we are getting following error.

    Failed to create game on /rummycafe/GameCreate.php/Game_create?Game_create : Response is not valid json 'Array
    (
    [Game_create] =>
    )

    following is my php script code:

    <?php

    $json=stripslashes($_REQUEST['Game_create']);
    $jsonRes = json_decode($json, true);
    $ActorNr = $jsonRes['ActorNr'];
    $MaxPlayers = $jsonRes['CreateOptions']['MaxPlayers'];
    $LobbyType = $jsonRes['CreateOptions']['LobbyType'];
    $GameId = $jsonRes['GameId'];
    $Type = $jsonRes['Type'];

    /* CODE TO INSERT DATA INTO DATABASE */

    ?>

    Any help would be much appreciate. Thank you in advance
  • JohnTubeJohnTube mod
    edited April 2016
    Please do not start forum discussions and send emails at the same time. Please do not send multiple emails about same subject.

    First, I think you should adjust configuration:

    Base URL should be http://<ip>/rummycafe
    PathCreate: GameCreate.php
    And you should configure and implement PathClose, eg. GameClose.php

    Webhooks are HTTP POST requests that contain JSON data. I can't understand why are you looking for Game_Create key? In your code I can't see where do you return HTTP response with JSON data.

    I can't really write code for you if that's what do you expect. I explained webhooks concepts and what's needed to save and load room state. I believe documentation contains enough details. Maybe someone else on the forum can help you with PHP code.
  • Thanks JohnTube...
  • edited April 2016
    Hi John,

    Thank you for your reply. we have made necessary changes in Base URL and PathCreate as you have suggested.

    Our Base URL: http:///rummycafe
    PathCreate: GameCreate.php

    we did try to send entire request object to our mail. but we are getting only 1 in mail with print_r($_REQUEST) and blank json object with json_encode($_REQUEST). no json string. as you said webhook are HTTP request, means we should get json string when we call webhook,

    Can you just tell us using which parameter we can access json string sent by Photon server.
    because in POST we have many other headers in request as well.

    Yes, we did sending json response but didn't included it in previous post. We have modified our php scriot and only placed below code in webhook script. ]
    
    $jsonRes = json_encode($_REQUEST, true);
    mail(<MAIL ID>,'test-photon',json_encode($_REQUEST));
    $outputjson['m'] = '1'; 
    $temp_outputjson = ($outputjson);
    echo json_encode($temp_outputjson);
    Photon configuration is changed as below:



    Any help would be great. Thanks in advance.


  • @UnityGames please try to use code-highlighting in your posts. I added that as an example to your last post. Makes it a lot easier to read. You can format with the according buttons above the editor. Thanks.
  • @Markus, Sure will do it for future post. Thank you for your suggestion. :)
  • JohnTubeJohnTube mod
    edited April 2016
    @UnityGames,

    There is no such thing as Game_Create sent from Photon. Please get arguments directly from request body.

    And again I invite you to re read webhooks documentation. I already told you that PathClose webhook is needed in order to save room state.

    First, I highly recommend you to use Postman to test your webhooks implementation and Runscope to log all webhooks calls.

    I'm not a PHP expert unless you want me to Google things for you and paste Stackoverflow answers here. At least tell us what PHP version you are using, which framework -if any-.

    You are asking 2 questions here:
    How to get JSON data from HTTP POST request in PHP?
    How to send HTTP response with JSON data in PHP?
  • @JohnTube
    Thank you for your replay, we have removed Game_Create parameters from our script, we are accessing arguments directly from request body. if you check script in our previous post
    mail(<MAIL ID>,'test-photon',json_encode($_REQUEST));
    $outputjson['m'] = '1'; 
    $temp_outputjson = ($outputjson);
    echo json_encode($temp_outputjson);
    but we are getting only [] in mail body.

    we are using custom php to write our webhook no framework. Currently our concern is to get json object from photon server.

    and Yes currently we have only one question:

    1. How to get JSON data from HTTP POST request in PHP?

    We are not expecting you to write code for us but it will much help full if you can share any such resolved question for webhook in php.

    Our configuration on photon server is also attached in our second last post.
    Any help would be great. Thanks in advance.
  • I asked one of our customers, Julian Mautner, from StillAlive studios, to give us a code snippet of how they are using webhooks in PHP. Here is what he sent me:
    <?php
    //read input from webhook 
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    
    //------------------------------------------------------------------//
    
    //in case of an error this will usually stay an empty array and return the result code 1. If specific errors occur, other error numbers are returned.
    $reply = array();
    
    //handle event: access request via object: $req->GameId, etc.
    if($obj->Type == "Save")
    	$reply = saveRequest($obj);
    else if($obj->Type == "Load")
    	$reply = loadRequest($obj);
    else if($obj->Type == "Close")
    	$reply = closeRequest($obj);
    else if($obj->Type == "Join")
    	$reply = array("ResultCode" => 0);
    
    //------------------------------------------------------------------//
    
    if(count($reply) <= 0)
    	$reply = array("ResultCode" => 0, "Message" => "Unhandled request type ".$obj->Type."!");
    echo json_encode($reply);
    
    //------------------------------------------------------------------//
    
    function saveRequest($req)
    {
    	//... todo
    	
    	if(success)
    		return array("ResultCode"=>0);
    	else
    		return array("ResultCode"=>1, "Message"=>"Creating/Updating save-game failed! ".$req->GameId);
    }
    ?>
  • @JohnTube ,

    Cheers!!!

    Its works, thank you so much for your help. Main change was we were trying to accept json string from request body using $_REQUEST, while actually it should be file_get_contents('php://input')

    Thank you for your help again.
  • I'm glad your problem was solved.
Sign In or Register to comment.