Rocket.chat: Integrations with PHP

Created on 26 Aug 2017  路  2Comments  路  Source: RocketChat/Rocket.Chat

Hey folks,

a little bit off topic. But I am trying to get PHP with Curl to work nicely with rocket.chat. The part I am not getting right is the nested array.

Let's consider the default example:

{
  "username": "TestRocket",
  "icon_url": "https://example.com/test.png",
  "text": "Example message",
  "attachments": [
    {
      "title": "Rocket.Chat",
      "title_link": "https://rocket.chat",
      "text": "Rocket.Chat, the best open source chat",
      "image_url": "https://rocket.chat/images/mockup.png",
      "color": "#764FA5"
    }
  ]
}

I can get everything to work but the attachements part. Anyone got some code handy that would work with the above code?

Thanks! :)
-Chris.

Most helpful comment

You, Sir, are a Saint. It works like a charm.

All 2 comments

@christianreiss Try something like this. Just update CURLOPT_URL

<?php

// Get cURL resource
$ch = curl_init();

// Set url
curl_setopt($ch, CURLOPT_URL, 'https://my.rocketchat/hooks/xxxxxxx/h3cxxxxxTwqEk');

// Set method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  "Content-Type: application/json",
 ]
);
// Create body
$json_array = [
            "attachments" => [
                [
                    "color" => "#FF0000",
                    "title" => "Attachment Title",
                    "title_link" => "https://rocket.chat",
                    "image_url" => "https://rocket.chat/images/mockup.png",
                    "text" => "Rocket.Chat, the best open source chat"
                ]
            ],
            "alias" => "TestRocket",
            "channel" => "#mychatroom",
            "text" => "Example message"
        ]; 
$body = json_encode($json_array);

// Set body
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

// Send the request & save response to $resp
$resp = curl_exec($ch);

if(!$resp) {
  die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
  echo "Response HTTP Status Code : " . curl_getinfo($ch, CURLINFO_HTTP_CODE);
  echo "\nResponse HTTP Body : " . $resp;
}

// Close request to clear up some resources
curl_close($ch);

?>

You, Sir, are a Saint. It works like a charm.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Buzzele picture Buzzele  路  3Comments

mddvul22 picture mddvul22  路  3Comments

engelgabriel picture engelgabriel  路  3Comments

Kiran-Rao picture Kiran-Rao  路  3Comments

zeigerpuppy picture zeigerpuppy  路  3Comments