I am newbie to Perl. I am working on integration of Braintree Payment gateway to an existing project. I'm following guides given n Braintre, its so clear and simple but I can't get it done. I have downloaded the Sample project from Github through the link: https://github.com/braintree/braintree_perl_guide
I am getting server errors while executing the app.pl file,
Steps followed:
Created a Sandbox account, got the Merchant id, Public key, Private key and the Configuration code.
Installed necessary modules needed to run the Perl script
Edited the app.pl file given and given my Merchant id and the associated keys.
Edited the form.tt file and given the Configuration code.
In terminal executed the command Perl app.pl, while pressing enter I got,
Dancer 1.3124 server 79859 listening on locahost:3000
== Entering the development dance floor ...
From the browser connected to localhost:3000/ and have got the Braintree Credit Card Transaction Form.
Entered the details and clicked on submit button and suddenly got Error 500. "Unable to process your query".
How to resolve this please need your assistance.
My app.pl file
use strict;
use warnings;
use Dancer;
use Template;
use Net::Braintree;
my $config = Net::Braintree->configuration;
$config->environment("sandbox");
$config->merchant_id("wbjnmbzfnvs6zt56");
$config->public_key("smbbnwfhybb3h5ty");
$config->private_key("****");
get '/' => sub {
template 'form'
};
post '/create_transaction' => sub {
my $result = Net::Braintree::Transaction->sale({
amount => "1000.00",
credit_card => {
number => param("number"),
expiration_month => param("month"),
expiration_year => param("year"),
cvv => param("cvv")
},
options => {
submit_for_settlement => 1
}
});
my $success = $result->is_success ? "true" : "false";
if ($result->is_success) {
return "<h1>Success! Transaction ID: " . $result->transaction->id . "</h1>"
} else {
return "<h1>Error: " . $result->message . "</h1>"
}
};
Dancer->dance;
and my Form.tt file
<html>
<head>
</head>
<body>
<h1>Braintree Credit Card Transaction Form</h1>
<div>
<form action="/create_transaction" method="POST" id="braintree-payment-form">
<p>
<label>Card Number</label>
<input type="text" size="20" autocomplete="off" data-encrypted-name="number" />
</p>
<p>
<label>CVV</label>
<input type="text" size="4" autocomplete="off" data-encrypted-name="cvv" />
</p>
<p>
<label>Expiration (MM/YYYY)</label>
<input type="text" size="2" data-encrypted-name="month" /> / <input type="text" size="4" data-encrypted-name="year" />
</p>
<input type="submit" id="submit" />
</form>
</div>
<script type="text/javascript" src="https://js.braintreegateway.com/v1/braintree.js"></script>
<script type="text/javascript">
var braintree = Braintree.create('MIIBCgKCAQEA1E9xWJbLZeJVM9VuITkFTLbYhbxERQ64hKqDL495BTwJBJaTz+Y29U555ekRaAGeOzuRAP7wgsOhyKsvKn3w7i3JVakdPYJSLMKgjqrQOTxSxUaUn+qpb+etJiALC3lsckmh04Io/x8B16hZAKhjQTB1XUZtuEcT8Pe0ObPlnZpWPXayMGElyBQnS/AaLWE7VZiq7ezqiRl5atp7RatAUACvfTkpRdlBAw9XuaEpgKPLPWtj8CQCJk3LDYWjrLvwGKQ/LW/uPoBpfVmqbbSVe1sAaZcdMcPyqL0viYn3QSIkiLhz8SvCJExo4XaMBSGOENg2bCbBWNHSNiJzrdZA4wIDAQAB');
braintree.onSubmitEncryptForm('braintree-payment-form');
</script>
</body>
</html>
Per comments, the error was actually caused by a proxy issue. Bypassing the proxy resolved the problem.
Related
Hi I am trying to somehow create a custom payment gateway. The one I am using is integrated in Gravity Forms and I have created a new php gateway MeprTransactiumGateway.php to include this new custom gateway.
I am able to capture the payment but not assign the subscription to the member. The member is being registered in memberpress but with no Memberships.
This is the code I am editing:
public function display_payment_form($amount, $user, $product_id, $txn_id) {
$mepr_options = MeprOptions::fetch();
$prd = new MeprProduct($product_id);
$coupon = false;
$txn = new MeprTransaction($txn_id);
//Artifically set the price of the $prd in case a coupon was used
if($prd->price != $amount) {
$coupon = true;
$prd->price = $amount;
}
ob_start();
$invoice = MeprTransactionsHelper::get_invoice($txn);
//echo $invoice;
$email = MeprTransactionsHelper::get_email($txn);
echo do_shortcode("[gravityform id=\"4\" field_values=\"email=".$email."\" title=\"Subscription\" description=\"false\" ajax=\"true\"]");
/* ?>
<div class="mp_wrapper mp_payment_form_wrapper">
<form action="" method="post" id="payment-form" class="mepr-form" novalidate>
<input type="hidden" name="mepr_process_payment_form" value="Y" />
<input type="hidden" name="mepr_transaction_id" value="<?php echo $txn_id; ?>" />
<div class="mepr_spacer"> </div>
<input type="submit" class="mepr-submit" value="<?php _e('Submit', 'memberpress'); ?>" />
<img src="<?php echo admin_url('images/loading.gif'); ?>" alt="<?php _e('Loading...', 'memberpress'); ?>" style="display: none;" class="mepr-loading-gif" />
<?php MeprView::render('/shared/has_errors', get_defined_vars()); ?>
<noscript><p class="mepr_nojs"><?php _e('Javascript is disabled in your browser. You will not be able to complete your purchase until you either enable JavaScript in your browser, or switch to a browser that supports it.', 'memberpress'); ?></p></noscript>
</form>
</div>
<?php*/
}
The gravity form is being echoed using do_shortcode. The payment is going through. Then a success or fail message is displayed as confirmation. I would like that if a success message is received the membership is actually submitted (this was previously done in the html form code that is commented out)
Current version V2 reCaptcha returns a "POST" in CGI:params. Not exactly what the old V2 version did.
The up side is that any HTML form contents and the reCaptcha response come in at the same time. The down side is that the "g-recaptcha-response" value is a blob that requires local validation.
The "g-recaptcha-response" value looks something like this:
03AJzQf7OU1j33-wm7I73BItJg-l2COD-YwSjesvfej_5vy5c0r_LUhaDU1KsvU0BV0Rc-MHRbR4L17TNya1CqFtCJGulzvwTpKCfjwWcwqj2e3nFiqeropkXnYzwE78Eydr0jGi3OjZCKK71rmhOXZr0OA_nC8Cpd6aPaexqkrfLXdiXFPE7pQqc-qixYzVklb2MIuPyxw414kVbyHsbDr5p-pitK9cXvvPYK1Td7T_z6xnMUIuNN5zY3ArYzlAGexsSffucQRrzSKT_779In1QzwQppASux3-Z_xPLQgCLnRsJlwcby7gFFWXHSfAxV2ErpsiGWQcGa1
How can one decipher this response in Perl to be sure it is a genuine acknowledgement that the Turing test was solved correctly?
Do you know the module Captcha::reCAPTCHA::V2? I have succesfully used it and it is a great time saver. In plain CGI, the server side code that does the validation would look like:
my $rc = Captcha::reCAPTCHA::V2->new;
my $result = $rc->verify('<your secret key here>', param('g-recaptcha-response'), remote_host);
# Check the result
if( !$result->{success} ){
# The check failed, ignore the POST
next;
}
I assume that you have already created your reCAPTCHA keys, have your HTML form and an idea of how to create the rest of the server side code.
To help other people that may seek how to do this, this is a minimum form for the client side (this is based on bootstrap):
<form id="contact-form" method="post" action="contact">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="message">Comments</label>
<textarea id="message" type="text" name="message" class="form-control" placeholder="Your comments..." rows="4" required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div align="center">
<button
class="g-recaptcha"
data-sitekey="<your site key here>"
data-callback="onSubmit">
Enviar mensaje
</button>
</div>
</div>
</div>
</form>
<script>
function onSubmit(token) {
document.getElementById("contact-form").submit();
}
</script>
Then, on the server side you would need something like (this is based on FastCGI; for CGI you would not use the loop):
use CGI::Fast qw(:standard);
use Captcha::reCAPTCHA::V2;
...
while(my $query = new CGI::Fast) {
...
if( request_method eq 'POST' ) {
my $rc = Captcha::reCAPTCHA::V2->new;
my $result = $rc->verify('<your secret key here>', param('g-recaptcha-response'), remote_host);
# Check the result
if( !$result->{success} ){
# The check failed, ignore the POST
next;
}
# Do something with the form
}
...
}
We are new in Perl scripting and we wanted to pass through a .NET site authentication.
We have an existing code for authentication specific for Sharepoint sites, code snippet below:
my $ua = new LWP::UserAgent('keep_alive' => '1');
print "$url \n";
$ua->credentials("$uname", "$pwd");
my $response =$ua->get($url);
my $cde = $response->code();
We wanted to customize the code so that it will work specific for .NET sites authentication. We used WWW::Mechanize, see code snippet below:
my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech->get($url);
$mech->form_name('Login');
$mech->field("UserName", $username);
$mech->field("Password", $password);
$mech->click();
But when the program is run, an error is shown: "There is no form named 'Login' in sample.pl". Any thoughts on how to authenticate forms specific for .NET sites?
Adding: HTML form code snippet...
<div id="loginArea">
<div id="loginMessage" class="groupMargin">Sign in with your account</div>
<form method="post" id="Login" autocomplete="off" novalidate="novalidate" onkeypress="if (event && event.keyCode
== 13) Login.submitLoginRequest();" action="">
<div id="formsAuthenticationArea">
<div id="userNameArea">
<input id="userNameInput" name="UserName" type="email" value="" tabindex="1" class="text fullWidth" spellcheck="false" placeholder="Username" autocomplete="off">
</div>
<div id="passwordArea">
<input id="passwordInput" name="Password" type="password" tabindex="2" class="text fullWidth" placeholder="Password" autocomplete="off">
</div>
<div id="kmsiArea" style="display:none">
<input type="checkbox" name="Kmsi" id="kmsiInput" value="true" tabindex="3">
<label for="kmsiInput">Keep me signed in</label>
</div>
<div id="submissionArea" class="submitMargin">
<span id="submitButton" class="submit" tabindex="4" onkeypress="if (event && event.keyCode == 32) Login.submitLoginRequest();" onclick="return Login.submitLoginRequest();">Sign in</span>
</div>
</div>
</form>
</div>
Usually this code works for .NET sites:
$mech->submit_form(
with_fields => {
login => "somelogin",
pass => "somepass",
},
button => "submit_button_name",
);
But you have weird error message: you're selecting "Login" form but $mech searching for "loginForm"... Can you show actual form's HTML?
Also there is no need to do $mech->cookie_jar(...) because $mech do this by default.
UPDATE
Try this code (Login is id of your form but not the name):
$mech->submit_form(
with_fields => {
UserName => "somelogin",
Password => "somepass",
},
);
I have a contact form which is a template for pages on wordpress that I use if I need a contact form. All works fine but I want to add the capability of adding a file attachment so when the user fills in their name etc they can upload a photo and that photo will be sent to be me as an attachment.
I have a perfect working contact form and I only want to add that functionality to it. All my current code does all this it sends the name of the person their email address and their message to my email, all I'm missing is the attachment feature. I've been looking at alot of contact forms with this feature but to integrate that feature to my sendmail.php seems very hard as the coding style is completely different. Here is a demo of this in action. demo
This is my php file that has the form in it.
<?php get_header(); ?>
<script type="text/javascript">
$(document).ready(function(){
$('#contact').ajaxForm(function(data) {
if (data==1){
$('#success').fadeIn("slow");
$('#bademail').fadeOut("slow");
$('#badserver').fadeOut("slow");
$('#contact').resetForm();
}
else if (data==2){
$('#badserver').fadeIn("slow");
}
else if (data==3)
{
$('#bademail').fadeIn("slow");
}
});
});
</script>
<!-- begin colLeft -->
<div id="colLeft">
<!-- Begin .postBox -->
<div class="postBox">
<div class="postBoxTop"></div>
<div class="postBoxMid">
<div class="postBoxMidInner first clearfix">
<h1>Contact Us</h1>
<p><?php echo get_option('alltuts_contact_text')?></p>
<p id="success" class="successmsg" style="display:none;">Your email has been sent! Thank you!</p>
<p id="bademail" class="errormsg" style="display:none;">Please enter your name, a message and a valid email address.</p>
<p id="badserver" class="errormsg" style="display:none;">Your email failed. Try again later.</p>
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"></textarea><br />
<input type="submit" id="submitinput" name="submit" class="submit" value="SEND MESSAGE"/>
<input type="hidden" id="receiver" name="receiver" value="<?php echo strhex(get_option('alltuts_contact_email'))?>"/>
</form>
</div>
</div>
<div class="postBoxBottom"></div>
</div>
<!-- End .postBox -->
</div>
<!-- end colleft -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
and here is the file that handles the sending of the mail.
<?php
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
Thanks!
You can read this simple tutorial to know what needs to be done to add file upload support to your current form:
http://www.tizag.com/phpT/fileupload.php
Hope it helps!
EDITED
After the upload process, you can do like this:
if (file_exists($_FILES['uploaded']['tmp_name'])) {
$mail->AddAttachment($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);
}
What this does is to add an attachment to your email by calling the AddAttachment from PHPMailer, and using the file just uploaded from the TMP folder of your server... so no actual storage of the file is necessary.
You can use
http://wordpress.org/plugins/contact-form-7/
It has a option for Upload field as well as all validations, really easy to use.
You just need to enter shortcode and you can use the contact form anywhere you want.
I am running a Perl application named bitlfu.For login it is using something like Apache HTTP Basic Auth but not a form.I want to make form for the login with username and password field.
I have tried JavaScript and PHP with no results till now.
So I need help!
PS:
this kind of url works
http://user:password#host.com
I think a simple JavaScript like:
document.location='http://' + user + ':' + pass + '#mydomain.tld';
should do the work.
So basically, you have to create a form, with a user and pass field, then onsubmit, use the part of JavaScript given here:
<form method="post" onsubmit="javascript:document.location='http://' + $('login') + ':' + $('pass') + '#mydomain.tld';">
<input type="text" name="login" id="login" />
<input type="password" name="pass" id="pass" />
<input type="submit" value="ok"/>
</form>
where $() is a document.getElementById or jquery or so. I used the $() function to make the code shorter. Here is an implementation, which does not work on every browser. Again, look throw jQuery for cross browser solution.
function $(_id) { return document.getElementById(_id); }
Otherwise, you can use php and redirect the user with a header location.
php way:
<?php
if (isset($_POST['login']) && isset($_POST['password'])) { header('Location: ' . urlencode($_POST['login']) . ':' . urlencode($_POST['password']) . '#domain.tld'); }
else
{
?>
<form method="post" onsubmit="javascript:document.location='http://' + $('login') + ':' + $('pass') + '#mydomain.tld';">
<input type="text" name="login" id="login" />
<input type="password" name="pass" id="pass" />
<input type="submit" value="ok"/>
</form>
<?php
}
You can redirect the user to http://user:password#host.com with Perl, or using JavaScript. I don't know Perl so I'll show you the JS:
function submitted() {
document.location = "http://" + document.getElementById("username").value + ":" + document.getElementById("password").value + "#host.com";
}
<form onSubmit="submitted">...blablabla...</form>
This should work. The only problem is that this shows the password in the URL.
The awesome AJAX way using jQuery:
$.ajax({
'url': 'http://host.com/',
//'otherSettings': 'othervalues',
username: $("username").val(),
password: $("password").val()
},
sucess: function(result) {
alert('done');
}
});
The ultimate Perl way (I think)
$username = # somehow get username
$password = # somehow get password
use CGI;
my $query=new CGI;
print $query->redirect('http://host.com/');
The method of explicitly redirecting document.location with username#password in URL caused me some problems with Safari giving a phishing warning.
If I instead first make an AJAX request to a URL with basic auth headers added, and then redirect document.location without the username/pass in the URL then it worked better for me
Example
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('form').submit(function() {
$.ajax({
url: 'https://site/collaborators/',
username: $("#login").val(),
password: $("#pass").val()
}).done(function() {
$("#error_msg").html("");
document.location='https://site/collaborators/';
}).fail(function(result) {
console.error(result);
$("#error_msg").html("Error logging in: "+result.statusText);
});
return false;
});
});
</script>
<div id="error_msg" style="color: red"></div>
<form method="post">
Username:
<input type="text" name="login" id="login" />
Password:
<input type="password" name="pass" id="pass" />
<input type="submit" value="Submit"/>
</form>
Unfortunate caveat with Safari only, if you type your username and password incorrectly, then it makes another standard HTTP basic auth popup, but this is better than a big red "Phishing warning" that occurs when you make the document.location include username/pass
Chrome doesn't have duplicate popup if login credentials are incorrect though
This is a simple plug&play solution ;-). Will work for any domain (and on HTTPS too):
<script>
function submitAuthForm() {
var login = document.getElementById('login').value;
var pass = document.getElementById('pass').value;
location = location.href.replace('://', '://' + encodeURIComponent(login) + ':' + encodeURIComponent(pass) + '#');
// might be required to reload on Firefox (FF shows confirmation dialog)
setTimeout(function(){
location.reload(true);
}, 5000);
}
</script>
<form method="get" onsubmit="submitAuthForm(); return false">
<input type="text" id="login" />
<input type="password" id="pass" />
<input type="submit" value="OK" />
</form>
You can drop this in your 401 error document.
Note that return false is required so that the page is not reloaded twice.