Why is my recaptcha response unsuccessful? - php

I have been looking for what I might be doing wrong and for solutions all over but none seem to rectify my problem. I have a form with a recaptcha, it is pretty simple. But my recaptcha validation fails every time and echo's "Not successful" when it should be successful. What am I doing wrong? Here is my code.
<?php
require_once('src/autoload.php');
require_once('src/ReCaptcha/ReCaptcha.php');
require_once('src/ReCaptcha/RequestMethod.php');
require_once('src/ReCaptcha/RequestParameters.php');
require_once('src/ReCaptcha/Response.php');
require_once('src/ReCaptcha/RequestMethod/Post.php');
require_once('src/ReCaptcha/RequestMethod/Socket.php');
require_once('src/ReCaptcha/RequestMethod/SocketPost.php');
require_once('src/ReCaptcha/RequestMethod/Curl.php');
require_once('src/ReCaptcha/RequestMethod/CurlPost.php');
$gRecaptchaResponse = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$SITEKEY = 'XXXX';
$secret = 'XXXX';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
echo "success";
} else {
$errors = $resp->getErrorCodes();
echo "not success";
echo $errors;
}
?>

//reCaptcha
$StrUrl = "https://www.google.com/recaptcha/api/siteverify";
$StrSecretKey = "XXXXXX";
$data = array('secret' => $StrSecretKey, 'response' => $_POST['Response']);
$ch = curl_init($StrUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$Response = curl_exec($ch);
curl_close($ch);
$Robot = json_decode($Response);
$data = 0;
if(isset($Robot->success) AND $Robot->success==true){
//CODE
}
Try this. It was originally designed for an AJAX call, however if you change the $_POST['Response'] to the name of the response variable then it should work, hopefully.

Related

file_get_content with no return

I'm trying to implement reCAPTCHA in my website, everything seems working fine, except the return from file_get_contents().
Here is my code:
if ($_REQUEST["send"] == 1){
// access
$secretKey = 'my_key';
$captcha = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
echo ($responseKeys);exit;
if(intval($responseKeys["success"]) !== 1) {
$message = 'Invalid reCAPTCHA';
} else {
$msg = 'content';
send_mail('send_to',"Subject",$msg);
header("location:index.php?send=1");exit;
}
}
My variable response is returning empty.
I tried to open https://www.google.com/recaptcha/api/siteverify? inserting manually the variables and it seems to work fine.
Am I forgeting something?
Thanks
Their API waiting for a POST request. Your code send GET request.
See answer here How to post data in PHP using file_get_contents?
My wrappers were disabled, reason why I couldn't reach the URL and get the return.
As I don't have access to php.ini the workaround was send the request with curl, here is the code:
$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$response = '';
} else {
curl_close($ch);
}
if (!is_string($response) || !strlen($response)) {
echo "Failed to get contents.";
$contents = '';
}
$responseKeys = json_decode($response,true);

FB messenger Bot not getting postback payloads

