My page won't answer the Messenger call - php

I'm developing some code that answers via Facebook Messenger and I use this piece of code to handle the answer and answer back:
if(isset($_REQUEST['hub_verify_token'])) {
if ($_REQUEST['hub_verify_token'] === A::VERIFY_TOKEN) {
echo $_REQUEST['hub_challenge'];
exit;
}
}
$input = json_decode(file_get_contents('php://input'), TRUE);
$sender_id = $input['entry'][0]['messaging'][0]['sender']['id'];
$message_text = $input['entry'][0]['messaging'][0]['message']['text'];
$fb_handler = new FBHandler($sender_id);
/*$to_send = array(
'recipient' => array('id' => $sender_id ),
'message' => array('text' => "Hi" )
);*/
$to_send = $fb_handler->talk($message_text);
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.A::ACCESS_TOKEN);
curl_setopt_array($ch, array(
CURLOPT_POSTFIELDS => json_encode($to_send),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));
$response = curl_exec($ch);
error_log($response['error']);
curl_close($ch);
What I don't understand is why the commented $to_send works but the non-commented not, because the code in the A class is correct, it composes correctly the array.
So I came up with an idea and I'm asking you if it's correct (because I found nothing in the Facebook Developers documentation): is it possible that the array that will be sent to Messenger has to be composed in the same set of instructions?
I know it sounds ridiculous, but I dunno what else to think.
Also I noticed that error_log doesn't work: nothing has been written in the php_errorlog file. What's happening?

Related

Php: get response from a posted form on an external service

This would seem an easy task, but I can't get it to work.
I need to access some data publicly provided by the Bank of Mexico. The data is available through a form you can find at the link: http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarCuadro&idCuadro=CP5&locale=es
You can see an example of the data I need by clicking on the button "html" on the top left section. Once that table is opened I know how to fetch the data I need and work with them. However, I'd like to have this as an automated task so that the script can check regularly when new data is available.
So, I am trying to use file_get_contents() along with stream_context_create() to post the parameters I need and open the result page, so I can work with it.
I tried a few different ways (first I was using http_post_fields() ), but nothing seems to work.
Right now my code is this:
<?php
$url = 'http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries';
$data = array(
'anoFinal' => 2015,
'anoInicial' => 2015,
'formatoHTML.x' => 15,
'formatoHTML.y' => 7,
'formatoHorizontal' => false,
'idCuadro' => 'CP5',
'locale' => 'es',
'sector' => 8,
'series' => 'SP1',
'tipoInformacion' => '',
'version' => 2
);
$postdata = http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
//returns bool(false)
?>
What am I missing? I noticed that the page does in fact return nothing if wrong parameters are sent (as you can see by opening simply http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries without any post data: nothing is returned), thus I'm not sure whether the post is successful but nothing is returned because some parameters are wrong, or if the code is wrong.
The posted data should be fine, as I copied them directly from a successfull query I made manually.
What am I missing?
It turns out cURL is a better way to do this, thanks to CBroe for the advice.
Here is the fixed code I am using, if someone else needs it:
<?php
//$url and $data are the same as above
//initialize cURL
$handle = curl_init($url);
//post values
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
//set to return the response
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
//execute
$response = (curl_exec( $handle ));
?>

LinkedIn API - posting to a group or profile share returns a 401 authentication code

I had a problem with no documented solution that I could find. Now that I found it, I'm posting it here in the event someone runs into the same issue.
I followed the steps to authenticate with LinkedIn and get an access token, I was able to retrieve my profile information and groups that I belong to without any issue.
Next, I wanted to make a post to a group using the API.
The LinkedIn API docs show the use of file_get_contents, but it was not working for me. The access token was correct, but I was receiving a 401 response. Refer to https://developer.linkedin.com/documents/code-samples. Because I added ignore_errors=1, the group post was made, but still returning a 401.
As reference, this was the piece of code that I had to change to resolve the 401:
$context = stream_context_create(
array('http' =>
array('method' =>"POST",
'header'=> "Content-Type:application/json\r\n",
'content' => $body,
'ignore_errors' => '1'
)
)
);
$res = file_get_contents($url, false, $context);
Solution Overview
Using the LinkedIn API to post to a group, the steps are:
Set up the URL:
$params = array('oauth2_access_token' => YOUR_ACCESS_TOKEN);
$url = 'https://api.linkedin.com/v1/groups/{group_id}/posts?' . http_build_query($params);
Set the body for the POST
$bodyArray = array(
'title' => $title,
'summary' => $userMessage,
'content' => array(
'title' => '$title2',
'submitted-image-url' => $pictureUrl,
'submitted-url' => $redirectUrl,
'description' => $userMessage
)
);
$body = json_encode($bodyArray);
Use CURL instead of get_file_contents This is what I needed to change to get it working.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => $body,
));
// here we execute the code and check for response code
curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($http_status == "201"){
echo date('g:i') . ' Posted to LinkedIn group <br>';
}else{
echo date('g:i') . '<b>LinkedIn error: ' . $http_status . '</b><br>';
}

Sending push notification using parse using query

