Not able to get response in braintree checkout button - paypal

I am using braintree paypal checkout for the payment, payment is working fine, but not able to get response of that, here is my code for that
<script type="text/javascript">
var form = document.querySelector('#payment-form');
var client_token = "<?php echo \Braintree\ClientToken::generate(); ?>";
braintree.dropin.create({
authorization: client_token,
selector: '#bt-dropin',
paypal: {
flow: 'vault',
onSuccess: function (nonce, email) {
alert('sdsdsd123');
console.log(JSON.stringify(nonce));
},
},
}, function (createErr, instance) {
if (createErr) {
console.log('Error', createErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
instance.requestPaymentMethod(function (err, payload) {
if (err) {
console.log('Error', err);
return;
} else {
console.log("Payment confirmation");
console.log(payload);
}
// Add the nonce to the form and submit
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
});
},
);
var checkout = new Demo({
formID: 'payment-form'
});
But not able to get response in onsuccess function, can anyone please tell me how cani get this success response,

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
It looks like you may be confusing the implementation of PayPal within the Braintree JSv2 Drop-In UI with the Braintree JSv3 Drop-In UI. The onSuccess option is not supported in JSv3. The full list of configuration options of the PayPal object in JSv3 is available here.
Based on the code you provided, I would suggest removing your onSuccess callback function. You should still be able to achieve your desired result by placing that code in your instance.requestPaymentMethod callback function like so:
<script type="text/javascript">
var form = document.querySelector('#payment-form');
var client_token = "<?php echo \Braintree\ClientToken::generate(); ?>";
braintree.dropin.create({
authorization: client_token,
selector: '#bt-dropin',
paypal: {
flow: 'vault'
}
}, function (createErr, instance) {
if (createErr) {
console.log('Error', createErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
instance.requestPaymentMethod(function (err, payload) {
if (err) {
console.log('Error', err);
return;
}
console.log("Payment confirmation");
console.log(payload);
alert('sdsdsd123');
console.log(payload.nonce);
// Add the nonce to the form and submit
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
});
});
</script>

Related

REST Routes with mongoose and express

When I try to add a review to my product from the front-end I am getting a 404 error for PUT http://localhost:3000/products. But I am to add/update data using the following curl command using my routes:
curl --data "name=Product 1&description=Product 1 Description&shine=10&price=29.95&rarity=200&color=blue&faces=3" http://localhost:3000/products
My products router
// This handles retrieving of products
// Includes Express
var express = require('express');
// Initialize the router
var router = express.Router();
var moment = require('moment');
var _ = require('underscore');
var color = require('cli-color');
var mongoose = require('mongoose');
var Product = mongoose.model('Product');
var Review = mongoose.model('Review');
// Route middleware
router.use(function(req, res, next) {
console.log("Something is happening in products!!");
next();
});
// GET route for all Products
router.get('/', function (req, res, next) {
Product.find( function (err, products) {
if (err) {
return next(err);
}
res.json(products);
});
});
// POST route for adding a Product
router.post('/', function (req, res, next) {
var product = new Product (req.body);
product.save( function (err, post) {
if(err) {
return next(err);
}
res.json(product);
});
});
// Pre-loading product object
router.param('product', function (req, res, next, id) {
var query = Product.findById(id);
query.exec( function (err, product) {
if (err) {
return next(err);
}
if(!product) {
return next(new Error('can\'t find product'));
}
req.product = product;
return next();
})
});
// GET route for retrieving a single product
router.get('/:product', function (req, res) {
req.product.populate('reviews', function (err, product) {
if (err) {
return next(err);
}
res.json(req.product);
});
});
// POST route for creating a review
router.post('/:product:reviews', function (req, res, next) {
var review = new Review(req.body);
review.product = req.product;
review.save( function (err, review){
if (err) {
return next(err);
}
req.product.reviews.push(review);
req.product.save( function (err, review) {
if (err) {
return next(err);
}
res.json(review);
});
});
});
This code is taken from a tutorial on thinkster for [MEAN stackl2
Original Post
I am having trouble figuring out how to update an existing entry in my mongodb database using a service I defined with ngResource in my Angular app. So far I have been unable to create a function that will update the back-end after a user clicks my submit button. I have been looking around for a solution for about 2 days but so far have not found a solution. I know the solution is similar to how I delete users in My User's Controller, but nothing I have tried has worked.
My Product Service
angular.module('gemStoreApp.productService',['ngResource'])
.factory('productsService', function($resource) {
return $resource('/products/:id', {},{
'update': { method: 'PUT'}
});
});
My Product Detail
angular.module('gemStoreApp')
.controller("ReviewCtrl", ['$scope', '$resource', 'productsService', function ($scope, $resource, productsService) {
this.review = {};
this.addReview = function(product){
product.reviews.push(this.review);
productService.save({id: product._id}, function() {
// I have tried .update, .$update, and .save methods
});
this.review = {};
};
}]);
I have verified that the products.review variable contains the update. Here is a sample of my JSON output from my console before and after adding the review:
Before the review is added to the front end
{"_id":"product_id","name":"Product 1","description":"Product 1 Description",...,"reviews":[{}]}
After the review is added to the front end
{"_id":"product_id","name":"Product 1","description":"Product 1 Description",...,"reviews":[{"stars":4,"body":"An Awesome review!","author":"user#domain.com","createdOn":1436963056994}]}
And I know that my productsService.save() function is being called as well, as I can put a console log in and see it run when I view in the browser.
My User's Controller
angular.module('gemStoreApp')
.controller('UsersCtrl', ['$scope', '$http', 'usersService', function ($scope, $http, usersService) {
$scope.users = {};
$scope.users = usersService.query();
$scope.remove = function(id) {
var user = $scope.users[id];
usersService.remove({id: user._id}, function() {
$scope.users.splice(user, 1);
});
};
}]);
My full source code is available on my Github page. Any help will be greatly appreciated.
I actually put it into work in this plunker
Took the same factory :
app.factory('productsService', function($resource) {
return $resource('product/:id', {id:"#id"},{
'update': { method: 'PUT'}
});
});
here is my controller :
$scope.products = productsService.query();
$scope.saveProduct = function(product){
product.$update();
}
and how i pass the value in the HTML :
<div ng-repeat="product in products">
<input type="text" ng-model="product.text">
<button ng-click="saveProduct(product)">Update</button>
</div>
If you track the networks request in the javascript console you will see a request : PUT /product/id with the updated data.
Hope it helped. If you have anymore question fell free to ask.

JQuery form submit with function not working

I'm having an issue with the jquery function submit for a form :
$(document).ready(function () {
$('#message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_message_11').submit(function() {
alert("HELLO2");
});
return false;
}
});
});
<form id="edit_message_11" class="edit_message" method="post" action="/message/11" accept-charset="UTF-8">
<textarea id="message" class="form-control edit_message_form" name="message">
Hello
</textarea>
http://jsfiddle.net/978QC/
When I do the following for my form : $('#edit_message_11').submit(function() { ... }); it doesn't trigger the submit.
However, If I do $('#edit_message_11').submit(); it does trigger the submit.
The reason why I need to do $('#edit_message_11').submit(function() { ... }); is because I want to do an ajax submit.
Anyone has a clue?
Thanks!
I don't believe it will work the way you are trying to do it. When it's inside the submit function, the alert will never fire until it gets a response back from POST. Which means you need a response from your form processing script.
Your AJAX call doesn't need to be inside the submit function, it just needs to be inside the event.
$(document).ready(function () {
$('#selfie_message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_selfie_11').submit();
$.ajax({
type: "POST",
url: "/selfies/11",
data: $("#edit_selfie_11").serialize()
});
}
});
});
If you need something to happen on success, you would do it like this.
$(document).ready(function () {
$('#selfie_message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_selfie_11').submit();
$.ajax({
type: "POST",
url: "/selfies/11",
data: $("#edit_selfie_11").serialize(),
success: function(response){
//your response code here//
}
});
}
});
});

