file_get_contents() returning false for Google reCAPTCHA v3 - recaptcha

I have been trying to implement Google reCAPTCHA v3 by using the following PHP source code:
<script src="https://www.google.com/recaptcha/api.js?render=6Ldl-98fAAAAAKRPodblUlTcVgvrfWZ_8lODjmZA"></script>
<?php
if(isset($_POST) && isset($_POST["btnSubmit"]))
{
$secretKey = '6Ldl-98fAAAAAD3ekajHHVBi2X4fZTW37bI5IGUN';
$token = $_POST["g-token"];
$ip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = array('secret' => $secretKey, 'response' => $token, 'remoteip'=> $ip);
// use key 'http' even if you send the request to https://...
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data)
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if($response->success)
{
echo '<center><h1>Validation Success!</h1></center>';
}
else
{
echo '<center><h1>Captcha Validation Failed..!</h1></center>';
}
}
?>
The problem is that every time I run this and step through the code line by line, I notice that the file_get_contents() function is always returning false and is assigning false to the '$result' variable. Why is this?
$result = file_get_contents($url, false, $context);
I would appreciate any advice that I can get.

From docs: 'null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.'
Show us $response, so var_dump($response). In recaptcha v2 i had empty string or token lately. That's why I ask for response, json decode will decode if there is proper json value.
I'd bet you get empty result and json_decode fails.

Related

Transform CURL to Http facade laravel

I have this code :
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$curlHandle = curl_init('http://url.com');
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $httpParams);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curlHandle);
curl_close($curlHandle);
dump($curlResponse);die();
I have the response in $curlResponse with status = 200
But when I tried with Http from laravel :
$http = Http::asForm();
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response = $http->send('post', 'http://url.com', $httpParams)->body();
dump($response);
Response is empty : "". The status is 200. Can you help me please, why using Http facade I have empty response ? Thx in advance. Please help me !!!
You can write reusable method inside separate class
public function apiCall($url, $method = "get",$data=[])
{
$htppCall = Http::withHeaders([
'Content-Type' => 'application/json',
])->{$method}($url,$data);
if ($htppCall->status() == 401) {
//error handling
}
return $htppCall->object();
}
Then call like this
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response=$this->apiCall($url,'post',$httpParams);
dd($response);
Import right facade
use Illuminate\Support\Facades\Http;
checking what status code you got
$htppCall->status()
to get data as object
$htppCall->object()
To get data as array
$htppCall->json()
To check client errors
$htppCall->clientError()
to check server errors
$htppCall->serverError()
To Get the body of the response.
$htppCall->body()
If any issues let me know in comment

Guzzle POST request: required body when execute request

I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.

Redirect in Slim

I have an ajax request, but I need my response to redirect to a certain twig template. This is what I have:
$response = ['success'=>false];
return $this->view->render($resp, 'spotlight-results.twig',['data' => $response] );
The problem with this is I am receiving the page in the console, this is not replacing the page that makes the request. I don't know if I explained myself correctly...
I have found the answer:
$loader = new Twig_Loader_Filesystem('../templates/');
$twig = new Twig_Environment($loader);
$template = $twig->loadTemplate('spotlight-results.twig');
$message = ['success' => false];
$view = $template->render(['data' => $message]);
$response = ['success' => false, 'view' => $view];
This way I return my template, with my desired content, $message

laravel verify shopify webhook

How can I verify my shopify webhooks in laravel?
Currently I'm doing the following:
//Validate secret
if ( Request::header( 'X-Shopify-Hmac-Sha256' ) ) {
$hmac_header = Request::header( 'X-Shopify-Hmac-Sha256' );
$data = Request::json();
$calculated_hmac = base64_encode( hash_hmac( 'sha256', $data, Config::get( 'constants.SHOPIFY_APP_SECRET' ), true ) );
if ( $hmac_header != $calculated_hmac ) {
return Response::json( array(
'error' => true,
'message' => "invalid secret" ),
403 );
}
}else {
return Response::json( array(
'error' => true,
'message' => "no secret" ),
403 );
}
But it fails with the following message:
#0 [internal function]: Illuminate\Exception\Handler->handleError(2, 'hash_hmac() exp...', '/Users/JS/Sites...', 58, Array)
#1 /Users/JS/Sites/xxx/api/app/controllers/CustomerController.php(58): hash_hmac('sha256', Object(Symfony\Component\HttpFoundation\ParameterBag), 'xxxxxxxxxx...', true)
I suspect it has sth to do with the way I get the request data:
$data = Request::json();
Does anyone have a solution? Thx!
Follow the example given in the Shopify docs: https://docs.shopify.com/api/webhooks/using-webhooks#verify-webhook
Replace
$data = Request::json();
with
$data = file_get_contents('php://input');
You can still use Request::json() elsewhere to get a ParameterBag for processing data from the webhook.
Here's my handler, works good:
public function handle($request, Closure $next)
{
$data = file_get_contents('php://input');
$calculated_hmac = base64_encode(hash_hmac('sha256', $data, [SECRET], true));
if (!$hmac_header = $request->header('X-Shopify-Hmac-Sha256') or
$hmac_header != $calculated_hmac or $request->email == 'jon#doe.ca') {
return Response::json(['error' => true], 403);
}
return $next($request);
}
note that:
$request->email == 'jon#doe.ca' for case if there is not received test hooks for some reason
[SECRET] is the code from the store notifications settings under the webhook callback URL (All your webhooks will be signed with [SECRET] so you can verify their integrity.)

HybridAuth send tweet with image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

Resources