I want to send push notification using query
for example
I have this query
$ages = array(18,19,20,21)
$parseQuery = new parseQuery('_User');
$parseQuery->whereContainedIn('age', $ages);
$result = $parseQuery->find();
and I want to send them a push notification
Should I use the Installation or is theres another way ?
Thanks
UPDATE:
I am using this sdk
https://github.com/apotropaic/parse.com-php-library
from the code I am returning list of people I am going to send them notification
I want to send the push notifications to the _User class
It looks like you're using parseQuery to retrieve a user with the age constraints you specified. Once you have the user data in your $result, you can use curl to send push notifications, according to the docs.
Here's a bit of code I found on the web, it should be simple to adopt it to your existing code to send a push notification to the user you've retrieved.
<?php
$APPLICATION_ID = "xxxxxxxx";
$REST_API_KEY = "xxxxxxxxx";
$MESSAGE = "your-alert-message";
$url = 'https://api.parse.com/1/push';
$data = array(
'channel' => '',
'type' => 'android',
'expiry' => 1451606400,
'where' => array(
'age' => array('$in' => array(18,19,20,21))
),
'data' => array(
'alert' => 'greetings programs',
),
);
$_data = json_encode($data);
$headers = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_exec($curl);
It's worth noting that you need php-curl for this to work. It's very easy to install or enable if you don't already have it. Alternatively you can use file_get_contents to achieve he same thing if you want to use something out of the box.
Edit: I've updated the $data array with the constraints you defined in the question. You don't need to use parseQuery to find users with the updated code. You're effectively telling Parse to apply the constraints with the call.
Update 2: I haven't tested this code but the library makes it very straightforward how to setup in the README. The library is just using curl underneath so you can use whichever is more convenient.
$parse = new parsePush('Sample push message');
$parse->where = array(
'age' => array('$in' => array(18,19,20,21))
);
//create acl
$parse->ACL = array("*" => array("write" => true, "read" => true));
$r = $parse->send();

PHP cURL Json Post - doing something wrong

I'm new to php and I'm trying to create a simple example for calling our company api. I got NetBeans IDE 7.1.2 to work last night (yay) but I cannot seem to get the following code to show me anything. I can run it in the debugger. I can step through it. I even get to the end without errors, but the curl_exec returns just 0. I have added the CURLOPT_PROXYPORT so that I can get fiddler to see the traffic, but fiddler sees nothing. I am also trying to run this as a php command line (if that has any bearing).
I know I'm doing something stupid... but that's the problem with stupid.
<?php
$url = 'https://target.boomerang.com/api/JobCreate';
$authToken = 'phptest';
$data = array(
"emailHTML" => "Howdy",
"jobKind" => "email",
"senderEmail" => "bob#boomerang.com",
"subject" => "My howdy email"
);
$data_string = json_encode($data);
$headers = array(
'Content-type: application/json',
'auth_token: ' . $authToken,
'Accept: application/json',
'Expect:'
);
$ch = curl_init();
$args = array(
CURLOPT_URL => $url,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_PROXYPORT => "localhost:8888"
);
curl_setopt_array($ch, $args);
$res = curl_exec($ch);
$res_data = json_decode($res, true);
print($res_data);
?>
Thanks for any help.
So the problem was caused by SSL certificate mismatch? I suppose it can be solved by adding this...
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
...into $args array.

Make a HTTPS request through PHP and get response

I want to make HTTPS request through PHP to a server and get the response.
something similar to this ruby code
http = Net::HTTP.new("www.example.com", 443)
http.use_ssl = true
path = "uri"
resp, data = http.get(path, nil)
Thanks
this might work, give it a shot.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
for more info, check
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
To open HTTPS stream I could only work it out using both HTTP and SSL context options…
Thus something like:
<?php
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array(
'ssl' => array(
'verify_peer' => false,
'verify_peername' => false
// Instead ideally use
// 'cafile' => 'path Certificate Authority file on local filesystem'
),
'http' => array(
'method' => 'POST',
'header' =>
'Content-type: application/x-www-form-urlencoded'."\r\n".
''
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://example.com/submit.php', false, $context);
// A Good friend
var_dump($http_response_header);
?>
The Zend Framework has a nice component called Zend_Http_Client which is perfect for this kind of transaction.
Under the hood it uses curl to make requests, but you'll find Zend_Http_Client has a much nicer interface to work with and is easier to configure when you want to add custom headers or work with responses.
If all you want to do is retrieve the page contents with minimal work, you may be able to do the following, depending on your server's configuration:
$data = file_get_contents('https://www.example.com/');
Example how to use HttpRequest to post data and receive the response:
<?php
//set up variables
$theData = '<?xml version="1.0"?>
<note>
<to>my brother</to>
<from>me</from>
<heading>hello</heading>
<body>this is my body</body>
</note>';
$url = 'http://www.example.com';
$credentials = 'user#example.com:password';
$header_array = array('Expect' => '',
'From' => 'User A');
$ssl_array = array('version' => SSL_VERSION_SSLv3);
$options = array(headers => $header_array,
httpauth => $credentials,
httpauthtype => HTTP_AUTH_BASIC,
protocol => HTTP_VERSION_1_1,
ssl => $ssl_array);
//create the httprequest object
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//print out the result
echo "<pre>"; print_r($result); echo "</pre>";
?>
There are 2 examples, GET and POST methods, but they both require the HttpRequest library to be included.
If you don't have the HttpRequest library included, kindly check this answer on how to include it: HttpRequest not found in php
GET example:
<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
$r->send();
if ($r->getResponseCode() == 200) {
file_put_contents('local.rss', $r->getResponseBody());
}
} catch (HttpException $ex) {
echo $ex;
}
?>
Post Example
<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
?>

Categories