I'm trying to implement Google ReCaptcha V2 in a PHP form.
Here is my code :
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'], false, stream_context_create($arrContextOptions));
$response = json_decode($response, true);
if($response["success"] === true)
{
echo "Logged In Successfully";
}
else
{
echo "You are a robot";
}
}
?>
When i submit my form, it always return
You are a robot
.
My public key is correct, and my private key too.
I don't know what i'm doing wrong ?
I'm working as localhost.
Thanks.
Just integrated 2 days ago the V2 recaptcha from Google
Try my code below, explicitly to see if is solving your problem:
I can see u do file_get_contents, and i think here is your issues, u have to make POST, please use my code below
if($_SERVER["REQUEST_METHOD"] === "POST"){
// prepare post variables
$post = [
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => 'is optional, but i pass it',
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$response = json_decode($response, true);
// check result
if(isset($response['success']) && $response['success'] == true){
echo "Logged In Successfully";
}else{
echo "You are a robot";
}
}
Related
i have created a form in codeigniter and given a google captcha v2, i have created the site key and secret key added it to config files, and also added the js and the recaptcha div including my site key. the following is my captcha function in controller:
public function validate_captcha() {
$recaptcha = trim($this->input->post('g-recaptcha-response'));
$userIp= $this->input->ip_address();
$secret='xxxxxxxxxxxx'; (i have given my scret key here)
$secretdata = array(
'secret' => "$secret",
'response' => "$recaptcha",
'remoteip' =>"$userIp"
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify);
$status= json_decode($response, true);
if(empty($status['success'])){
return FALSE;
}else{
return TRUE;
}
}
the following is my register form function in same controller:
public function ajaxRegAction() {
$this->load->library('session');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$this->load->library('form_validation');
$utype='W';
$dhamu = $this->validate_captcha();
$createddate = date('Y-m-d h:i:s');
$createdby = '0';
$mobile = $this->input->post('phone');
$form_data = array(
'type' => $utype,
'unique_id' => $this->mainModel->generateIndividualID(),
'phone_num' => $mobile,
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'created_by' => $createdby,
'created_date' => $createddate,
);
$name = $this->input->post('firstname')." ".$this->input->post('lastname');
$access_info = array('user_type'=>$utype);
$check = $this->mainModel->checkUserAvail($this->input->post('phone'),$this->input->post('email'));
$checkauser = $this->mainModel->checkAjaxUser($this->input->post('phone'),$this->input->post('email'));
if($check==0) {
if($dhamu==1){
$insert = $this->mainModel->ajaxRegInsertUser($form_data, $access_info,$this->input->post('password'));
$message="Dear ".$this->input->post('firstname').", You have successfully registered with Book The Party. Thank You for coming On-Board. Contact us at 9666888000 for any queries - Team BTP";
$email_message=$message;
$message=rawurlencode($message);
$this->mainModel->sendOtptoCustomer($mobile,$message);
$this->mainModel->sendmailtoCustomer($this->input->post('email'),$email_message);
echo "success";
}
else{ echo "Captcha Error";}
}
else{
echo "Registration Failed !";
}
even if i check the google recaptcha box and press register, the form is showing "Captcha Error", values are not being added to the database also. can anyone please tell me what could be wrong here, thanks in advance
Step 1:
Make sure you have added localhost in your domain in Google Captcha V2 dashboard.
Step 2:
I am modifying your function you can use it like this:
public function validate_captcha()
{
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
return TRUE;
} else {
return FALSE;
}
}
instead of CURL
Do let me know if this works
I had working code in my server, that verified in-app purchases.
There are already 2 days, that my verification started give me a bad response.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
Nothing changed on my side.
(P.S. I'm able to get an access token via refresh, so, I assume I have no problems with my credentials).
Here is the code, that worked OK before.
$product_sku = $_REQUEST['product_sku'];
$transaction_id = $_REQUEST['transaction_id'];
$transaction_time = $_REQUEST['transaction_time'];
$purchase_data = #$_REQUEST['purchase_data'];
$market = $_REQUEST['market'];
$verified = false;
$test_purchase = false;
if (isset($product_sku) && isset($transaction_id) && isset($transaction_time) && isset($market)) {
// If it's GOOGLE
if ($market == '2') {
// verifies if the IAB is correct
if (isset($purchase_data) && $purchase_data != "") {
// Getting necessary data for verification
$client_id = file_get_contents('google_play_developer_api_client_id');
$client_secret = file_get_contents('google_play_developer_api_client_secret');
$refresh_token = file_get_contents('google_play_developer_api_refresh_token');
$refresh_token_url = 'https://accounts.google.com/o/oauth2/token';
$verification_url = "https://www.googleapis.com/androidpublisher/v3/applications/mypackage/purchases/products/" . $product_sku . "/tokens/" . $purchase_data;
// Preparing for the REFRESH_TOKEN request. This need to be changed after Memcache enabling.
// Will be needed to store the ACCESS_TOKEN in the Memcache for the expiration time and after expiring get new ACCESS_TOKEN with REFRESH_TOKEN
// constructing the necessary data for Google authentication
$data_array = array(
"grant_type" => "refresh_token",
"client_id" => $client_id,
"client_secret" => $client_secret,
"refresh_token" => $refresh_token
);
// replacing '\/' with '/' as after json_encode() the '/' in the array values will be replaced with '\/'
$data_array = str_replace("\/", "/", json_encode($data_array));
// contracting Headers for the REFRESH_TOKEN request
$headers = array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
);
// making REFRESH_TOKEN request and getting the new ACCESS_TOKEN
$make_call = callAPI('POST', $refresh_token_url, $data_array, $headers);
$response = json_decode($make_call, true);
if (array_key_exists("access_token", $response)) {
$accessToken = $response["access_token"];
// preparing for the Verification request
// adding necessary headers
array_push($headers, "Authorization: OAuth " . $accessToken, "Accept: application/json");
// making Verification request and getting the receipt from Google
$make_call = callAPI('GET', $verification_url, false, $headers);
$receipt = json_decode($make_call, true);
if (array_key_exists("purchaseState", $receipt)) {
// checking for the test purchase or for the purchase made using promo code.
// if purchaseType exists in the receipt the it is test purchase or the purchase made using promo code
// purchaseType = 0 -> Test Purchase, purchaseType = 1 -> Purchase made using promo code
if (array_key_exists("purchaseType", $receipt)) {
$purchaseType = $receipt["purchaseType"];
$test_purchase = $purchaseType == 0;
}
// Getting the purchaseState from the receipt.
// purchaseState = 0 -> Successfull purchase, purchaseState = 0 -> Canceled purchase
$purchaseState = $receipt["purchaseState"];
// Getting Order Id from the receipt
$order_id = $receipt["orderId"];
// Getting Purchase Time from the receipt. Time in millis from the Unix Epoch
$purchaseTimeMillis = $receipt["purchaseTimeMillis"];
// Verifying the purchase
// Verification is failed for any of the following reasons
// 1. Test purchase or the purchase made using promo code
// 2. Canceled Purchase
// 3. If the order id from receipt and the transaction id from the mobile app are different
// 4. If the PurchaseTime from the receipt and the Transaction Time from the mobile are different
// If all conditions are true, the purchase is verified.
$verified = ($purchaseState == 0 && $order_id == $transaction_id && $purchaseTimeMillis == $transaction_time);
} elseif(!array_key_exists("error", $receipt)){
// Something went wrong, let's set the verified to true, so we don't know if it is cheating
$verified = true;
}
} else {
// Something went wrong, let's set the verified to true, so we don't know if it is cheat
$verified = true;
}
}
} else {
// Changed this, while adding verification for other platforms
$verified = true;
}
$verified = $verified ? 1 : 0;
$test_purchase = $test_purchase ? 1 : 0;
// Updating verified and test Purchase fields in the payment_transaction table
// The default value is 1, so no need for updating , if the payment is verified
if ($verified == 0 || $test_purchase == 1) {
dbQuery("UPDATE payment_transaction SET verified=$verified, test_purchase=$test_purchase WHERE user_id=$user_id AND txnid='$transaction_id'", $user_id);
}
$output['status'] = 'ok';
$output['verified'] = $verified;
$output['test_purchase'] = $test_purchase;
}
echo json_encode($output);
function callAPI($method, $url, $data = false, $headers = null)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "GET":
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
if ($headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if (! $result) {
die("Connection Failure");
}
curl_close($curl);
return $result;
}
?>
Any Ideas what may be the reason for the bad response?
I have tried to generate a new refresh token, but the result is the same. (
Ok. I found the problem. The PurchaseToken was incorrect in my case.
BTW, the Error Code 400 means that the authentication is ok , but some data is invalid. In my case, it was the PurchaseToken.
I have tried google captcha using PHP as following way
HTML
<div class="col-md-12">
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6Lf2yUUUAAksikja1XQNtIOqIDmtzb46uHGY-Wq_sl">
</div>
</div>
</div>
PHP
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$secret = '6Lf2yUAAHvAr2QoaNHYFDG945Z6Ai7EqTg6Y71';
//get verify response data
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret=&response=" . rawurlencode($_POST['g-recaptcha-response']) . "&remoteip=" . rawurlencode($_SERVER['REMOTE_ADDR']));
$responseData = json_decode($verifyResponse);
if($responseData->success){
} else {
echo 'Robot verification failed, please try again.';
}
}
This same code has worked in PHP 5.4 But Is not working on PHP 7.0 , i don't know how to fix it, any suggestion or solution please post
You can try in this way.
Hope it will help you.
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$privatekey = "XXXXXXXXXXXXXXXXXXXXXX";
$captcha = $_POST['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $privatekey,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
$ch = curl_init();
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
curl_close($ch);
$jsonResponse = json_decode($response);
if ($jsonResponse->success === true) {
}
else {
$errMsg = 'Robot verification failed, please try again.';
}
} else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
You will probably get timeout-or-duplicate issue if your captcha is validated twice. Save logs in a file in append mode and check if you are validating a Captcha twice.
For instance, check below:
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'])
file_put_contents( "logfile", $verifyResponse, FILE_APPEND );
Now, check the logfile created above and try to check if captcha is verified twice.
I have already tried below code,
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
You need to use the proper Tumblr endpoint:
http://www.tumblr.com/api/write
I'm pretty sure the others won't work.
Obviously make sure that your user and pass are correct, other than that, this looks fine - it's pretty much exactly what I'd write.
Could anyone help me figure out how to post to tumblr using php.
I tried googling for a library or a sample code but couldn't find one. all I can find is this here https://github.com/alexdunae/tumblr-php/blob/master/Tumblr.php and it doesnt seem to work also I looked and tried the code on v1 api at tumblr website that doesnt work either ....
function post($data){
if(function_exists("curl_version")){
$data["email"] = $this->email;
$data["password"] = $this->password;
$data["generator"] = $this->generator;
$request = http_build_query($data);
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c,CURLOPT_POST,true);
curl_setopt($c,CURLOPT_POSTFIELDS,$request);
curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
$return = curl_exec($c);
$status = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if($status == "201"){
return true;
}
elseif($status == "403"){
return false;
}
else{
return "error: $return";
}
}
else{
return "error: cURL not installed";
}
}
Thanks for the help
I just noticed that this is showing up as Featured for Tumblr and I want to say this: As of 2012, you should IGNORE the above answer by Tuga because it DOES NOT work with the newest Tumblr API.
What you need is TumblrOAuth which is built from OAuth Sandbox.
It is only setup to read and write Tumblr posts, so if you want to do more than that, you'll need to alter the code. I used it as my code base for Followr.
Stolen from http://www.tumblr.com/docs/en/api
// Authorization info
$tumblr_email = 'info#davidville.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'regular';
$post_title = 'The post title';
$post_body = 'This is the body of the post.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
?>
$conskey = "CONSUMER KEY";
$conssec = "CONSUMER SECRET";
$tumblr_blog = "myblog.tumblr.com";
$to_be_posted = "This is the text to be posted";
$oauth = new OAuth($conskey,$conssec);
$oauth->fetch("http://api.tumblr.com/v2/blog/".$tumblr_blog."/post", array('type'=>'text', 'body'=>$to_be_posted), OAUTH_HTTP_METHOD_POST);
$result = json_decode($oauth->getLastResponse());
if($result->meta->status == 200){
echo 'Success!';
}
This code will let you post to your tumblr blog using tumblr API.
I hope this code helps.
The api example provided by Tuga is working for me (on Wordpress)...so I think your problem lies elsewhere, and not with the example provided. I would also be very appreciative if you guys got a version 2 api working if you could post it.