Stripe V3 Cardholder name on source card - javascript

I have MVC project and facing one issue with stripe flow. any help would be really appreciated.
Below is my flow.
I'm creating card token from UI using stripe js version v3. with this code, I'm able to retrieve both card and token perfectly from stripe.
stripe.createToken(card, { name: name }).then(function (result) {
if (result.error) {
// Inform the customer that there was an error.
} else {
// stripeTokenHandler will post the form to back end with token, here we are getting card with proper name,
// but we are just sending token to back end
stripeTokenHandler(result.token);
}
});
Then I use that token further to create a stripe source with C# back end code, for that I have used Stripe.net, Version=37.15.0.0m below is the code.
// creating a stripe customer, consider this is working fine
Stripe.Customer customer = GetCustomerService().Create(options, requestOptions);
// create the credit card source and attach it to the current StripeCustomerId
var options = new Stripe.SourceCreateOptions()
{
Type = "card",
Token = token,
};
var requestOptions = new Stripe.RequestOptions();
if (stripeAccountId.IsNotEmpty())
requestOptions.StripeAccount = stripeAccountId;
Stripe.Source source = null;
try
{
source = GetSourceService().Create(options, requestOptions);
}
catch (StripeException ex)
{
msgs.Add(ex.Message, MessageType.UserError, ex);
msgs.Add($"Payment source was not created", MessageType.UserError);
}
And this is how I'm retrieving stripe sources.
List<Stripe.Source>() sources = GetSourceService().List(customerId).ToList();
This all works fine, but the retrieved sources does not contains the name of card holder, which was there when we created and retrieved token. I tried to look at the documentation, but no luck.
I think it's issue in the flow, I might be missing some pieces but not sure what it is. Again, any help would be really appreciated. Thanks!

If you're building a net new project you should really look at using the newer Payment Methods / Payment Intents APIs instead of what you're doing here.
That said, you don't seem to be attaching the Token to the Customer, rather you seem to be creating a Source - which is different. If you do want to create the Source with a name, you'd want to provide that.

Related

Stripe Javascript library confirmCardPayment not returning

I'm attempting to use Stripe as a payment method, on an ASP.Net MVC project
We've gone the route of using stripe elements to define our own look and feel for the card details.
I've followed the tutorials, and have managed to get the card widgit displaying nicely.
Where it fails is on the submission.
I've hooked up the following JS to the button (taken straight from the guides)
var form = document.getElementById('payment-form');
var clientSecret = $("#authcode").val();
form.addEventListener('submit', function(ev) {
ev.preventDefault();
stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
billing_details: {
name: 'Jenny Rosen'
}
}
}).then(function(result) {
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
console.log(result.error.message);
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
// Show a success message to your customer
// There's a risk of the customer closing the window before callback
// execution. Set up a webhook or plugin to listen for the
// payment_intent.succeeded event that handles any business critical
// post-payment actions.
}
}
});
});
Now when I put a breakpoint on it does enter the stripe.confirmCardPayment function
However I never get a response. I've put a break point on the line if (result.error) { but it never fires. I've sat and left it for over two minutes.
No errors in the chrome console, and also no network traffic.
I am happy that the JS is all loaded correctly because if I hit submit again the Stripe JS lib correctly tells me I have an in-flight confirmCardPayment
Any suggestions are most appreciated.
Looks you are using jQuery at:
var clientSecret = $("#authcode").val();
You should wrap js with
$(document).ready(function(){
....
}):
Right, I've finally got it working.
Yes I believe with the answers given by Nolan / Raphael that it was indeed a caching issue!
However. Deleting the cache with CTRL+SHIFT+DEL had no effect.
Only way I could get the cache to clear was to physically alter the JS.
Thanks again to Nolan / Raphael for their suggestions :)

Why am I unable to send the charge to Stripe and my Strapi.js backend using a try/catch in my React frontend?

