I'm trying to implement Google Invisible Recaptcha on a website online after the domain registration on google recaptcha site, I followed the documentation, but not works. When send the form, show the alert error:
Cannot contact reCAPTCHA. Check your connection and try again.
This is my code (only the interesting points), HTML/JS:
<script src='https://www.google.com/recaptcha/api.js?
onload=onloadCallback&render=explicit&hl=it' async defer></script>
</head>
<body>
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset>
<input name="email" type="text" id="email" required/>
<input type="submit" class="submit" id="submit" value="Contact!" />
</fieldset>
</form>
<script type="text/javascript">
var onSubmit = function(token) {
// ajax call
};
var onloadCallback = function() {
grecaptcha.render('submit', {
'sitekey' : 'PUBLIC_KEY',
'callback' : onSubmit
});
};
</script>
and the contact.php file:
class Captcha
{
private $key = 'PRIVATE_KEY';
public $goo;
public function verify()
{
$postData = http_build_query(
array(
'secret' => $this->key,
'response' => $this->goo,
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$options = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postData
)
);
$context = stream_context_create($options);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
return json_decode($response);
}
}
$captcha = new Captcha();
$captcha->goo = $_POST['g-recaptcha-response'];
$response = $captcha->verify();
if (!$response->success) {
// not works
}
else {
// works
}
I don't understand what is incorrect.
Thanks for help!
Related
I want to make an API request using a simple wp plugin I created by submitting a form and the form will submit to action.php
<?php
/** * Plugin Name: Taofeeq Wodpress Plugin demo
* Plugin URI: #
* Description: Display content using a shortcode to insert in a page or post
* Version: 0.1
* Text Domain: tbare-wordpress-plugin-demo
* Author: Taofeeq Tajudeen
* Author URI: #
*/
function tt_wordpress_plugin_demo($atts) {
?>
<form id="ct" method="POST">
<label for="source">Source:</label>
<input type="txt" name="source" required>
<label for="target">Target:</label>
<input type="text" name="target" id= "trg" required>
<input type="submit" value="Submit">
</form>
<?php
}
add_shortcode('tt-plugin-demo', 'tt_wordpress_plugin_demo');
action.php
`<?php
if (isset($_post['submit'])){
$source = $_post['source'];
$target = $_post['target'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.apyhub.com/data/convert/currency',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"source":$source,
"target":$target
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'apy-token: my_api_token'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
What I need assistance with is submitting the form without reloading the page where I insert the form shortcode. Also how to submit it to action.php since the file is in a plugin? Maybe you guys can assist me in a way that instead of submitting to action.php, it will submit to the same page where i will insert the action.php codes and action.php will no longer be needed.
I tried adding everything on the same page and after submission, the page will reload and return nothing.
I tried submitting it to action.php, it says page not found.
I tried submitting it to
action="<?php echo esc_attr(admin_url( 'admin-post.php' ) ); ?>"
but it brought me to the admin login page and after logging in it displays nothing.
Lastly, I don't know how to submit without reloading the page.
I want to store more customer information from my Paystack form such as first name, last name and shipping address, but only email and amount is stored. I discovered this can be done using metadata but I really don't know how to go about it. I'd be glad if anyone can help.
The HTML payment form
<form class="container" id="paymentForm">
<h3>Please fill the form below</h3>
<div class="form-group">
<label for="first_name">First Name</label>
<input class="form-control" type="text" id="first-name" required />
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input class="form-control" type="text" id="last-name" required />
</div>
<input type="text" class="amount" id="amount" value="" hidden>
<div class="form-group">
<label for="email">Email Address</label>
<input class="form-control" type="email" id="email-address" required />
</div>
<div class="form-group">
<label for="address">Shipping Address</label>
<input class="form-control" type="text" id="shipping-address" required />
</div>
<div class="form-submit">
<button type="submit" class="btn btn-primary btn-lg" onclick="payWithPaystack()"> Pay </button>
</div>
</form>
Here's Paystack Js code
const paymentForm = document.getElementById('paymentForm');
paymentForm.addEventListener("submit", payWithPaystack, false);
function payWithPaystack(e) {
e.preventDefault();
let handler = PaystackPop.setup({
key: 'pk_test_xxxxxxxxxx', // Replace with your public key
email: document.getElementById("email-address").value,
amount: document.getElementById("amount").value * 100,
//these three values (first_name, last_name and address) aren't retrieved
first_name: document.getElementById("first-name").value,
last_name: document.getElementById("last-name").value,
address: document.getElementById("shipping-address").value,
ref: 'CLE-BPS' + Math.floor((Math.random() * 1000000000) + 1), // generates a pseudo-unique reference. Please replace with a reference you generated. Or remove the line entirely so our API will generate one for you
// label: "Optional string that replaces customer email"
onClose: function() {
window.location = "https://my-url/?transaction=cancelled";
alert('Transaction cancelled.');
},
callback: function(response) {
let message = 'Payment complete! Reference: ' + response.reference;
alert(message);
window.location = "https://my-url/verify_transaction.php?reference=" + response.reference;
}
});
handler.openIframe();
}
verify_transaction.php
<?php
$ref = $_GET['reference'];
if ($ref == "") {
header("Location: javascript://history.go(-1)");
exit();
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($ref),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer SECRET_KEY",
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
$result = json_decode($response);
}
if ($result->data->status == 'success') {
$status = $result->data->status;
$reference = $result->data->reference;
$amount = $result->data->amount;
$l_name = $result->data->customer->last_name;
$f_name = $result->data->customer->first_name;
$fullname = $f_name . " " . $l_name;
$customer_email = $result->data->customer->email;
$shipping_address = $result->data->customer->address;
$customer_id = $result->data->customer->id;
$date = date('d-m-Y H:i:s');
include "config.php";
$stmt = $link->prepare("INSERT INTO transactions (status, reference, fullname, amount, customer_email, shipping_address, customer_id, date_purchased) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssss", $status, $reference, $fullname, $amount, $customer_email, $shipping_address, $customer_id, $date);
$stmt->execute();
if (!$stmt) {
echo "Oops...Something went wrong";
} else {
header("Location: https://my-url/success.php?status=success");
exit();
}
$stmt->close();
$link->close();
} else {
header("Location: error.php");
exit();
}
modify your paystack js code to look like this:
metadata:{
custom_field:[
{
first_name: document.getElementById("first-name").value,
last_name: document.getElementById("last-name").value,
address: document.getElementById("shipping-address").value,
}
]
}
so from the code above, I am creating a property, metadata and value is an object, and inside of the object, I am creating another property, custom_field and the value is an array. Place the additional fields you want to add in an object and place it inside of the custom_field property defined. You can place an many object as you want inside the custom_field array defined.
modify your verify_transaction.php to get the values;
After $result = json_decode($response);
$first_name = $result->data->metadata->custom_field[0]->first_name,
$last_name = $result->data->metadata->custom_field[0]->last_name,
$address = $result->data->metadata->custom_field[0]->address,
However, you can echo $response to see where the defined metadata is.
I am making a newsletter integration with external api , and it works fine but on submit my entire page redirects to admin post php , i have tried to use it without action and adding ajax script to footer but don't exactly know how to use my wp_remote method to send data without refreshing or redirecting my page
<?php
namespace SalesManago;
if (!defined('ABSPATH')) {
die;
}
/**
* Class ZH_SalesmanagoNewsletter
*/
class ZH_SalesmanagoNewsletter extends ZH_Salesmanago {
public function __construct() {
add_shortcode( 'sm_newsletter', array($this, 'newsletter_form' ));
add_action('admin_post_nopriv_newsletter', array($this, 'saveDataNewsletter'));
add_action('admin_post_newsletter', array($this, 'saveDataNewsletter'));
}
public function newsletter_form() {
return "
<div style='height: 300px; display: block; position: relative'></div>
<form id='ajax-newsletter-form' action='". esc_url( admin_url('admin-post.php') ) . "' method='post'>
<label for='email'>Email</label>
<input type='email' name='email' id='email' required>
<input type='hidden' name='action' value='newsletter'>
<input type='submit' name='sm-submit' value='>'>
</form>";
}
public function prepareDefaultNewsletterData()
{
$clientId = SALESMANAGO_CLIENTID;
$apiKey = SALESMANAGO_APIKEY;
$apiSecret = SALESMANAGO_APISECRET;
$data = [
'clientId' => $clientId,
'apiKey' => $apiKey,
'requestTime' => time(),
'sha' => sha1($apiKey . $clientId . $apiSecret),
];
return $data;
}
public function parseNewsletterData(){
$email = $_POST['email'];
$set[0]['contact'] = array(
'email' => $email,
);
return $set;
}
public function saveDataNewsletter(){
if (isset($_POST['sm-submit'])) {
$set = $this->parseNewsletterData();
$params = array(
"upsertDetails" => $set,
"owner" => SALESMANAGO_OWNER,
);
$data = array_merge($this->prepareDefaultSalesData(), $params);
$headers = [
'Content-Type' => 'application/json'
];
$result = wp_remote_post( SALESMANAGO_ENDPOINT .'/api/contact/batchupsertv2',
array(
'method' => 'POST',
'headers' => $headers,
'sslverify' => false,
'body' => json_encode($data)
)
);
}
}
}
So I want my users to be able to create a post in the frontend and upload an image with a form I've created.
When the image is uploaded I want to update an ACF-field with the uploaded image.
I've seen some posts on this but none of them are explained any good.
I want to use Ajax and I want to use axios, so please no jQuery. I also use Qs.
The image itself is never uploaded but the file name is inserted in the media library.
Thank you!
HTML
<form enctype="multipart/form-data" method="post" id="register-store-form">
<fieldset class="store-images mb-3">
<label for="store-images">Add images</label>
<input type="file" id="store_images" name="store_images" accept="image/png, image/jpeg">
</fieldset>
<button class="btn btn-primary" id="update-store">Save store</button>
</form>
JS
const Qs = require('qs');
const axios = require('axios');
const saveStoreBtn = document.querySelector('#update-store');
const addStore = document.querySelector('#add-one-more-store');
function saveStore(e) {
const storeName = document.querySelector('#store-name');
const storeImages = document.querySelector('#store_images');
const storeImageFile = storeImages.files[0];
const ajaxData = {
action : 'create_store',
security : shkGlobal.addStore,
name : storeName.value,
image_name : storeImageFile.name,
image_type : storeImageFile.type,
description : storeDescription.value
};
axios.post(shkGlobal.adminUrl, Qs.stringify(ajaxData))
.then(function(response) {
saveStoreBtn.innerHTML = "Thank you";
})
.catch(err => console.log('Not working', err));
};
updateStoreBtn.addEventListener('click', saveStore);
PHP
function create_store() {
check_ajax_referer('add_store', 'security');
$name_value = $_POST['name'];
$image_name = $_POST['image_name'];
$image_type = $_POST['image_type'];
$post_data = array(
'post_type' => 'store',
'post_title' => htmlentities($name_value),
'post_content' => $_POST['description'],
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_data );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES[$image_name];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'].'/'.$image_name,
'post_mime_type' => $image_type,
'post_title' => $image_name,
'post_content' => 'File '.$image_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('field_602019eba7767', $attach_id, $post_id);
}
echo json_decode($response);
exit;
}
add_action('wp_ajax_create_store', 'create_store');
add_action('wp_ajax_nopriv_create_store', 'create_store');
There are two problems in your case, first one that you are uploading multiple files, so structure of $_FILES will be different. Second one is that you specified store_images instead store_images[] for multiple file upload.
So in html change <input type="file" name="store_images" multiple> to <input type="file" name="store_images[]" multiple>
And in php, change your code accordingly to example below.
$files = $_FILES['store_images];
foreach ($files as $key => $value) {
if ($files['name']) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
wp_handle_upload($file);
}
}
}
I've been trying to figure this out for days with no luck.
I'm trying to implement Stripe Payments Checkout into my website. The payment amount is on the payments page as a JS variable. I was able to get Basic Checkout working, but apparently that can't use a custom amount, or send any data to the PHP processing page (email, and some order attributes). I've been trying to use the Custom Checkout but I can't figure it out. Any help?
So far I have this in config.php:
<?php
require_once('vendor/autoload.php');
$stripe = array(
"secret_key" => "MY SECRET KEY IS HERE",
"publishable_key" => "MY PUBLISHED KEY IS HERE"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
and this is in a file called process.php:
<?php
require_once('./config.php');
$token = $_POST['stripeToken'];
$input = $_POST["totalprice"];
$customer = \Stripe\Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $input,
'currency' => 'usd'
));
echo $input;
?>
And in the initial PHP file I have:
<?php require_once('./config.php'); ?>
<form action="process.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="MY PUBLIC TEST KEY IS HERE"
data-amount= amt * 100
data-name="Test Name"
data-description="Widget"
data-image="/img/logo.jpg"
data-locale="auto"
>
<form type=hidden name="totalprice" value=amt*100 action="process.php" method="POST">
</script>
</form>
With that said though, I've had a bunch of other code I've tried before that hasn't worked, so this current code probably should be scrapped. I'd really appreciate any help I can get!
Well, following is the sample code of Custom Integration.
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Stripe.com',
description: '2 widgets',
zipCode: true,
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
The source code is given on this page
So is that what you are looking for?