I work at an MSP and I'm trying to integrate our ticketing system (Autotask) with Slack. So far, I have set up an HTTP POST request to some PHP code when a new ticket is created, which posts a chat message in a certain channel ("New Ticket Created! [Ticket Title] - [Ticket Description]" etc.) using Incoming Webhooks. Below is the important bits of that code:
<?php
require_once __DIR__ . '/src/autoload.php';
//Gets ticket number from HTTP POST
$ticketNum = $_POST['subject'];
//Generated at api.slack.com/apps > Incoming webhooks (for the channel I'm posting in)
$responseURL = 'https://hooks.slack.com/services/XXXXXXXXXXXX';
class Response {
public $response_type = "";
public $text = "";
public $attachments = array();
}
//*****
//QUERYING TICKETING SYSTEM API FOR TICKET INFORMATION
//THIS CODE WORKS, OMITTED FOR EASIER READING
//*****
$r = new Response();
$r->response_type = "in_channel";
$r->text = "New Ticket Created: \n*".$ticketName."* (".$ticketNum.") \n".$ticketDescription;
$r->attachments = array(
0 => array('callback_id' => 'newTicketAction', 'text' => 'Select an action:',
'color' => '95baa9', 'actions' => array(
0 => array('name' => 'newTicketAction', 'text' => 'Accept', 'type' => 'button',
'value' => 'accept', 'style' => 'primary'),
1 => array('name' => 'newTicketAction', 'text' => 'View', 'type' => 'button',
'value' => 'view')
)
)
);
header('Content-Type: application/json');
//Using CURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $responseURL,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($r)
));
$resp = curl_exec($curl);
var_dump($resp);
curl_close($curl);
?>
This works and posts a message in the correct channel that looks like this:
The problem I'm having is with responding to those button clicks. I have my Request URL set up, pointing to another PHP script. My understanding is that the button click sends another HTTP POST request to this page with a JSON object, which has a payload item. My hunch is I'm accessing this incorrectly. My code is below:
<?php
require_once __DIR__ . '/src/autoload.php';
//get information from HTTP POST, sent at button click
$payload = $_POST['payload'];
$data = json_decode($payload,true);
$responseURL = $data -> response_url;
class Response {
public $response_type = "";
public $text = "";
public $attachments = array();
}
$r = new Response();
$r->response_type = "in_channel";
$r->text = "Ticket Accepted";
header('Content-Type: application/json');
//Using CURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $responseURL,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($r)
));
$resp = curl_exec($curl);
var_dump($resp);
curl_close($curl);
?>
You can see right now I'm just trying a simple response message for testing purposes, but when I click the 'Accept' button I get the following response:
I've scoured the web and cannot find a solid tutorial on Interactive Messages which includes "receiving" button clicks. Any help would be greatly appreciated.
PHP syntax was wrong for accessing array element.
Related
I'm trying to fetch subtitles from OpenSubtitles (http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC) like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Opensubtitles listing
function data($request){
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://api.opensubtitles.org/xml-rpc'; // api url
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
return $response;
}
//Get token
$request = xmlrpc_encode_request("LogIn", array('', '', 'eng', 'TemporaryUserAgent'));
$token = data($request)['token'];
//Get listing
$request = xmlrpc_encode_request("SearchSubtitles", array(
'imdb' => '0462499',
'sublanguageid' => 'eng',
'season' => '',
'episode' => '',
'token' => $token
));
$response = data($request);
var_dump($response);
?>
However I keep getting 401 Unauthorized. Does anyone know how to fix this problem? I know it's not a problem with the API because I am able to retrieve the token just fine.
Try using your username/password instead empty string.
And change UserAgent in TemporaryUserAgent in Header as written in
http://trac.opensubtitles.org/projects/opensubtitles/wiki/DevReadFirst
The second request should be in the following format:-
$request = xmlrpc_encode_request("SearchSubtitles", array($token, array(array('sublanguageid' => 'eng', 'imdbid' => 'your_imdbid'))));
Hope this helps.
I am currently building a routine that needs to download files from one specific Dropbox folder , send them to another server and then move them to another folder on Dropbox.
I am using the /files/move_batch API endpoint for Dropbox to do so.
Here are the params sent to the API to move multiples files (well I'm only trying to move one file right now as it's still not working) :
$params = array(
'headers' => array(
'method' => 'POST',
'content-type' => 'application/json; charset=utf-8',
),
'body' => json_encode(array(
'entries' => array(
'from_path' => self::$files[0],
'to_path' => '/Applications/Archives/' . substr(self::$files[0], strrpos(self::$files[0], '/') + 1),
),
'autorename' => true,
)),
);
But I keep getting the same error message :
Error in call to API function "files/move_batch": request body: entries: expected list, got dict
I don't know what the API means by a list or how it should be formated.
The entries value should be a list of dict, one per file you want to move, each one containing both a from_path and a to_path. Your code is supplying the entries value to be a single dict though. (In PHP you can make both lists and dicts using the array keyword.)
It's easier to see and work with when you break it into pieces. Here's a working sample that does that.
<?php
$fileop1 = array(
'from_path' => "/test_39995261/a/1.txt",
'to_path' => "/test_39995261/b/1.txt"
);
$fileop2 = array(
'from_path' => "/test_39995261/a/2.txt",
'to_path' => "/test_39995261/b/2.txt"
);
$parameters = array(
'entries' => array($fileop1, $fileop2),
'autorename' => true,
);
$headers = array('Authorization: Bearer <ACCESS_TOKEN>',
'Content-Type: application/json');
$curlOptions = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($parameters),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
);
$ch = curl_init('https://api.dropboxapi.com/2/files/move_batch');
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
?>
To move just one file using this batch endpoint, you would change that line to something like:
'entries' => array($fileop1),
I am working on a project that requires some integration between different WordPress instances and I am in the process of creating a WordPress plugin that will provide that functionality through the REST API.
I have enabled the WP-API plugin and the Basic Authentication plugin and am able to make requests that do not require authentication but when I make a request that does require authentication, such as adding a new page, I am met with 401 - Sorry, you are not allowed to create new posts.
I realize basic authentication is not suitable for production needs but would like to get it working properly for development and have been spinning my wheels on this seemingly small problem. I am perfectly able to make these requests using Postman, so there is something wrong with my implementation. Here is the code in question:
function add_new_page($post) {
// Credentials for basic authentication.
$username = 'user';
$password = 'password';
// Request headers.
$headers = array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
'Content-Type' => 'application/json'
);
// Request URL.
$url = "http://localhost/wp-json/wp/v2/pages";
// Request body.
$body = array(
'slug' => $post->post_name,
'status' => $post->post_status,
'type' => $post->post_type,
'title' => $post->post_title,
'content' => $post->post_content,
'excerpt' => $post->post_excerpt,
);
$body_json = json_encode($body);
// Request arguments.
$args = array(
'method' => 'POST',
'blocking' => true,
'headers' => $headers,
'cookies' => array(),
'body' => $body_json,
);
// Fire request.
$response = wp_remote_request($url, $args);
// Handle response.
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
$response_body = json_decode(wp_remote_retrieve_body($response));
// Display response body.
echo '<pre>';
print_r($response_body);
echo '</pre>';
}
// Exit so we can read the response.
exit();
}
I would be really appreciative of any insights somebody out there could provide.
I'm trying to get the latest changes from my documentlist in Sharepoint using PHP and GetListItemChangesSinceToken. I'm using phpSPO as a SDK since there aren't any official Sharepoint SDK's for PHP.
So far I have this:
$payload = array(
'query' => array(
'__metadata' => array('type' => 'SP.ChangeLogItemQuery'),
'ViewName' => '',
'QueryOptions'=> '<QueryOptions><Folder>Shared Documents</Folder></QueryOptions>'
)
);
$headers = array();
$headers["X-HTTP-Method"] = "MERGE";
$changes = $this->request->executeQueryDirect($this->settings->URL . "/_api/web/Lists/GetByTitle('Documents')/GetListItemChangesSinceToken", $headers, $payload);
Which returns: {"error":{"code":"-2147467261, System.ArgumentNullException","message":{"lang":"en-US","value":"Value cannot be null.\r\nParameter name: query"}}}
I've tried changing the X-HTTP-Method and changing the array to fit the documented JSON/XML request (XML in JSON objects, come on Microsoft)
First approach
The following example demonstrates how to utilize GetListItemChangesSinceToken method:
$listTitle = "Documents";
$payload = array(
'query' => array(
'__metadata' => array('type' => 'SP.ChangeLogItemQuery'),
'ViewName' => '',
'QueryOptions'=> '<QueryOptions><Folder>Shared Documents</Folder></QueryOptions>'
)
);
$request = new ClientRequest($webUrl,$authCtx);
$options = array(
'url' => $webUrl . "/_api/web/Lists/GetByTitle('$listTitle')/GetListItemChangesSinceToken",
'data' => json_encode($payload),
'method' => 'POST'
);
$response = $request->executeQueryDirect($options);
//process results
$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('z', '#RowsetSchema');
$rows = $xml->xpath("//z:row");
foreach($rows as $row) {
print (string)$row->attributes()["ows_FileLeafRef"] . "\n";
}
Second approach
Since SharePoint REST Client SDK for PHP now supports GetListItemChangesSinceToken method, the previous example could be invoked like this:
$list = $ctx->getWeb()->getLists()->getByTitle($listTitle);
$query = new ChangeLogItemQuery();
//to request all the items set ChangeToken property to null
$query->ChangeToken = "1;3;e49a3225-13f6-47d4-a146-30d9caa05362;635969955256400000;10637059";
$items = $list->getListItemChangesSinceToken($query);
$ctx->executeQuery();
foreach ($items->getData() as $item) {
print "[List Item] $item->Title\r\n";
}
More examples could be found here under phpSPO repository.
I'm using wordpress and i want to integrate an SMS API into my wordpress site. Can anyone help in knowing where (in which file) to write the code for integration and also the code to integrate SMS API.
My SMS API Url is :
http://www.elitbuzzsms.com/app/smsapi/index.php?key=KEY&campaign=****&routeid=**&type=text&contacts=< NUMBER >&senderid=SMSMSG&msg=< Message Content >
I want to integrate above API in my wordpress theme so that i can send sms based on mobile number and add required message.
In wordpress you can use wp_remote_get and wp_remote_post
get request example
$url = 'http://www.elitbuzzsms.com/app/smsapi/index.php?key=KEY&campaign=****&routeid=**&type=text&contacts=< NUMBER >&senderid=SMSMSG&msg=< Message Content >';
$response = wp_remote_get( $url );
if( is_array($response) ) {
$header = $response['headers']; // array of http header lines
$body = $response['body']; // use the content
}
post request example
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'username' => 'bob', 'password' => '1234xyz' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}