I am trying to send a charge to stripe. I have a charge set up in my Strapi.js backend as well as a new order being created. I have created a function in my react frontend to create an entry to my 'orders' content type in strapi but it seems as though nothing in the function's try/catch is working, it is not even logging an error.
I've attempted to make change some variables here and there, but im honestly a little overwhelmed because this is the first time im using these technologies and I am somewhat of a beginner. I was somewhat watching a video for guidance through some things but this is where I faced issues. I am bringing in the script tag in the index.html file as well. I am using strapi sdk.
Here is what the create Orders function on the strapi backend looks like(stripe is being brought in at top of page using secret key):
create: async (ctx) => {
const { address, city, products, amount, token } = ctx.request.body;
// Stripe Charge
const charge = await stripe.charges.create({
amount: amount * 100,
currency: 'usd',
description: `Order ${new Date(Date.now())}`,
source: token
});
const order = await strapi.services.orders.add({
address,
city,
products,
amount,
});
return order;
}
Here is my submit function in react frontend checkout.js file
handleOrder = async () => {
const { checkOutItems, city, address } = this.state;
let token;
const amount = calculateTotalAmount(checkOutItems);
// console.log('working')
try {
// create token
const response = await this.props.stripe.createToken();
token = response.token.id;
await strapi.createEntry('order', {
address,
city,
products: checkOutItems,
amount,
token
});
} catch (error) {
console.log(error)
}
}
Well I am expecting that when i fill out the form as well as the chain of '4242' for stripe card element on the page, the charge will be sent and i can go to my stripe dashboard and see the charge, and also be able to go to my strapi admin dashboard and go to orders and see a new order created.
As of now, none of this happens. I fill the information, click submit, the form resets and then nothing. No error is logged, no console.logs within the try catch will work.

Creating a user session - NODE js

I am new to node js & javascript in general. I have the below piece of code that will handle a login. I have a MYSQL database with a customer table. When the customer enters their username and password, it checks does it exist in the database. This part is working.
I now want to enhance this feature so that it will take the username and create some sort of a session variable, which can be used across the application. I am new to JS so I am not yet sure which inbuilt facilities already exist, or best practice around sessions.
I want to be able to use this session variable across the application, and for subsequent logout facility.
Can someone advise me on this, or point me in the right direction? Thanks.
case "/login":
var body = '';
console.log("user Login ");
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var obj = JSON.parse(body);
console.log(JSON.stringify(obj, null, 2));
var query = "SELECT * FROM Customer where name='"+obj.name+"'";
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'
});
db.query(
query,
[],
function(err, rows) {
if (err) {
response.end('{"error": "1"}');
throw err;
}
if (rows!=null && rows.length>0) {
console.log(" user in database" );
theuserid = rows[0].customerID;
var obj = {
id: theuserid
}
response.end(JSON.stringify(obj));
}
else{
response.end('{"error": "1"}');
console.log(" user not in database");
}
}
);
});
}
There can be multiple ways of implementing a user session.
One, you could use a browser cookie, it comes with many pros and cons and you should read about it a bit to see how its managed. This would also depend on the server you are using (express, hapi, etc).
Two, you can set a JWT token on the backend, and include it in the header of the response, then you can either use your application state or the local storage of the browser to save that token on the UI. Any such follow up requests requiring authentication should contain this auth token as a header for verification.
For more clarity, you can look into related libraries (such as passport), which make this task a lot easier.
PS: If you choose cookies, please make sure the business is going to allow it or not as the end-users do not like being tracked always. :)

Creating LinkedNotebooks from API

I am working with the Evernote api trying to make linked notebooks from within our web application.
We are using evernote-sdk-js version of the API.
We are able to create the Shared Notebook from the API. Also we are able to create a Linked Notebook and receive a valid response. The problem is the linked notebook is not working. The notebook is returned in the ListLinkedNotebook api call but when I try to authorize it I receive an error.
Error { identifier: 'SharedNotebook.id', key: 'xxxx' }
From what I've read means the notebook is no longer shared by the owner. This is not true as the owner account still shows the pending request in the 'share' window.
Here is the logical flow:
1) User enters email address of the person they wish to share notebook with. A request is made to our server to create a ShareNotebook.
We create a Shared Notebook like this: (From Owner Account)
var notebook = new Evernote.SharedNotebook();
notebook.notebookGuid = guid;
notebook.email = email;
notebook.privilege = Evernote.SharedNotebookPrivilegeLevel.FULL_ACCESS;
var userclient = new Evernote.Client({token: token, sandbox: sandbox});
var notestore = userclient.getNoteStore();
notestore.createSharedNotebook(userclient.token, notebook, function(err, results){
callback(err, results);
});
With an example response like:
{
allowPreview:null
email:"...#gmail.com"
id:12345
notebookGuid:"d2fa3cbe-...."
notebookModifiable:false
privilege:4
recipientSettings:null
requireLogin:null
serviceCreated:1469079222000
serviceUpdated:1469079222000
shareKey:"xxxx-sxxx"
userId:999xxxxx
username:null
}
2) Since Evernote doesn't send an email from the API request we manually send the user a link to activate the Shared Notebook.
Code to create LinkedNotebook: (From Shared User Account)
var notebook = new Evernote.LinkedNotebook;
notebook.shareName = options.shareName;
notebook.username = options.username;
notebook.shardId = options.shardId;
notebook.shareKey = options.shareKey;
var userclient = new Evernote.Client({token: token, sandbox: sandbox});
var notestore = userclient.getNoteStore();
notestore.createLinkedNotebook(userclient.token, notebook, function(err, results){
callback(err, results);
});
And the example response:
{
shareName: 'Notebook Name',
username: '...',
shardId: 'sxxx',
shareKey: 'xxxx-sxxx',
uri: null,
guid: '4f8df3c2-...',
updateSequenceNum: 630,
noteStoreUrl: 'https://www.evernote.com/shard/sxxx/notestore',
webApiUrlPrefix: 'https://www.evernote.com/shard/sxxx/',
stack: null,
businessId: null
}
Has anyone had any luck creating a Linked Notebook from the API? It seems like the createLinkedNotebook API call is not working correctly. Thanks for your help.
tl;dr you can't do what you're trying to do right now, sorry.
So there are a couple pieces missing here, not something you can do much about.
The first piece is that the shared notebook must be "claimed" by a user (the recipient), during which it gets assigned to the user. Until it's claimed, a LinkedNotebook pointing to the SharedNotebook won't actually give you access to the underlying Notebook - authenticateToSharedNotebook will fail.
The second piece is the shareKey itself. We renamed the struct member you see as shareKey to globalId on the SharedNotebook and sharedNotebookGlobalId on the LinkedNotebook - we're currently in the process of updating our developer documentation, and then we'll update the sdks. To "claim" a sharedNotebook, the recipient needs to call authenticateToSharedNotebook with the shareKey, not the globalId. The catch is that we don't expose a method to generate the real shareKey, so there's no way for third-party clients to generate this and join the shared notebook. Once it is claimed, you can call authenticateToSharedNotebook with the globalId to get access to the notebook.
There's a shareNotebook method we added that send an email as part of the API call. That email contains a link for the user to click on which contains the shareKey and allows claiming a SharedNotebook, but that isn't currently in the SDKs or documented. We'll hopefully get it up with this round of doc updates.