I am developing a facebook chatbot. I am facing a issue which I cannot solve. I am developing this in laravel. Here I cannot get the postback payload. here is my code
public function index(Request $request) {
if ($request->hub_verify_token === $this->verifyToken) {
echo $request->hub_challenge;
exit;
}
$input = json_decode(file_get_contents("php://input"), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$pageId = $input['entry'][0]['id'];
$accessToken = "access_token_that_got_from_fb";
//set Message
if($messageText != "") {
$answer = "Howdy! User";
}
if($messageText == "hello") {
$answer = 'Testing hello from bot';
}
foreach ($input['entry'][0]['messaging'] as $message) {
// When bot receive message from user
if (!empty($message['postback'])) {
$answer = 'got it tada';
}
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ] //json_encode($request->getContent())
];
$ch = curl_init('https://graph.facebook.com/v2.11/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
}
and my route is
Route::any('chatbot', 'ChatbotController#index');
here the message is working . but the postback payload request is not going to server. on the other hand using the same code in normal php file I am able to get postback paylod.
$hubVerifyToken = 'chatbot';
$accessToken = "access_token";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload'] : '' ;
//set Message
if($messageText == "hi") {
$answer = "Hello";
}
if($messageText == "hello") {
$answer = "Hello there, welcome to Chatleads";
}
if($postback) {
$answer = "postback TADA";
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.11/me/messages?access_token=$accessToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
How to solve this issue? can anyone show me a path?
Solved it by checking at laravel.log file.
$this->messageText = isset($this->input['entry'][0]['messaging'][0]['message']['text']) ? $this->input['entry'][0]['messaging'][0]['message']['text'] : '' ;
messageText should be like this. that's why its causing an error.

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

CloudSight Response Speed

I am experimenting with the Cloudsight API (Image recognition) and am seeing speed issues in response time. Their website advertises a 6-12 second response time, but I am routinely seeing responses taking up to and well over 20 seconds.
I would like to know if this is something on CloudSights end and that is just the response time, or if my code is causing these delays by being unoptimized or doing unnecessary work.
The following is my PHP code, it works fully, I can upload an image and read/display the response. My HTML code is a simple form that calls this PHP file.
<?php
$filename = $_FILES['fileToUpload']['name'];
$filedata = $_FILES['fileToUpload']['tmp_name'];
$filesize = $_FILES['fileToUpload']['size'];
$filetype = $_FILES['fileToUpload']['type'];
/*$tmpfile = $_FILES['fileToUpload']['tmp_name'];
$filename = basename($_FILES['fileToUpload']['name']);*/
$ch = curl_init("https://api.cloudsightapi.com/image_requests");
//$ch = curl_init("http://requestb.in/131zwlo1");
$postFields = [
"image_request[locale]" => "en-US",
"image_request[language]" => "en-US",
"image_request[image]" => "#$filedata".";filename=#$filename".";type=#$filetype"
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: CloudSight [key]", "Content-Type:multipart/form-data"));
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
$token = $result['token'];
$status = $result['status'];
sleep(3);
while($status == "not completed"){
sleep(1);
$cht = curl_init("http://api.cloudsightapi.com/image_responses/$token");
curl_setopt($cht, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cht, CURLOPT_HTTPHEADER, array("Authorization: CloudSight 6-j8FTD-h1ZtnlYgacdSEQ"));
$result = curl_exec($cht);
curl_close($cht);
$result = json_decode($result, true);
$status = $result['status'];
};
$name = $result['name'];
$reason = $result['reason'];
if($name != ""){
echo "\nName: $name";
};
if($reason != ""){
echo "\nReason Skipped: $reason";
};
?>

Accessing the PayPal ButtonManager API with PHP cURL

I'm trying to access the PayPal ButtonManager API. I'm getting error 10002, Authentication failed. I've double/triple checked all the credentials, and regenerated them too. I don't think the AppID should be necessary; it doesn't work with or without it anyway.
Exact error message text:
L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
//ButtonManager API
$ret = ch_post();
error_log($ret);
echo urldecode($ret);
function ch_post(){
//API Credentials
$accID = urlencode("accID");
$username = urlencode("username_api1.website");
$password = urlencode("password");
$signature = urlencode("signature");
$appID = urlencode("APP-ID");
$endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$certpath = "C:\certpath.pem";
$ch_headers = array(
"USER"=>$username,
"PWD"=>$password,
"SIGNATURE"=>$signature,
"APPID"=>$appID,
"VERSION"=>"51.0"
);
$ch_params = array(
"METHOD"=>urlencode("BMCreateButton"),
"OTHERPARAMS"=>urlencode("OTHER")
);
$ch = curl_init($endpoint);
curl_setopt($ch,CURLOPT_HTTPHEADER,http_build_query($ch_headers));
curl_setopt($ch,CURLOPT_CAINFO,$certpath);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($ch_params));
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_HEADER,TRUE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_SSLVERSION, 6);
$cexec = curl_exec($ch);
if(!$cexec) {
$response = "Failed: ".curl_error($ch)."(".curl_errno($ch).")";
curl_close($ch);
return $response;
}
curl_close($ch);
return $cexec;
}

Categories