Strong customer authentication in stripe - ajax

I have implemented Strong customer authentication in stripe.
its working on test mode, but not working on live mode I want to know the payment method for live mode?
function createPaymentIntent(plan_id,customer_id) {
$.ajax({
type: 'POST',
url: 'https://api.stripe.com/v1/payment_intents',
headers: {
Authorization: 'Bearer sk_live_*******************'
},
data: {
customer: customer_id,
amount: Math.round(amount*100),
confirmation_method: 'automatic',
payment_method: 'pm_card_threeDSecure2Required',
confirm: true,
currency: currency,
},
success: (response) => {
console.log("payment" + response['client_secret']);
var stripe = Stripe('pk_live_********************');
var elements = stripe.elements();
try {
stripe.handleCardPayment(
response['client_secret']
).then(function(result) {
if (result.error) {
$('#hvalidation').hide();
$('.checkout-title').after('<span id="errmsg">Please complete the authentication process</span>');
// Display error.message in your UI.
} else {
createSubscription(plan_id,customer_id);
// The payment has succeeded. Display a success message.
}
});
}
catch(error) {
console.log(error.message);
}
},
error: (response) => {
console.log(response);
}
})
}
Actual Result- Authentication model is not displaying on live mode.
Expected Result- Authentication model should display on live mode.

Related

Rails: Stripe accept payment workflow

I am trying to integrate Stripe using the elements workflow.
Below are the steps that a user does
Select the plan
Enter card details and click 'Subscribe'
When the user clicks "Subscribe", in the backend I
create a subscription and return the clientSecret
call confirmCardPayment by using the clientSecret in step 1
on success of step 2, pass the paymentIntentId to backend to fetch the card details and save it in the user record.
Below is part of the code
$(document).on('click', '#payment-btn', (e) => {
event.preventDefault();
let name = document.querySelector('#name_on_card').value;
$.ajax({
url: '/subscriptions',
method: 'POST',
beforeSend: function(request){
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
data: {
plan_id: plan_id
}
}).then((res) => {
stripe.confirmCardPayment(res.clientSecret, {
payment_method: {
card: card,
billing_details: {
name: name
}
}
}).then((result) => {
if(result.error) {
alert(result.error.message);
} else {
$.ajax({
url: '/user',
method: 'PATCH',
dataType: "json",
beforeSend: function(request){
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
data: {
stripe_customer_payment_method_id: result.paymentIntent.payment_method
}
}).then((result) => {
Turbolinks.visit('/videos?message=success');
})
}
});
});
});
Would this be a good way to execute the payments workflow or is there a more efficient way, may be i am missing something.
Thanks.

Get a 401 error with POST and PUT Laravel passport/Vue/Axios

I am working on a Vue application with a seperate Laravel back-end API. The back-end has Laravel passport that requires an access token when doing database calls.
Normally everything goes right, I can get data back from the database but for some reason, 2 of my calls gets errors, the POST en PUT. I don't know why I get unauthenticated (401) from laravel passport back, while my get request is going well. Also, both POST and PUT are going fine in the postman application.
The get request
getSuppliers() {
axios.get(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
})
.then((response) => {
this.loaded = true;
this.relations = response.data.data;
})
.catch(error => console.log(error));
},
The post request
axios.post(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
Helper functions for access token
function getHeaders(token) {
return {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
};
}
function getToken() {
const oauth = JSON.parse(localStorage.getItem('oauth') || '{}');
if (oauth.access_token) {
return oauth.access_token;
}
return false;
}
Somebody out there that had the same problem or similair?
After some digging, going through my other code and requests I find a solution that fixed it for me.
Instead of
axios.post(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
I had to do
axios({
method: 'post',
url: `${this.$API_URL}/api/v1/relations`
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
I don't see any difference except the style, so I don't know exactly why the second style is working and the first one is not, especially for the put and post type of requests.

Paypal - How to Create Payment on server side using PHP Laravel

I'm working on paypal express checkout now, and i have difficulties on create payment on server side, here is my code:
var CREATE_PAYMENT_URL = '{{route('landing.paypalresponse', 1)}}';
var EXECUTE_PAYMENT_URL = 'https://my-store.com/paypal/execute-payment';
var CSRF_TOKEN = $("meta[name='csrf-token']").attr("content");
paypal.Button.render({
env: 'sandbox', // Or 'sandbox'
commit: true, // Show a 'Pay Now' button
payment: function() {
return paypal.request({
method: 'post',
url: CREATE_PAYMENT_URL,
headers: {
'x-csrf-token': CSRF_TOKEN
}
}).then(function(data) {
console.log(data);
return data.id;
});
},
onAuthorize: function(data) {
return paypal.request.post(EXECUTE_PAYMENT_URL, {
paymentID: data.paymentID,
payerID: data.payerID
}).then(function() {
// The payment is complete!
// You can now show a confirmation message to the customer
});
}
}, '#paypal-button');
what should i do on the server side?
how to create payment on my controller?
is that return a JSON array? or?
i have try to convert the object here:
Paypal tutorial
to array and return to my paypal button, but it return me this error
Paypal Error

Send an Authenticated Request

I have an MVC project secured with a asp.net identity:
This is my Login function:
self.login = function () {
event.preventDefault();
if (!$('#formLogin').valid()) {
return false;
}
var loginData = {
grant_type: 'password',
username: self.userName(),
password: self.password()
};
$.ajax({
type: 'POST',
url: '/API/Token',
data: loginData
}).done(function (data) {
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
self.authenticate();
//change status of Login button to Logout
self.redirect('Users');
}).fail(showError);
}
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
console.log(self.token);
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
}
$.ajaxSetup({
headers: headers
});
}
That works fine, I get the token successfully and the headers are set up correctly.
The problem is that when I try to send a request- for example:
self.getUsers = function () {
$.get("/API/Users/GetUsers/");
}
I get a 401 error from the server:
"message": "Authorization has been denied for this request."
What am I doing wrong?
According to the official documentation of the jQuery.ajax, use this to set custom headers of each request:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', '...');
}
});

Extjs 5 ajax PUT and DELETE methods throw 403 errors (csrf token included)

I am building a web application with django-rest-framework and extjs5.
Obviously i faced problems with django's csrf token, which i had to inlude in Extjs's Ajax requests.
But while i implemented POST method successfully, it seems that my implementation doesn't work for PUT and DELETE method.
My POST method code:
onSaveRecordBtnClick: function(){
Job_Name = this.lookupReference('Job_Name').getValue();
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/',
method: "POST",
params: {
Job_Name: Job_Name,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Submission Successfull');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
This works perfectly, but when i try PUT or DELETE method i keep getting:
Request Method:DELETE
Status Code:403 FORBIDDEN
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
My DELETE method:
onJobDblClick : function(grid, record, index, eOpts) {
var job_id = record.id;
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/' + job_id + '/',
method: "DELETE",
params: {
'id': job_id,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Deleted Successfully');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
My job model is:
Ext.define('MyApp.model.Job', {
extend: 'MyApp.model.Base',
fields: [
{ name: 'id', type: 'int' },
{ name: 'Job_Name', type: 'string' },
],
proxy: {
type: 'rest',
url: '/jobs_api/job/',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
I don't know why this is happening. Please help!!

Resources