Payment GateWay integration in nodejs and mongodb

Hi I am Integration Payment GateWay to my app but i am stuck. for cod(Cash On Delivery) mode of payment it is working fine.but while in integration online payment gateway it is giving bit pain like i am creating payment link using instamojo when link is created successful; i return that payment link to client and redirect user to that link
1 if user fills card details successfully and instamojo hits my provided webhook(post url) with payment details
2 what if user cancels tab or doesn't pays
question here is where shall in create order in database. if it is to be created on placeorder url of my app then i need to set order status incomplete and run a cron job for second condition (because order is already created and webhook is not hit by intamojo). is it right way to do or there is other better ways to handle all this
Promise.all([getUpdatedCart(userId), findUser(userId), getDiscount(userId,couponCode)])
.then(function(resultArray) {
var cart = resultArray[0];
var user = resultArray[1];
var discountAmount = resultArray[2];
var offerId=null;
if (!cart)
return sendResponse(response,400,"error","Cart Not Found");
if (discountAmount>0)
var offerId=getOfferId(couponCode);
var order = {
user: user._id,
cart: cart._id,
shippingAddress:shippingAddressId,
billingAddress:billingAddressId,
paymenMethod: paymentMethod,
offer:offerId,
deliveryNote:deliveryNote,
amount:cart.amount
};
var newOrder = Order(order);
if (paymentMethod==='cod')
newOrder.save(function(error,order){
if (!error)
if (order){
Cart.expireCart(cart._id);
return sendResponse(response,201,"success",order);
}
});
else if(paymentMethod==='intamojo'){
var purpose='Order Number-'+ newOrder.id;
Instamojo.setHeaders(InstaConfig.test.API_KEY, InstaConfig.test.API_AUTH_TOKEN);
var amountPayable = cart.amount - discountAmount;
var data = generatePayload(user, purpose, amountPayable);
Instamojo.createPaymentLink(data, function(error, resultResponse, body) {
if (resultResponse && body && resultResponse.statusCode===201)
return sendResponse(response,200,"success",body.longUrl+"?embed=form");
});
}
else if(paymentMethod==='payumoney'){
}
else
return sendResponse(response,400,"error","Invalid Mode of Payment");
})
.catch(function(error) {
return sendResponse(response,400,"error",error);
});
Can anyone Please help if i need to write cron job kindly suggest library for that
You need not create a cron job.
You can create Order in your database first, and then create a request passing the orderID in purpose parameter to uniquely Identify the Payment Request.
Provide redirect_url and webhook at the time of create a request.
After any Payment payment_request_id and payment_id is send to the redirect_url provided.
Use payment_request_id and payment_id to get the status of the payment, the response will have payment: { ... ,status, ... } use this to update the status in your database.
You can use webhook as a fallback if the user accidentally closes the browser window/tab before it reaches the redirect_url.
For more details, read the documentation

Categories