I have been working with the implementation of Braintree payment gateway and now i am stuck with its Paypal method. The issue is describe below.
I have integrated the necessary code for for this and when selection the Paypal method and trying to login to Paypal, it always shows the error like below screenshot.
[![error screen while login in to paypal][1]][1]
I think this is happening because of the client token is wrong. but i have creating the token using the php method: $clientToken = Braintree_ClientToken::generate().
(It will currently login when i give the demo client token provided by Braintree demo code).
Here below i mentioned my code . Please check and hope anyone can trigger the issue.
<?php
require_once '_environment.php';
function braintree_text_field($label, $name, $result) {
echo('<div>' . $label . '</div>');
$fieldValue = isset($result) ? $result->valueForHtmlField($name) : '';
echo('<div><input type="text" name="' . $name .'" value="' . $fieldValue . '" /></div>');
$errors = isset($result) ? $result->errors->onHtmlField($name) : array();
foreach($errors as $error) {
echo('<div style="color: red;">' . $error->message . '</div>');
}
echo("\n");
}
// CLIENT TOKEN
$clientToken = Braintree_ClientToken::generate();
if(isset($_POST['payment_method_nonce'])){
$nonce = $_POST['payment_method_nonce'];
$result = Braintree_Transaction::sale(array(
'amount' => '91.00',
'paymentMethodNonce' => $nonce
));
if ($result->success) {
echo($result->customer->id);
echo($result->customer->creditCards[0]->token);
echo 'success';
} else {
foreach($result->errors->deepAll() AS $error) {
echo($error->code . ": " . $error->message . "\n");
}
}
}
?>
<form id="checkout" method="post" action="">
<div id="payment-form"></div>
<input type="submit" value="Pay $10">
</form>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
var clientToken = '<?php echo trim($clientToken);?>';
braintree.setup(clientToken, "dropin", {
container: "payment-form"
});
</script>
To create a PayPal transaction, you will need a customer id, the following sample works for me.
index.php
<?php
require("config.php"); //config.php contains Braintree_Configuration object.
$aCustomerId = '39538986'; // can be generated from braintreegateway.com vault->New Customer
$clientToken = Braintree_ClientToken::generate(array(
"customerId" => $aCustomerId
));
;
?>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
var clientToken = "<?php echo $clientToken ?>";
braintree.setup(clientToken, "dropin", {
container: "payment-form"
});
</script>
<form>
<div id="paypal-container"></div>
</form>
<script type="text/javascript">
braintree.setup(clientToken, "paypal", {
container: "paypal-container",
onPaymentMethodReceived: function (obj) {
window.location.href = 'http://localhost/braintree/checkout_paypal.php?nounce='+obj.nonce;
}
});
</script>
checkout_paypal.php
<?php
require("config.php");
$nonce = $_GET["nounce"];
$result = Braintree_Transaction::sale(array(
'amount' => '100.00',
'paymentMethodNonce' => $nonce,
'options' => array(
'submitForSettlement' => True
)
));
?>
Related
I am working on a custom Joomla module that returns an LDAP directory with the ability to change sort options on the front end using AJAX.
The getAjax function returns the directory just fine if I call it as a string in the default.php template file (bypassing AJAX):
echo $directoryList;
The problem is when I try to return the variable "$content" through ajax, the directory does not show when changing the selector. However, in the helper.php if I change "return $content" to "return $sortOption", AJAX works and returns the selected option for the sort. So I know AJAX is working. Also note that if I change to "return $content.$sortOption", the select option variable is shown but no directory. I think it has something to do with the LDAP not loading properly through AJAX.
Mod_nu_directory.php
// no direct access
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once( dirname(__FILE__) . '/helper.php' );
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('change', '#sortDir select', function () {
var value = $('#sortDir option:selected').val(),
request = {
'option' : 'com_ajax',
'module' : 'nu_directory',
'data' : value,
'format' : 'raw'
};
$.ajax({
type : 'POST',
data : request,
success: function (response) {
$('.status').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
$dirDepts = $params->get('dirDepts', 'All');
$dirOptions = $params->get('dirOptions');
$directoryList = modNuDirectoryHelper::getAjax($dirDepts);
require( JModuleHelper::getLayoutPath('mod_nu_directory'));
helper.php
class modNuDirectoryHelper {
public static function getAjax($dirDepts) {
//get the sort variable from the select field using ajax:
$input = JFactory::getApplication()->input;
$sortOption = $input->get('data');
//Set our variables
$baseDN = 'CN=Users,DC=site,DC=local';
$adminDN = "admin";
$adminPswd = "P#55WorD";
$ldap_conn = ldap_connect('ldaps://ad.site.local');
$dirFilter = strtolower('(|(department=*' . implode('*)(department=*', $dirDepts) . '*))');
//if "All" categories are selected, dont add a filter, else add a directory filter
(strpos($dirFilter, 'all directory') !== false) ?
$filter = '(&(objectClass=user)(|(memberof=CN=Faculty,CN=Users,DC=site,DC=local)(memberof=CN=Staff,CN=Users,DC=site,DC=local)))' : $filter = '(&(objectClass=user)(|(memberof=CN=Faculty,CN=Users,DC=site,DC=local)(memberof=CN=Staff,CN=Users,DC=site,DC=local))' . $dirFilter . ')';
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldap_bind = ldap_bind($ldap_conn, $adminDN, $adminPswd);
if (!$ldap_bind) {
return 'Oh no! Unable to connect to the directory :(';
} else {
$attributes = array('displayname', 'mail', 'telephonenumber', 'title', 'department', 'physicalDelivery', 'OfficeName', 'samaccountname', 'wwwhomepage', 'sn', 'givenname');
$result = ldap_search($ldap_conn, $baseDN, $filter, $attributes);
//sort the entries by last name
ldap_sort($ldap_conn, $result, $sortOption);
$entries = ldap_get_entries($ldap_conn, $result);
// let's loop throught the directory
for ($i = 0; $i < $entries["count"]; $i++) {
// define the variables for each iteration within the loop
$userName = $entries[$i]['displayname'][0];
$userTitle = $entries[$i]['title'][0];
$userDept = $entries[$i]['department'][0];
$userPhone = '888-888-8888, ext. ' . $entries[$i]['telephonenumber'][0];
$userOffice = 'Office: ' . $entries[$i]['physicaldeliveryofficename'][0];
//person must have a name, title, and department
if ((!empty($userName)) || (!empty($userTitle)) || (!empty($userDept))) {
$content .= $userName . '<br />'
. $userTitle . '<br />'
. $userDept . '<br />'
. (!empty($userPhone) ? $userPhone : '') . '<br />'
. (!empty($userOffice) ? $userOffice : '') . '<br />'
. '<br />';
}
}
}
return $content;
}
}
default.php
<?php
// No direct access
defined('_JEXEC') or die;
?>
<p>Displaying the following departments:<br />
<?php
foreach ($dirDepts as $dirDept) {
echo '[' . $dirDept . '] ';
}
?>
</p>
<p class="dirOptions">Displaying the following Options:<br />
<?php
foreach ($dirOptions as $dirOption) {
echo '[' . $dirOption . '] ';
}
?>
</p>
<?php
if (in_array('showSort', $dirOptions)) {
?>
<form method="post" id="sortDir">
<select name="sortDir" >
<option value="displayname" selected="selected">First name</option>
<option value="sn">Last name</option>
<option value="department">Department</option>
</select>
</form>
<?php } ?>
<div class="status"></div>
The problem was the $entries array was not being treated as an actual array. I've tested this by substituting the $entry array with a static array and the AJAX callback behaved properly. I since removed the ajax functionality and just echoed the function and works fine. This is not solve why AJAX can't pull the array though.
the below function is my controller code which is called by an ajax request:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$this->load->model('Featured_candidate', 'featured', TRUE);
$result = $this->featured->get_featured_candidates_by_skills($skills);
if ($result) {
$str = "";
foreach ($result as $row) {
$str .= "Name: " . $row->candidate_name . "<br/>";
$str .= "Exp: " . $row->experience . "<br/>";
$str .= "Skills: " . $row->skills . "<hr/>";
}
$html = $str;
echo json_encode(array('html' => $html, 'success' => TRUE));
} else {
$html = 'No Candidates Found!';
echo json_encode(array('html' => $html, 'success' => FALSE));
}
}
my view code:
<script>
$(function() {
$("#featured_candidates").on("change paste keyup", function() {
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>mypage/search_featured_candidates/",
data: {skills: $(this).val()},
dataType: "json",
success: function(data) {
if (data.success === true) {
$("#featured").html(data.html);
} else {
$("#featured").html(data.html);
}
}
});
});
});
</script>
<div class="panel-body">
<div>
<input type="text" style="width: 100%"
name="featured_candidates" id="featured_candidates"
placeholder="keyword / skills" title="Featured Candidates"
/>
<br/><hr/>
</div>
<div id="featured">
<?php
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . "<br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
?>
</div>
</div>
now i am trying to display the result array using ajax like i have displayed in my view code using foreach. so to display it using ajax i have concatenated the array in my controller method in $str but it is not working while when i updated my controller method to this:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$html = $skills ;
echo json_encode(array('html' => $html, 'success' => TRUE));
}
it is working fine..any help or suggesttion would be a great help...thanks in advance..
You have a mistake here
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . <br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
You forgot the "
. $row->candidate_name . "<br/>";
// ^ You forgot the "
The formulation of your question makes it difficult to know where your problem really is. But from a quick look you normally have to set proper headers in order to output json formatted data with PHP.
Try adding this before you do your echo, maybe this solves your problem:
header('Content-Type: application/json');
I am using a plugin to hijack a form and post it via an ajax function within the plugin. I can post the form and get a result in the console but I am unable to get the form to post and work properly.
My current build is using:
Laravel - PHP framework
Instagram PHP class - Interacting with the instagram api with php
Ajax plugin - To post forms without page refresh.
Currently I have got this for the ajax code(plugin):
Link here
And in my functions.js file I have got this code to post the form:
$(document).ready(function() {
$('.forms').each(function() {
$(this).formSubmit({
// Shows the formData that will be submitted; return false
// to prevent the form from being submitted
before: function(formData) {
if( console ) {
console.log('`before` callback:');
console.log(formData);
}
},
// Shows the AJAX response when the form is accepted
success: function(data) {
if( console ) {
console.log('`success` callback:');
console.log(data);
}
},
// Shows the AJAX response when the form is rejected
error: function(data) {
if( console ) {
console.log('`error` callback:');
console.log(data);
}
},
// Shows the AJAX error if one occurs
ajaxError: function(textStatus, errorThrown) {
if( console ) {
console.log('`ajaxError` callback:');
console.log(textStatus);
console.log(errorThrown);
}
},
// These add and remove a custom class called 'whoops' to the
// parent element of all invalid fields
showInvalid: function() {
$(this).parent().addClass('whoops');
},
hideInvalid: function() {
$(this).parent().removeClass('whoops');
}
});
});
});
Below is the markup for the form that wraps around the image so you can send a like/unlike through the instagram api from the form submit.
try {
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
$liked_media = $current_user->getLikedMedia();
/* echo 'https://api.instagram.com/v1/media/'. $item->getId() .'/likes?access_token='.$token.''; */
if ( isset( $_POST['action'] ) ) {
echo '<br/>FORM IS SUBMITTED, INSPECT WHAT WAS SENT';
print_r($_POST);
$id = $_POST['id'];
switch( strtolower( $_POST['action'] ) ) {
case 'like':
$current_user->addLike( $id );
break;
case 'unlike':
$current_user->deleteLike( $id );
break;
}
}
} catch ( Exception $e ) {
// yes there is an error
$error = $e->getMessage();
}
echo '<section id="images">';
foreach ( $media as $item ) {
echo '<article class="instagram-image">';
echo '<form class="forms" action="'; echo URL::current(); echo '" method="post">';
$id = $item->getId();
echo '<a title="' . $item->getCaption() .'" class="fancybox" href="' . $item->link . '"><img alt="' . $item->getCaption() .'" src="' . $item->images->standard_resolution->url . '" /></a>';
echo '<div class="formSubmit-feedback"></div>';
echo '<img src="/public/img/377.gif" alt="loader"/>';
if ( $current_user->likes($item) ){
echo '<button class="ajax instabtn unlike icon-heart" type="submit" name="action" value="Unlike"></button>';
} else {
echo '<button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button>';
}
echo '<input type="hidden" name="id" value="'; echo $id; echo '">';
echo '<p>'; echo $item->likes->count; echo '</p>';
echo '</form>';
echo '</article>';
}
echo '</section>';
The errors I get when posting the form are below, it finds the right id of the object to post tobut it will not post to the server:
`before` callback: functions.js:51
Object {id: "509073517011482478_5670460"}
I know its close but I am unsure where to look with it.
This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 9 years ago.
I have a piece of ajax script that is trying to post a form for me. Currently without ajax the form will post properly and it will send the data. What I want is an ajax post so it does not refresh the page and it posts the data too. There are multiple forms on one page.
My js script looks like this:
function post_form(action)
{
var token = $('.forms').attr('id');
var itemId = $('.forms').find('input.id').val();
var instaUrl = 'https://api.instagram.com/v1/media/'+itemId+'/likes?access_token='+token+'';
console.log(token);
console.log(itemId);
console.log(instaUrl);
var dataString = token;
$.ajax({
type: "POST",
url: instaUrl,
data: dataString,
crossDomain: true,
dataType: 'jsonp',
beforeSend: function()
{
$("#loading").fadeIn("slow");
if ( action == "like" )
{
$("#open"+comment_id).hide();
$("#loading_like_or_unlike"+comment_id).html('<img src="loader.gif" align="absmiddle" alt="Loading...">');
}
else if ( action == "unlike" )
{
$("#close"+comment_id).hide();
$("#loading_like_or_unlike"+comment_id).html('<img src="loader.gif" align="absmiddle" alt="Loading...">');
}
else {}
},
success: function(response)
{
if ( action == "like" )
{
$("#close"+comment_id).show();
}
else if ( action == "unlike" )
{
$("#open"+comment_id).show();
}
else {}
$("#loading").fadeOut("slow");
}
});
event.preventDefault();
}
$(document).ready(function() {
$('button.like').each(function() {
$(this).on('click', function(){
post_form();
});
});
});
Now in my markup I have a form that has an id in a hidden input value. The form once posted looks for the id and uses a case switcher with a like ans unlike switch. It uses the instagram php library to connect and get the data for the images as you will be able to see:
try {
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
$liked_media = $current_user->getLikedMedia();
/* echo 'https://api.instagram.com/v1/media/'. $item->getId() .'/likes?access_token='.$token.''; */
if ( isset( $_POST['action'] ) ) {
echo '<br/>FORM IS SUBMITTED, INSPECT WHAT WAS SENT';
print_r($_POST);
$id = $_POST['id'];
switch( strtolower( $_POST['action'] ) ) {
case 'like':
$current_user->addLike( $id );
break;
case 'unlike':
$current_user->deleteLike( $id );
break;
}
}
} catch ( Exception $e ) {
// yes there is an error
$error = $e->getMessage();
}
// view rendering stuff
// display the error
if ( $error != '' )
{
echo "<h2>Error: ".$error."</h2>";
}
echo '<section id="images">';
foreach ( $media as $item ) {
echo '<article class="instagram-image">';
// define the form and set the action to POST to send the data to this script
echo '<form id="'. $token .'" class="forms" action="'; echo URL::current(); echo '" method="post">';
$id = $item->getId();
echo '<a title="' . $item->getCaption() .'" class="fancybox" href="' . $item->link . '"><img alt="' . $item->getCaption() .'" src="' . $item->images->standard_resolution->url . '" /></a>';
echo '<div class="formSubmit-feedback"></div>';
//echo '<img src="/public/img/377.gif" alt="loader"/>';
if ( $current_user->likes($item) ){
echo '<button class="ajax instabtn unlike icon-heart" type="submit" name="action" value="Unlike"></button>';
} else {
echo '<button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button>';
}
echo '<input class="id" type="hidden" name="id" value="'; echo $id; echo '">';
echo '<p>'; echo $item->likes->count; echo '</p>';
//echo '<p>'.$item->getId().'</p>';
//echo '<p>By: <em>' . $item->user->username . '</em> </p>';
//echo '<p>Date: ' . date('d M Y h:i:s', $item->created_time) . '</p>';
//echo '<p>$item->comments->count . ' comment(s). ' . $item->likes->count . ' likes. ';
echo '</form>';
echo '</article>';
}
echo '</section>';
The form works I know that for sure but I really need to know how I can get this to post to the right place and do the switch so it likes/unlikes the image.
Does anyone know a way around this at all?
Thanks
So the database changes happen properly but the page doesn't reflect the change properly?
I'm not sure if the ajax success has action in its scope...try echoing the action in the php script and using the ajax response var to control the images.
we have an iframe facebookapp which worked fine till yesterday. Although we didn't change anything our app suddenly stopped working.
We could identify users_isAppUser() as a problem. The method returns that the user has not added the app though he definitely has installed the app and is logged in. We could delete the try/catch part (see code below), so that the app does not get catched in a redirect loop, but the following methods do not work either:
$this->facebook->api_client->friends_get()
$this->facebook->api_client->friends_getAppUsers()
$this->facebook->api_client->call_method('facebook.users.hasAppPermission', array('ext_perm' => 'publish_stream'))
require_login() does work and we can get the facebook userid of the logged in user.
The weird thing is, that our app worked fine for a couple of weeks till yesterday.
Have there been any secret changes to the API in the last days? Or any other conclusions what the problem could be?
I would appreciate any tips. Thanks in advance!
$this->fbuserid = $this->facebook->require_login();
// check if user has added app, exception gets thrown if the cookie has an invalid session_key i.e. user is not logged in
try {
if(!$this->facebook->api_client->users_isAppUser()) {
$this->facebook->redirect($this->facebook->get_add_url());
}
} catch (exception $ex) {
// clear cookies for application and redirect to login prompt
$this->facebook->set_user(null, null);
$this->facebook->redirect($this->configArray['appcallbackurl']);
}
<?php
// this is sample code taken from the Facebook Developers Site.Thank you to Face book
define('YOUR_APP_ID', '');
define('YOUR_APP_SECRET', '');
function get_facebook_cookie($app_id, $app_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $app_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
echo "<pre/>";
/*print_r($_COOKIE);
print_r($cookie);*/
$user = json_decode(file_get_contents('https://graph.facebook.com/me?access_token=' . $cookie['access_token']));
$photo = json_decode(file_get_contents('https://graph.facebook.com/100000439661780/albums?access_token=' . $cookie['access_token']));
echo "<pre/>";
print_r($photo);
?>
<img src="https://graph.facebook.com/ureshpatel5/picture" height="200" width="200" />
<html>
<body>
<?php
$albums = $facebook->api('/me/albums');
print_r($albums);
foreach($albums['data'] as $album)
{
// get all photos for album
$photos = $facebook->api("/{189346844423303_46487}/photos");
foreach($photos['data'] as $photo)
{
echo "<img src='{$photo['source']}' />", "<br />";
}
}
?>
<?php if ($cookie) { ?>
Welcome <?= $user->name ?>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<?php
echo $photo->source;
?>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '<?= YOUR_APP_ID ?>', status: true,
cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
</script>
</body>
</html>