I am trying to process a Stripe charge in Angular using the Angular Payments module. I am able to get the token from Stripe, but receive the following error on the client side when I attempt to submit the token to my Express server:
ReferenceError: token is not defined
Any thoughts on how to resolve this?
Here's the relevant code:
Controller:
myApp.controller('PaymentFormCtrl',
function($scope){
$scope.handleStripe = function(status, response){
console.log('response', status, response);
if(response.error) {
console.log('error');// there was an error. Fix it.
} else {
console.log('no error');
token = response.id;
return $http.post('http://localhost:8080/api/payments', payment);
}
};
});
HTML for form:
<form stripe-form="handleStripe" name="myForm">
<div class="span3">
<label for="">Card number</label>
<input type="text" class="input-block-level" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="myForm.number.$card.type"/>
</div>
<div class="span1">
<label for="">Expiry</label>
<input type="text" class="input-block-level" ng-model="expiry" payments-validate="expiry" payments-format="expiry" />
</div>
<div class="span3">
<label for="">Name on card </label>
<input type="text" class="input-block-level">
</div>
<div class="span1">
<label for="">CVC</label>
<input type="text" class="input-block-level" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type"/>
</div>
<div class="span4">
<button type="submit" class="btn btn-primary btn-large">Submit</button>
</div>
</form>
Server Javascript:
apiRouter.route('/payments')
.post(function(req, res) {
var stripeToken = request.body.stripeToken;
var charge = stripe.charges.create({
amount: 1000,
currency: "usd",
source: stripeToken,
description: "payinguser#example.com"
}, function (err, charge) {
if (err && err.type === 'StripeCardError') {
}
});
});
One thing to fix for sure is that in the server side your request is 'req' yet you are trying to get the token from
request.body.stripeToken,
should be
req.body.stripeToken
Related
I am Getting null value in action method when i am pass data from angular js to action method. data is coming up to $scope.custmodel and i debug and see it hit to the AddCutomer method but data is null. can anyone help me to fix this issue
Admin.js code
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope,AdminService) {
$scope.Action = 'Add';
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (data) {
if (data != null) {
alert('Insert successfully');
} else {
alert('error in inerting data');
}
});
}
})
.factory("AdminService", function ($http) {
var fact = {};
fact.saveCustomerDdetails = function (d) {
return $http({
url: '/Admin/AddCutomer',
method: 'POST',
data: JSON.stringify(d),
headers: { 'content-type': 'application/json' }
});
};
return fact;
});
ASP MVC Method
[HttpPost]
public JsonResult AddCutomer(Customer customer) {
te.Customers.Add(customer);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
html code
<form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customercode" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customername" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
add [FromBody] attribute to the controller as shown below
public JsonResult AddCutomer([FromBody] Customer customer)
I have created a simple login and signup using MEAN stack languages. I have a profile page where user can edit his info like name, address, etc. I am able to store and retrieve input type "text" fields. How can i add image upload feature and retrieve uploaded images? Im new to mean stack so can anyone please help me? Thanks.
My server.js is this
require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
// use JWT auth to secure the api
app.use('/api', expressJwt({ secret: config.secret }).unless({ path: ['/api/users/authenticate', '/api/users/register'] }));
// routes
app.use('/login', require('./controllers/login.controller'));
app.use('/register', require('./controllers/register.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/api/users', require('./controllers/api/users.controller'));
// make '/app' default route
app.get('/', function (req, res) {
return res.redirect('/app');
});
// start server
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
HTML to save and view saved data looks like this
<h1>My Account</h1>
<div class="form-container">
<form method="post" >
<div class="form-group">
<label for="firstName">First name</label>
<input type="text" id="firstName" class="form-control" ng-model="vm.user.firstName" required />
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<input type="text" id="lastName" class="form-control" ng-model="vm.user.lastName" required />
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" class="form-control" ng-model="vm.user.username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" ng-model="vm.user.password" />
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" id="password" class="form-control" ng-model="vm.user.address" />
</div>
<div class="form-group">
<button class="btn btn-primary" ng-click="vm.saveUser()">Save</button>
<button class="btn btn-danger" ng-click="vm.deleteUser()">Delete</button>
</div>
</form>
</div>
<!-- View Data -->
<div class="col-md-12">
<h1>Hi {{vm.user.firstName}}!!</h1>
<p><strong>User Name :</strong> {{vm.user.username}} </p>
<p><strong>Full Name : </strong> {{vm.user.firstName}} {{ vm.user.lastName}}</p>
<p><strong> Your address is : </strong> {{vm.user.address}}</p>
</div>
and app.js looks like this
(function () {
'use strict';
angular
.module('app')
.controller('Account.IndexController', Controller);
function Controller($window, UserService, FlashService) {
var vm = this;
vm.user = null;
vm.saveUser = saveUser;
vm.deleteUser = deleteUser;
initController();
function initController() {
// get current user
UserService.GetCurrent().then(function (user) {
vm.user = user;
});
}
function saveUser() {
UserService.Update(vm.user)
.then(function () {
FlashService.Success('User updated');
})
.catch(function (error) {
FlashService.Error(error);
});
}
function deleteUser() {
UserService.Delete(vm.user._id)
.then(function () {
// log user out
$window.location = '/login';
})
.catch(function (error) {
FlashService.Error(error);
});
}
}
})();
and user.service.js which is used to update data to db is
function updateUser() {
// fields to update
var set = {
firstName: userParam.firstName,
lastName: userParam.lastName,
username: userParam.username,
address: userParam.address,
};
// update password if it was entered
if (userParam.password) {
set.hash = bcrypt.hashSync(userParam.password, 10);
}
db.users.update(
{ _id: mongo.helper.toObjectID(_id) },
{ $set: set },
function (err, doc) {
if (err) deferred.reject(err.name + ': ' + err.message);
deferred.resolve();
});
}
To build the image upload feature, You need to add functionality to both the frontend and backend.
You need to have a custom image upload directive or component in the angularjs and Some kind of upload handler package in the Express Server as well.
Keeping all this in mind, Google will surely lead you to best package available for you.
One code sample can be found here : https://gist.github.com/keithics/bf0e13feaee5631fa936b7b203029cd4
Other: https://github.com/nervgh/angular-file-upload
There are huge number of libraries available for the same.
I have created a form in a modal which allows someone to enter in plan details. I have then created the scope form in ng-model attribute as you can see below...
<form>
<div class="form-group">
<label>{{plans.title}}</label>
<input type="text" name="title" ng-model="plans.title" class="form-control" placeholder="Enter Title" required />
</div>
<div class="form-group">
<label>{{plans.overview}}</label>
<textarea name="overview" ng-model="plans.overview" class="form-control" placeholder="Overview/Purpose" required />
</div>
<div class="form-group">
<label>{{plans.notes}}</label>
<textarea name="notes" ng-model="plans.notes" class="form-control" placeholder="Plan Notes" required />
</div>
<div class="form-group">
<label>{{plans.visualplan}}</label>
<div class="button" ngf-select ng-model="plans.visualplan" name="visualplan" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" >Upload Visual Plan</div>
</div>
<div class="form-group">
<button type="submit" ng-click="submit()" Value="Post">Post</button>
</div>
</form>
In my code I am then trying to pull the data from the form into my scope object for plans under title, overview, notes and visualplan. Then i have coded this to upload the data from the form into my firebase json. However upon submitting the details, the upload to json process works correctly, but it is uploading the default values for title, overview, notes and visualplan which i have initiatlly set in my dailyplans.js file. What i want to upload is the details which I have attached through ng-model instead of the initial set values. Can anyone spot what I am doing wrong?
Below is my js file.
$scope.submit = function() {
$scope.plans = {
title: 'title',
overview: 'overview',
notes: 'notes',
visualplan: 'visual plan'
}
if (authData) {
ref.child('teaching-plans').child('teaching-plans' + authData.uid).set($scope.plans).then(function(authdata) {
console.log('successful');
}).catch(function(error) {
console.log(error);
});
}
}
You are resetting the plans object when user clicks on submit. Ideally it should be outside of submit method.
This is how you should do it
$scope.plans = {
title: 'title',
overview: 'overview',
notes: 'notes',
visualplan: 'visual plan'
}
$scope.submit = function(plans) {
if (authData) {
ref.child('teaching-plans').child('teaching-plans' + authData.uid).set(plans).then(function(authdata) {
console.log('successful');
}).catch(function(error) {
console.log(error);
});
}
}
And also update the html as
<div class="form-group">
<button type="submit" ng-click="submit(plans)" Value="Post">Post</button>
</div>
Hope this helps.
Just don't overwrite your plans object:
$scope.submit = function() {
$scope.plans.title = 'title';
$scope.plans.overview = 'overview';
$scope.plans.notes = 'notes';
$scope.plans.visualplan = 'visual plan;
if (authData) {
ref.child('teaching-plans').child('teaching-plans' + authData.uid).set($scope.plans).then(function(authdata) {
console.log('successful');
}).catch(function(error) {
console.log(error);
});
}
}
This way angular can fire the listeners correctly.
login.controller
angular
.module('app.pages.auth.login')
.controller('LoginController', LoginController);
/** #ngInject */
function LoginController($http, $location)
{
var vm = this;
vm.submitPost = function(userData){
$http({
url: 'http://localhost:7200/api/pages/auth/login',
method: 'POST',
data: userData
}).then(function(res) {
if(res.data.success){
$location.path('/pages/profile');
console.log(res.data.message);
//vm.message=res.data.message;
} else {
//console.log(res.data.message);
//vm.message=res.data.message;
$location.path('/pages/auth/login');
}
}, function(error) {
alert('here');
});
};
}
api.js
router.get('/pages/auth/login', function(req, res) {
console.log(req.flash('loginMessage'));
res.render('auth/login/login.html', { message: req.flash('loginMessage') });
});
router.get('/pages/profile', isLoggedIn, function(req, res) {
return res.json({
success:true,
//message: 'Login Success',
})
res.render('profile/profile.html', {user:req.user });
});
I am not getting any response from router to controller. It shows the alert message 'here'. Is there any thing wrong done here? please help me to fix this.
login.html
<form name="loginForm">
<div class="alertmessage" >{{vm.message}}</div>
<md-input-container flex md-no-float>
<input ng-model="vm.form.username" placeholder="Username" translate
translate-attr-placeholder="LOGIN.USERNAME" name="username" required="true">
<div ng-messages="loginForm.username.$error" ng-show="loginForm.username.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<md-input-container flex md-no-float>
<input ng-model="vm.form.password" type="password" placeholder="Password" translate
translate-attr-placeholder="LOGIN.PASSWORD" name="password" required="true">
<div ng-messages="loginForm.password.$error" ng-show="loginForm.password.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<div class="remember-forgot-password" layout="row" layout-sm="column"
layout-align="space-between center">
<md-checkbox class="remember-me" ng-model="data.cb1" aria-label="Remember Me">
<span translate="LOGIN.REMEMBER_ME">Remember Me</span>
</md-checkbox>
<a ui-sref="app.pages_auth_forgot-password" class="forgot-password md-accent-color"
translate="LOGIN.FORGOT_PASSWORD">Forgot Password?</a>
</div>
<md-button class="md-raised md-accent" aria-label="LOG IN" translate="LOGIN.LOG_IN"
translate-attr-aria-label="LOGIN.LOG_IN"
ng-click="vm.submitPost(vm.form);">
LOG IN
</md-button>
</form>
Please verify what is the value of 'userData' coming from the front end/from where u r calling it. Seems there is an issue with that only!
If thats not the issue then please check the network in developer tools that why your service is failing?
To go to network(on chrome) click F12 >> Network.
Verify your service call and see whats the issue!
EDIT:
where is your 'headers' in service call? You intentionally din't add or you missed it?
This is one more image of network tabWhen i click after login it showed like this
Network tab image showing like this
I am using Firebase email authentication. It worked pretty well yesterday, but for some reason, it suddenly stopped working this morning, and I have not touched the authentication part in the code at all. I am wondering if there is any changes in Firebase that i am not aware? or I did something may affect it?
Here is the code in controller:
// Home controller
.controller('LoginCtrl', ['$scope', '$firebaseAuth', function($scope, $firebaseAuth) {
// Auth Logic will be here
var firebaseObj = new Firebase("https://xxxx/");
var loginObj = $firebaseAuth(firebaseObj);
$scope.user = {};
$scope.SignIn = function(e){
e.preventDefault(); //To prevent from refresh
var email = $scope.user.username + '#whateverdomain.com';
var password = $scope.user.password;
console.log('Authentication start inside SignIn:' + );
loginObj.$authWithPassword({
email: email,
password: password
})
.then(function(user) {
//Success callback
console.log('Authentication successful');
$location.path('/dashboard');
}, function(error) {
//Failure callback
console.log(error.code);
if(error.code === "INVALID_USER") {
console.log('INVALID_USER');
$scope.loginForm.username.$invalid = true;
}
if(error.code === "INVALID_PASSWORD") {
console.log('INVALID_Password');
$scope.loginForm.password.$invalid = true;
}
});
}
}]);
Here is the view:
<body ng-controller="LoginCtrl">
<div class="container-login">
<div style="padding-bottom:0px; ">
<h1> Login</h1>
</div>
<form class="form-signin" name="loginForm" style="color:#C3BCB6;">
<div class="form-group" ng-class="{'has-error':loginForm.username.$invalid}">
<label>Username</label>
<input ng-model="user.username" type="text" name="username" class="form-control" placeholder="Input your username" ng-minlength="5" ng-maxlength="12"></input>
</div>
<div class="form-group" ng-class="{ 'has-error' : loginForm.password.$invalid }">
<label>Password</label>
<input ng-model="user.password" type="password" name="password" class="form-control" placeholder="Password" ng-minlength="8"></input>
</div>
<button type="button" ng-click="SignIn($event)" ng-disabled="!user.username || !user.password" class="btn btn-lg btn-primary btn-block">Sign in</button>
</form>
</div>
When authentication success, the user is supposed to redirect to the dashboard, or when it failed, it will show error message in the console.
Currently, it only shows "Authentication starts", but no "Authentication success" or any error message, from error.code.
I even checked out previous git commit, the authentication still did not work. Any thoughts? thanks!