Page need to be refresh before Facebook Login works

I am facing this issue in my application where facebook login is used.
ISSUE
Users need to press F5/refresh the page before facebook login prompt comes up. otherwise it doesn't come up and nothing happens on button click.
Here is the button tag for Facebook Login, which calls "Login()" method {angularJS is used}.
<a href="#" class="btn btn-default btn-lg" ng-click="login()"
ng-disabled="loginStatus.status == 'connected'"> <i class="fa fa-facebook fa-fw"></i> <span
class="network-name">Login Using Facebook</span></a>
AngularJS Code which gets called:
app.controller('DemoCtrl', ['$scope', 'ezfb', '$window', 'PFactory', '$location', function ($scope, ezfb, $window, PFactory, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function () {
ezfb.login(function (res) {
/**
* no manual $scope.$apply, I got that handled
*/
if (res.authResponse) {
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes,user_status,user_about_me,user_birthday,user_hometown,user_location,user_relationships,user_relationship_details,user_work_history'});
$location.path('/view9');
};
$scope.logout = function () {
ezfb.logout(function () {
updateLoginStatus(updateApiMe);
});
};
$scope.share = function () {
ezfb.ui(
{
method: 'feed',
name: 'angular-easyfb API demo',
picture: 'http://plnkr.co/img/plunker.png',
link: 'http://plnkr.co/edit/qclqht?p=preview',
description: 'angular-easyfb is an AngularJS module wrapping Facebook SDK.' +
' Facebook integration in AngularJS made easy!' +
' Please try it and feel free to give feedbacks.'
},
null
);
};
var autoToJSON = ['loginStatus', 'apiMe'];
angular.forEach(autoToJSON, function (varName) {
$scope.$watch(varName, function (val) {
$scope[varName + 'JSON'] = JSON.stringify(val, null, 2);
}, true);
});
function updateLoginStatus(more) {
ezfb.getLoginStatus(function (res) {
$scope.loginStatus = res;
$scope.promotion = 'promotion';
(more || angular.noop)();
});
}
function updateApiMe() {
ezfb.api('/me', function (res) {
$scope.apiMe = res;
});
}
}]);
Please help resolving it!
Thanks in Advance
Add true parameter after getLoginStatus callback function to force refreshing cache.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
ezfb.getLoginStatus(function (res) {
$scope.loginStatus = res;
$scope.promotion = 'promotion';
(more || angular.noop)();
}, true);

facebook programmatically post on a facebook page with a big photo

I've created a fake facebook page (entertainment page).
On the left of the attached image, I made a first post manually (the one below with the
big photo), and one programmatically (the one above with the small photo).
The code I used for the small photo looks like this:
FB.api(
'https://graph.facebook.com/[myAppId]/feed',
'post',
{
message: 'this is a grumpy cat',
description: "This cat has been lost for decades now, please call at 654321486",
picture: "http://laughingsquid.com/wp-content/uploads/grumpy-cat.jpg"
},
function (response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'<a href=\"https://www.facebook.com/' + response.id + '\">' +
'Story created. ID is ' +
response.id + '</a>';
}
}
);
But I'm not happy with it:
the application I'm working on make a list of lost animals,
so it would be much greater with big photos.
I didn't see any example of how to do it on the facebook developer pages.
I believe this is possible, but I've not found it out yet.
Have you guys already gone through this problem before?
There are two things that you will need to do to achieve this. I'm not 100% sure if the JS-SDK will allow you to do the second step, but you can use a server side SDK if needed.
The application will need to request the manage_pages and publish_stream permission. Then make a call to /{user-id}/accounts which will return all pages the authorized user manages, and their respective page access tokens.
Store in a variable the page access token returned for the page you want to post to. Set the photo you want to upload as the source parameter (must be local to the server running the code) and make a POST request to /{page_id}/photos using the page access token (NOT the application access token!).
So it would be along the lines of:
FB.api('/{page_id}/photos', 'post', { source: 'path/to/image.jpg', access_token: {page_access_token}, message: 'hey heres a photo' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
I believe the application also needs to specify fileUpload as true when initializing.
I would be happy to share my PHP code to do this if it would be helpful to you.
Finally, I did it!
I'm posting the solution, thanks to cdbconcepts for pointing me in the right direction.
After reading the doc again:
https://developers.facebook.com/docs/reference/api/photo/
They say that:
"You can also publish a photo by providing a url param with the photo's URL."
The url doesn't have to be on the same server, as shown in the example below,
and it works with the js-sdk.
So here is the final code that works for me:
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
var appId = 'Replace with your appId';
window.fbAsyncInit = function () {
FB.init({
appId: appId,
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
var options = {
scope: 'manage_pages, publish_stream'
};
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login(function () {
}, options);
} else {
FB.login(function () {
}, options);
}
});
};
// Load the SDK asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
console.log('Good to see you, ' + response.name + '.');
});
}
function error(msg) {
document.getElementById('result').innerHTML = 'Error: ' + msg;
}
function postApi() {
var myPageID = '484364788345193';
var targetPageName = 'Entertainment page of ling';
var pathToImg = 'http://laughingsquid.com/wp-content/uploads/grumpy-cat.jpg';
var accessToken = null;
FB.api(
'https://graph.facebook.com/me/accounts',
function (response) {
if (!response || response.error) {
console.log(response);
error('Error occured');
} else {
console.log(response);
for (var i in response.data) {
if (targetPageName === response.data[i].name) {
accessToken = response.data[i].access_token;
}
}
if (accessToken) {
FB.api(
'https://graph.facebook.com/' + myPageID + '/photos',
'post',
{
url: pathToImg,
access_token: accessToken,
message: "Tadaam"
},
function (response) {
if (!response || response.error) {
console.log(response);
error('Error occured');
} else {
console.log(response);
alert("PostId: " + response.id);
}
}
);
}
else {
error("Page not found in the accounts: " + targetPageName);
}
}
}
);
}
function logout() {
FB.logout();
}
$(document).ready(function () {
$("#logout").click(function () {
logout();
});
$("#post1").click(function () {
postApi();
});
});
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked. -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
<button id="logout">Logout</button>
<button id="post1">post something</button>
<div id="result"></div>
</body>
</html>

