how to send json post in cakephp

Rene Polo picture Rene Polo · Jan 9, 2014 · Viewed 9.3k times · Source

I need to send exactly this:

POST http://api.outbound.io/api/v1/identify
Content-Type: application/json
{
 "api_key": "MY_API_KEY",
 "user_id": "MY_UNIQUE_USER_ID",
 "traits" : {
    "email" : "[email protected]",
    "name" : "Dhruv Mehta",
    "phone" : "650xxxyyyyy"
 }
}

i never did something like this and i've made a lot of research but i couldn't find how to send those parameters to that URL

i hope you guys can help me with an example please, best regards!

Answer

Rene Polo picture Rene Polo · Jan 22, 2014

After a lot of research, i find out how to do it...

1.- Use

App::uses('HttpSocket', 'Network/Http'); // you should put this on your controller

2.- this on your function

$HttpSocket = new HttpSocket(); 

3.- Here comes the data you want to send via POST (in this example i will use the variables i've used.. you can replace them, add more or delete some.. it depends on the info you want to send)

$data = array(
           "api_key" => "API KEY",
           "user_id" => $idUser,
           "event" => "other",
           "extra" => array(
                          "course" => $course,
                          "price"=> $price )
               );

3.- You set the Headers

$request = array(
        'header' => array('Content-Type' => 'application/json',
        ),
    );

4.-json_encode it

 $data = json_encode($data);

5.- Where are you sending the Post To?, which data?, type of request?, do it this way

$response = $HttpSocket->post('http://api.yourweburl.com/api/', $data, $request);

*.- You can see the response uncommenting this snippet

//pr($response->body());

*.- Finally if you want to redirect somewhere after everything is done.. do it this way...

$this->redirect(array('action' => 'index'));

You should have something like this.

public function actiontooutbound($idUser, $course, $price){
 $HttpSocket = new HttpSocket();

    $data = array(
           "api_key" => "API KEY",
           "user_id" => $idUser,
           "event" => "other",
           "extra" => array(
                          "course" => $course,
                          "price"=> $price )
               );

    $request = array(
        'header' => array(
            'Content-Type' => 'application/json',
        ),
    );
    $data = json_encode($data);
    $response = $HttpSocket->post('http://api.outbound.io/api/v1/track', $data, $request);
   // pr($data);
    //pr($response->body());
   $this->redirect(array('action' => 'index'));     

}

This is how you call this function from another function (just in case)

$this->actiontooutbound($idUser, $course, $price); 

if you have any questions let me now i'll be happy to help you ;)