CodeIgniter Returns Uknown Response on IFTTT - php

I am testing the CodeIgniter 3.1 code by making a simple web service.
I found some issue with the response of the API on IFTTT.
The code I have used for the API response in the CI Controller is as below
public function setup()
{
$method = $_SERVER['REQUEST_METHOD'];
$header = $this->input->request_headers();
$IFTTT_Channel_Key = $header["Ifttt-Channel-Key"];
$IFTTT_Service_Key = $header["Ifttt-Service-Key"];
if(
("xyz" === trim($IFTTT_Channel_Key) ) &&
("xyz" === $IFTTT_Service_Key)){
$data = array(
"data" => array(
"accessToken" => "1224124112411",
"samples" => array(
"actions" => array(
"turn_on_light" => array(
"device_name" => "my_device"
)
)
)
)
);
$ci =& get_instance();
$this->output->set_status_header(200);
$ci->output->set_content_type('application/json');
$ci->output->set_output(json_encode($data));
echo json_encode($data);
}
}
The response in the IFTTT Platform :
���{"data":{"accessToken":"1224124112411","samples":{"actions":{"turn_on_light":{"device_name":"my_device"}}}}}
The Response in the Postman tool :
{"data":{"accessToken":"1224124112411","samples":{"actions":{"turn_on_light":{"device_name":"my_device"}}}}}
Note: Please don't edit the question without understanding the actual issue. Please

Related

Bing Search API in PHP - missing webPages property in json response

I am trying to get search results as per the api documentation
Here is what I wrote in PHP
require_once 'HTTP/Request2.php';
$api_key = 'my_bing_search_api_key';
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');
$headers = [
'Ocp-Apim-Subscription-Key' => $api_key
];
$request->setHeader($headers);
$url = $request->getUrl();
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
$url->setQueryVariables($parameters);
$request->setMethod(\HTTP_Request2::METHOD_GET);
$request->setBody("{body}");
$search_result = null;
try {
$response = $request->send();
$search_results = json_decode($response->getBody(), true);
return $search_results;
} catch (HttpException $ex) {
return [];
}
I am getting response but it is not having webPages property. It has _type, rankingResponse, relatedSearches and videos properties only.
I tested the same request in the api console. There I am getting the webPages property in the json response.
Any ideas what could have been the reason why I am not getting the webPages in PHP but works on microsoft's api tester site?
From the code snippet, you are passing the keyword to Bing web search API after encoding it.
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
Try without encoding the keyword. From their API testing console, HTTP request for the same keyword would appear as
https://api.cognitive.microsoft.com/bing/v5.0/search?q=animation
concepts and tutorials&count=10&offset=0&mkt=en-us&safesearch=Moderate

WordPress REST API Basic Authentication

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.

Sharepoint GetListItemChangesSinceToken CURL request in PHP

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.

How to Integrate 3rd party API in Wordpress

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>';
}

Laravel Json response function

I am currently developing an application in Laravel (v4.2.11) which is using ExtJS (v4.2.1-gpl).
As part of my ExtJS application, I am developing a JSON response that is used by ExtJS. However, I want to do the following thing:
return Response::json(array(
'menusystem' => array(
'listeners' => array(
'click' => function() {
location.href = 'test'
}
)
)
);
I do know this is not valid JSON. However, this is the way how the previous developer of the application did it that way. I'd like to know if this is possible within PHP, Laravel or JSON.
You can do something like this
$response = array(
'menusystem' => array(
'listeners' => array(
'click' => "%%%function() {
location.href = 'test'
}%%%"
)
)
);
$response = json_encode($response);
$response = str_replace('"%%%', '', $response);
$response = str_replace('%%%"', '', $response);
return $response;
It's only general conception. You can detect function structure in special macro etc.

Categories