can anyone please give me an example of slack message dialog in PHP? How to make curl call to dialog.open method? Please suggest.
Here is a simple example in PHP of how to create a Dialog based on a slash command.
Note that you need to create and install a Slack App first. You also need to add a slash command to your Slack app, which needs to call this script. Finally you need to manually add the OAuth Access Token from your Slack app to this script (replace YOUR_TOKEN).
The script will print the API response in the Slack channel, so you can the response and if they are any errors.
Execute the slash command to run the dialog.
// define the dialog for the user (from Slack documentation example)
$dialog = [
'callback_id' => 'ryde-46e2b0',
'title' => 'Request a Ride',
'submit_label' => 'Request',
'elements' => [
[
'type' => 'text',
'label' => 'Pickup Location',
'name' => 'loc_origin'
],
[
'type' => 'text',
'label' => 'Dropoff Location',
'name' => 'loc_destination'
]
]
];
// get trigger ID from incoming slash request
$trigger = filter_input(INPUT_POST, "trigger_id");
// define POST query parameters
$query = [
'token' => 'YOUR_TOKEN',
'dialog' => json_encode($dialog),
'trigger_id' => $trigger
];
// define the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
var_export($response);
Related
I have implemented a Slack app using PHP(HTTP-endpoint). Under slack slash commands, I have inserted the request URL (HTTP end-point which points to the code I have written in PHP to open a Slack Modal ) that opens a dialogue box (Slack Modal). And upon submitting the form it will go to GitHub, that I have inserted the URL of my code written in PHP under request URL in interactivity and shortcuts(Payload).
But due to security measures, I want to migrate the app to socket mode. Can someone please let me know how to implement the socket mode for PHP in my local VM?
This is code to open a dialog box in slack
<?php
$slack_token = 'xoxb-******************';
// Dialog Form:
$dialog = [
'callback_id' => 'git_issue',
'title' => 'Add issue',
'submit_label' => 'Create',
'elements' => [
[
'type' => 'text',
'label' => 'Name',
'name' => 'name'
],
[
'type' => 'text',
'label' => 'E-mail',
'name' => 'email'
],
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
How to migrate the application to socket mode?
Thanks in Advance
I use this own-written code. May be it is not perfect, but it works:
<?php
require 'vendor/autoload.php';
// Slack config:
$slack_token = 'xapp-*';
$bot_token = 'xoxb-*';
$url = false;
$dialog = [
'callback_id' => 'git_issue',
'title' => 'Add new GitHub Issue',
'submit_label' => 'Create',
'elements' => [
[
'type' => 'text',
'label' => 'Developer\'s Name',
'name' => 'name'
],
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/apps.connections.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Bearer '.$slack_token
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
if ($response) {
$resp = json_decode($response);
if (isset($resp->url)) {
$url = $resp->url;
}
}
if ($url) {
echo 'Slack returned the websocket URL'.PHP_EOL;
$client = new WebSocket\Client($url, ['timeout' => 3600]);
while (true) {
try {
$message = $client->receive();
echo $message.PHP_EOL.PHP_EOL;
if ($message) {
$data = json_decode($message);
if (isset($data->payload)) {
if (isset($data->payload->command) && $data->payload->command == '/git') {
// Open Dialog:
// define POST query parameters
$query = [
'token' => $bot_token,
'dialog' => json_encode($dialog),
'trigger_id' => $data->payload->trigger_id,
];
// define the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
$query = [
'envelope_id' => $data->envelope_id
];
$client->text(json_encode($query));
// -----------
}
if (isset($data->payload->type) && $data->payload->type == 'dialog_submission') {
// collect submitted data:
$name = $data->payload->submission->name;
$query = [
'envelope_id' => $data->envelope_id,
];
$client->text(json_encode($query));
}
}
}
} catch (\WebSocket\ConnectionException $e) {
// Possibly log errors
var_dump($e);
}
}
$client->close();
}
Configure your Slack app and create tokens:
go to https://api.slack.com/apps page and select existed one or
create a new app
go to "basic information" page, find "App-Level
Tokens" section. Create a new token. I use these scopes
"connections:write, authorizations:read" for it
go to "OAuth & Permissions" page and generate "Bot User OAuth Token"
go to "slash commands" page and create a command. In my code example we have it with the name "/git"
go to "Socket Mode" page and enable the mode with a slide button
For websockets connection via PHP I use this Textalk/websocket-php realization from GitHub.
I am working on a slash command that'll invoke a dialog.
$dialog = [
'callback_id' => 'ryde-46e2b0',
'title' => 'Request a Ride',
'submit_label' => 'Request',
'elements' => [
[
'type' => 'text',
'label' => 'Pickup Location',
'name' => 'loc_origin'
],
[
'type' => 'text',
'label' => 'Dropoff Location',
'name' => 'loc_destination'
]
]
];
// get trigger ID from incoming slash request
$trigger = filter_input(INPUT_POST, "trigger_id");
// define POST query parameters
$query = [
'token' => 'XXXXXXXXX MY TOKEN XXXXXXXXX',
'dialog' => json_encode($dialog),
'trigger_id' => $trigger
];
// define the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
var_export($response);
When I issue the slash command, my test dialog opens successfully
I then fill two test values test1 and test2 in the fields and submit the request. My endpoint is being hit with the dialog data payload correctly, but the data sent is not valid JSON:
The value of $_POST is: (I've masked all identifying tokens/IDs with xxx)
{"payload":"{\\\"type\\\":\\\"dialog_submission\\\",\\\"token\\\":\\\"XXX\\\",\\\"action_ts\\\":\\\"1536603864.688426\\\",\\\"team\\\":{\\\"id\\\":\\\"xxx\\\",\\\"domain\\\":\\\"ourdomain\\\"},\\\"user\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"my_name\\\"},\\\"channel\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"directmessage\\\"},\\\"submission\\\":{\\\"loc_origin\\\":\\\"test1\\\",\\\"loc_destination\\\":\\\"test2\\\"},\\\"callback_id\\\":\\\"ryde-46e2b0\\\",\\\"response_url\\\":\\\"https:\\\\/\\\\/hooks.slack.com\\\\/app\\\\/XXX\\\\/XXX\\\\/XXX\\\",\\\"state\\\":\\\"\\\"}"}
This is an invalid JSON, even when the "\\" instances are removed. Why is this happening?
Here is the code that handles the POST from Slack:
error_log(" -- dialog response: " . json_encode($_POST) . "\n", 3, './runtime.log');
Which results in the output above.
I'm not sure why you are calling json_encode($_POST). The documentation is very clear on the format that will be sent:
$payload = filter_input(INPUT_POST, 'payload');
$decoded = json_decode($payload);
var_dump($decoded);
I have developed a laravel project in which I want to call a REST API to pass a form inputs to it by the use of CURL. After submitting a form by user, form data are passed to a controller, then API is called but I receives false or null as response.
The data must be sent to API as below, as you see the data must be a json in an array(image is not a file, it is a path):
[{
'title' : 'title',
'body' : 'description',
'source' : 'http://www.google.com',
'date' : 1503845107465,
'active' : true,
'image' : '758.jpg',
'category' : [
1
]
}];
here is a part of my controller, $data is build out of form inputs.
$data = [
'title' => 'title',
'body' => 'description',
'source' => 'http://www.google.com',
'date' => 1503845107465,
'active' => true,
'image' => '758.jpg',
'category' => [
1
]
];
$curl=curl_init('http://x.x.x.x/rest/test');
$send = json_encode([$data]);
//return $send;
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $send);
try{
$res = curl_exec($curl);
}catch (Exception $e){
return $e->getMessage();
}
dd($res);
$res is false.
It must be mentioned that the code in controller works on localhost but it does not work on linux server.
I also used ixudra/curl but it does not solve my problem and it returns null.
I got this error Failed to connect to x.x.x.x Permission denied. I can ping this url and I can send data with curl to this IP in a php file. but in laravel I get this error
I am using unification engine #unificationengine API to post message on facebook.
I followed all the steps and created connections to use connectors. All the curl requests are working fine till send message.
In every curl from create user, create connection, connection refresh I am getting
{'status':200,'info':'ok'}
And now I want to use the connector to post message on facebook.
Below is my Curl code:
$post_msg = json_encode(
array(
'message' =>
array(
'receivers' =>
array(
array(
'name' => 'Me',
'address' =>'https://graph.facebook.com/'.$request->profile_id.'/feed?access_token='.$request->access_token.'&message=Hello&method=post',
'Connector' => 'facebook'
),
),
'sender' =>
array('address' => 'sender address'),
'subject' => 'Hello',
'parts' =>
array(
array(
'id' => '1',
'contentType' => 'binary',
'data' => 'Hi welcome to UE',
'size' => 100,
'type' => 'body',
'sort' => 0
),
),
),
)
);
$ch = curl_init('https://apiv2.unificationengine.com/v2/message/send');
curl_setopt($ch, CURLOPT_USERPWD, "0a7f4444-ae4445-45444-449-d9b7daa63984:8755b446-6726-444-b34545d-713643437560");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_msg);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
return ['label' => $response];
and I am getting:
status: 403 and info: forbidden in response.
I have tried everything available in documentation and on stack overflow or any other website. But hard luck.
Please suggest why I am getting this error?
Refrence SO Questions:
SO question 1
SO question 2
Thanks.
Update
I added these three options in curl request:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
and now I am getting 498, invalid access token error:
"{\"Status\":{\"facebook\":{\"status\":498,\"info\":\"Invalid Token:
\"}},\"URIs\":[] }
please use this as per php
public function facebookSharing($access_token) {
$app = new UEApp(env('UNIFICATION_APP_KEY'), env('UNIFICATION_APP_SECRATE'));
$user = new UEUser('unification_userkey', 'unification_usersecret');
$connection = $user->add_connection('FACEBOOK', "facebook", $access_token);
$options = array(
"receivers" => array(
array(
"name"=> "Me"
)
),
"message"=>array(
"subject"=>'testing',
"body"=> 'description',
"image"=> 'use any image url',
"link"=>array(
"uri"=> 'any web site url',
"description"=> "",
"title"=>"Title"
)
)
);
$uris = $connection->send_message($options);
}
The access token might have expired. Please reconnect the facebook connection again or refresh the connection.
The facebook access tokens have a lifetime of about two hours. For longer lived web apps, especially server side, need to generate long lived tokens. Long lived tokens generally lasts about 60 days.
UE has a capability to refresh facebook tokens. After adding connection using "apiv2.unificationengine.com/v2/connection/add"; api call, then you should call "apiv2.unificationengine.com/v2/connection/refresh"; api to make the short lived token to long lived.
i am trying to share a post on a page's wall using facebook api. everything works perfect . but the share button is not coming next to like and comment.
here is my code
$message_body = array(
'access_token' =>Yii::app()->session['page_access_token'],
'message' => $message,
'actions' => array(
array(
'name' => Yii::t('UserController', ' Get details '),
'link' => Yii::app()->createAbsoluteUrl ('user/adminmoreaboutprovider?&postId='.$fbPostId ),
),
),
);
$facebook->api("/".$userpage."/feed","post",$message_body);
Any idea how to bring share link there ?
$msg_body = array(
'message' => $message,
'actions' => array(
array(
'name' => 'Get details',
'link' => Yii::app()->createAbsoluteUrl('user/adminmoreaboutprovider?&postId='.$fbPostId ),
)
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://graph.facebook.com/6creeks/feed');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $msg_body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); //to suppress the curl output
$result= curl_exec($ch);
curl_close ($ch);
This gave me share lin but the get details links is missing on the Page wall. Is there any way to get both of this together?
With curl you can make a post (yes, along with the share button) using the following command.
curl -F 'access_token=XXXX' -F 'message=test' https://graph.facebook.com/[PAGE NAME]/feed
Hope this can be used as is in PHP.