Chuyu
Chuyu

Reputation: 93

how to write a php to get the json post from a webhook?

I add my url xxx/getjson.php to a webhook and once a person signup, it will post the json data to my url. I use http://requestb.in/ to check the data and the result is like this:

payload{ "signup": { "address": { "address1": "XX",
                                  "country": "United States"},                     
                     "id":22}}
token

the php script i write is:

$obj=json_decode($_POST);            //cannot get the json data

$userid=$obj->signup->id;

Also I don't know how to use the 'payload'

I find a similar sample code and I test it well using their web hooks. http://support.unbounce.com/entries/307685-how-does-the-form-webhook-work However, they use 'data.json' rather than 'payload' as parameters.

$form_data = json_decode($unescaped_post_data['data_json']);  
$userid= =$form_data->signup->id;

I used their stripslashes_deep function, and replaced the 'data_json' with 'payload' but still doesn't work.

I really appreciate your help.Thanks!

Upvotes: 6

Views: 27200

Answers (3)

Francis Yaconiello
Francis Yaconiello

Reputation: 10919

it looks like $obj=json_decode($_POST); is failing to decode your JSON string.

I think that the problem you are having is that you are not properly JSON encoding your "payload" data.

payload{ 
    "signup": { 
             "address":{ 
                     "address1": "XX",
                     "country": "United States"
              },                     
              "id":22
     }
}

token is not formatted properly. { "signup": { "address": { "address1": "XX","country": "United States"},"id":22}} is the correct JSON string. the extra stuff on either end of the JSON will cause it to not be parsable.

$_POST['payload'] would probably be how you access it.

Also, you didnt give us enough code to really help. we need either the HTML form, or the Javascript that is actually sending/building the POST. (or are you using something like Curl?)

Upvotes: 0

Chuyu
Chuyu

Reputation: 93

Finally worked it out! Only three lines needed but I spent the whole day... The webhook API provider should provide some more information about it. Thanks for your help!

$data = $_REQUEST["payload"];           
$unescaped_data = stripslashes($data);
$obj = json_decode($unescaped_data);
$userid = $obj->signup->id;

Upvotes: 3

user1403947
user1403947

Reputation:

$_POST will be an array so you need to specify the key.

$obj=json_decode($_POST['payload']); // put the second parameter as true if you want it to be a associative array

$userid=$obj->signup->id;

Upvotes: 3

Related Questions