Slack Dialog gives an error - php

I am working on a small slack app development. I stuck in one situation. I am using slack dialog to get data from the user and when user enter data
and click on submit button I get an alert message. I don't know what
is it and why it gives an alert. What to do with this? Please note I get
payload response in my interactive component script. And respond to the server with 200. Here is my Response code :
if($type == "dialog_submission")
{
http_response_code(200);
return json_encode(array(
'status' => 200,
'message' => 'ok'
));
$ch = curl_init("https://slack.com/api/chat.postMessage");
$dataSet = http_build_query([
"token" => $authToken,
"channel" => $data['channel']['name'],
"text" => "123",
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataSet);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
Screenshot of alert message

Try something like:
if($type == "dialog_submission") {
return json_encode(array(
'status' => 200,
'message' => ''
));
}

You need to return an empty response to the Slack Dialog, or you will get the error
We had some trouble connecting. Try again?
So you must somewhere have an echo that returns something to the Slack dialog causing the error. You need to remove those. Like the echo $result; at the end.
This error will also occur if your script has a run-time error, since it will then create an automatic response like "error in test.php line 101....". To check for that make sure you have error logging activated and check if there are any errors in the logfile.
You activate error logging by putting these commands at the beginning of your script:
ini_set("log_errors", 1);
ini_set("error_log", "php-errors.log");
You can however return validation errors to Slack, but those must be in a specific format. See this documentation for details.

Related

Telegram API: popup on telegram “Open this link?” How to avoid?

This is my first post. Hope I get help here. Thanks for reading.
Short version:
When i send a link to my bot, Telegram show a popup "Open this link .... ?" before open the link.
I want to avoid that. Any ideas?
See also questions
Force closure of the popup on telegram “Open this link?”
Is there a way to send links with telegram bot and show no alert on tap/click?
Long Version:
I have a telegram bot, which I'm sending a message from a Raspberry pi
via PHP. Background is some status notification on my smart home.
Please see code below.
I'm send a telegram message with a link attached with an inline keyboard, so that I can provide a certain responds to my smart home.
In other questions I saw that this is connected to the "parse_mode" html. I tried different modes, however the result is always the same.
Also checked the telegram api documentation for help.
https://core.telegram.org/bots/api#formatting-options
https://core.telegram.org/bots/api#sendmessage
As this is just for myself and running only locally, I don't care about cosmetics or security.
I would appreciate any help or new ideas.
Here is my code for reference
function telegram($message,$maschine) {
if (!isset($maschine)) {
echo "no Maschine for telegram";
exit;
}
if (!isset($message)) {
echo "no Message for telegram"; exit;
}
$website = "https://api.telegram.org/bot" . botToken;
$Keyboard = [
'inline_keyboard' =>
[
[
[
'text' => "test",
'url' => '192.168.1.1/test.php,
]
]
]
];
$encodedKeyboard = json_encode($Keyboard);
$params = [
'chat_id'=>chatId,
'text'=> $message,
'reply_markup' => #$encodedKeyboard,
'one_time_keyboard' => true,
'parse_mode'=> 'html'
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$jsonresult = json_decode(curl_exec($ch), true);
curl_close($ch);
if ($jsonresult['ok']==false) {
echo "Telegram Error Code: " . $jsonresult['error_code'] . " - ". $jsonresult['description'] . "<br>";
} else {
echo "Telegram message send<br>";
}
}
I more or less found the answer now to my own question:
I haven't found a solution for the inline_keyboard.
If you comment the keyboard feature out and only use the link in the "text" paramater --> Then telegram is not asking for a extra confirmation to open the link.
See upated code below.
So issue solved. At least for me.
$params = [
'chat_id'=>chatId,
'text'=> 'open this link: 192.168.1.1/test.php',
//'reply_markup' => #$encodedKeyboard,
//'one_time_keyboard' => $setting,
'parse_mode'=> 'Markdown'
];

Trigger ID not found with Slack slash command?

My goal is to be able to use a slash command to open a dialog and process the feedback into a database. I am trying to get the dialog to open but am getting an error regarding the slash command where it says "trigger_id" not found.
My app is set up with an API and the proper OAuth.
I added a slash command to my app with the url of my php page (domain.com/slash.php)
The slash command is set up with the code below.
When I run it from my slack, I get the output of
'{"ok":false,"error":"invalid_arguments","response_metadata":{"messages":["[ERROR] missing required field: trigger_id"]}}'
I have tried some debugging and output the trigger_id to the screen and find that the trigger_id is indeed null. What am I missing to pass this?
I admit that I am new to the slack realm. I have followed (I think) the documentation from the slack site on setting up the app correctly.
Am I missing something with my slack app setup or something in my code that is causing this error message?
Thank you in advance for your time!
<?
$command = $_POST['command'];
$text = $_POST['text'];
$token = $_POST['token'];
$cn = $_POST['channel_id'];
$user_id = $_POST['user_id'];
$triggerid = $_POST['trigger_id'];
// define the dialog for the user (from Slack documentation example)
$dialog = [
'callback_id' => 'validres-3100',
'title' => 'Test',
'submit_label' => 'Submit',
'elements' => [
[
'type' => 'text',
'label' => 'Test Field 1',
'name' => 'field_1'
],
[
'type' => 'text',
'label' => 'Test Field 2',
'name' => 'field_2'
]
]
];
// define POST query parameters
$query = [
'token' => '<my api auth code>',
'dialog' => json_encode($dialog),
'trigger_id' => $triggerid
];
// 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);
?>
To open dialog box in slack you can use this api "https://slack.com/api/views.open".
With api you need to send trigger id which is valid only for 3 seconds.
Your url will looks like :
"https://slack.com/api/views.open?trigger_id=" + "xxxx.xxxxxxxxx.xxxxxxxxxxxx" + "&view=your data".
with this request you need to send token with your post request like :-
(URL,"POST", { "token" ,"xoxb-xxxxxx-xxxxx-xxxxxxx"});
Need to add view.open API in your slack app also for this use following step:
Use "Bot User OAuth Access Token" , In "OAuth and permissions Tab" Format is xoxb-xxxxx-xxxxx-xxxx. And then add scope "views:open" and reinstall your app in slack. And then try to get open view dialog.
Hope this will be helpful.

How do I send info to this API using cURL and PUT?

I am working with an API that is documented here: https://cutt.ly/BygHsPV
The documentation is a bit thin, but I am trying to understand it the best I can. There will not be a developer from the creator of the API available before the middle of next week, and I was hoping to get stuff done before that.
Basically what I am trying to do is update the consent of the customer. As far as I can understand from the documentation under API -> Customer I need to send info through PUT to /customers/{customerId}. That object has an array called "communicationChoices".
Going into Objects -> CustomerUpdate I find "communicationChoices" which is specified as "Type: list of CommunicationChoiceRequest". That object looks like this:
{
"choice": true,
"typeCode": ""
}
Doing my best do understand this, I have made this function:
function update_customer_consent() {
global $userPhone, $username, $password;
// Use phone number to get correct user
$url = 'https://apiurlredacted.com/api/v1/customers/' . $userPhone .'?customeridtype=MOBILE';
// Initiate cURL.
$ch = curl_init( $url );
// Specify the username and password using the CURLOPT_USERPWD option.
curl_setopt( $ch, CURLOPT_USERPWD, $username . ":" . $password );
// Tell cURL to return the output as a string instead
// of dumping it to the browser.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Data to send
$data = [
"communicationChoices" => [
"communicationChoiceRequest" => [
"choice" => true,
"typeCode" => "SMS"
]
]
];
$json_payload = json_encode($data);
print_r($json_payload);
// Set other options
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($json_payload)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
// Execute the cURL request
$response = curl_exec($ch);
// Check for errors.
if( curl_errno( $ch ) ) :
// If an error occured, throw an Exception.
throw new Exception( curl_error( $ch ) );
endif;
if (!$response)
{
return false;
} else {
// Decode JSON
$obj = json_decode( $response );
}
print_r($response);
}
I understand that this is very hard to debug without knowing what is going on within the API and with limited documentation, but I figured asking here was worth a shot anyway.
Basically, $json_payload seems to be a perfectly fine JSON object. The response from the API however, is an error code that means unknown error. So I must be doing something wrong. Maybe someone has more experience with APIs and such documentation and can see what I should really be sending and how.
Any help or guidance will be highly appreciated!
before you test your code, you can use the form provided on the API Documentation.
when you navigate to API > Customers > /customers/{customerId} (GET), you will see a form on the right side of the page (scroll up). you need to provide the required values on the form then hit Submit button. you will surely get a valid data for communicationChoices based on the result from the Response Text section below the Submit button.
now, follow the data structure of communicationChoices object that you get from the result and try the same on API > Customers > /customers/{customerId} (PUT) form.
using the API forms, you may be able to instantly see a success or error from your input (data structure), then translate it to your code.

Send POST Request & Get JSON Response in PHP?

I'm trying to send a POST request via PHP from AJAX. I checked the API with Postman. It is working fine. But it is not getting executed in PHP. It is not showing up in Network Tab also.
I saw a lot of samples for making a POST Request in Stack Overflow & tried it. But I can't figure out where I'm going wrong ?
I have attached both the JS Code & PHP Code here
JavaScript CODE
function editUser(toid, name, mobile, mail, pin, addr, state, dis, subdis, role, user) {
$.ajax({
type: "POST",
url: "edituser.php",
dataType: 'html',
data: {
id: toid,
fullname: name,
phone: mobile,
email: mail,
address1: addr,
state: state,
district: dis,
subdistrict: subdis,
pincode: pin,
usertype: user,
role: role,
token: apptoken,
},
success: function (response) {
visibility(false);
console.log("Response > > " + response);
if (response.status == "SUCCESS") {
swal("Updated User", " Information Updated Successfully!", "success");
}
loadData();
}
});
}
PHP CODE
<?php
// where are we posting to?
$url = 'http://api.tech.com/api/UpdateUser';
// what post fields?
$fields = array(
'id' => $_POST['id'],
'fullname' => $_POST['fullname'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'address1' => $_POST['address1'],
'state' => $_POST['state'],
'district' => $_POST['district'],
'subdistrict' => $_POST['subdistrict'],
'pincode' => $_POST['pincode'],
'usertype' => $_POST['usertype'],
'role' => $_POST['role'],
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
$token = $_POST['token'];
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("AppToken: $token",
"Content-Type: application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// execute post
$result = curl_exec($ch);
echo $result;
// close connection
curl_close($ch);
?>
UPDATE:
The request sent to the API ($url) is not showing in the Network Tab. But the request to edituser.php is shown.
I feel like a lot of context is missing here but I have done a lot of stuff like this so I will try to help out with what I do understand.
Here is what I have gathered so far from your question.
You are calling an ajax function in JavaScript that triggers the given PHP code.
The JavaScript is successful in calling this code "per the network screenshot."
The network tab indicates the PHP script returns nothing.
Here are my thoughts on how to move forward.
You appear to be sending all data from your client side JavaScript including a secure pin and token. This is a very bad idea as it mean your users can all see this secure pin and steal it for their own nefarious purposes. Instead store constants like the secure pin in the php code.
If you are expecting to see the curl request in the network tab you are mistaken. The curl request is going from server to server and will never be seen by the client.
If the response tab is empty you may have something as simple as a syntax error or some kind of curl error that you are not capturing.
Add some of this to your request for debugging:
$result = curl_exec($request);
$response_code = curl_getinfo($request, CURLINFO_HTTP_CODE);
echo 'Response code: ' . $response_code;
if(curl_error($request))
{
echo '<br />Curl error: ' . curl_error($request);
}
You should see the response code at least in the "response" tab of the ajax call.
If you still see nothing make sure your PHP configuration is set up to show all warnings and errors, etc and isn't suppressing the information you need.

Callback from API not happening after posting parameters to API URL from server side

API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.

Categories