How to catch a 401 (or other status error) in an angular service call?

Using $http I can catch errors like 401 easily:
$http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}).
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
if(status == 401)
{
alert('not auth.');
}
$scope.posts = {};
});
But how can I do something similar when using services instead. This is how my current service looks:
myModule.factory('Post', function($resource){
return $resource('http://localhost/Blog/posts/index.json', {}, {
index: {method:'GET', params:{}, isArray:true}
});
});
(Yes, I'm just learning angular).
SOLUTION (thanks to Nitish Kumar and all the contributors)
In the Post controller I was calling the service like this:
function PhoneListCtrl($scope, Post) {
$scope.posts = Post.query();
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];
As suggested by the selected answer, now I'm calling it like this and it works:
function PhoneListCtrl($scope, Post) {
Post.query({},
//When it works
function(data){
$scope.posts = data;
},
//When it fails
function(error){
alert(error.status);
});
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];
in controller call Post like .
Post.index({},
function success(data) {
$scope.posts = data;
},
function err(error) {
if(error.status == 401)
{
alert('not auth.');
}
$scope.posts = {};
}
);
Resources return promises just like http. Simply hook into the error resolution:
Post.get(...).then(function(){
//successful things happen here
}, function(){
//errorful things happen here
});
AngularJS Failed Resource GET
$http is a service just like $resource is a service.
myModule.factory('Post', function($resource){
return $http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'});
});
This will return the promise. You can also use a promise inside your factory and chain that so your factory (service) does all of the error handling for you.