Rails: Stripe accept payment workflow - ruby

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.

Related

Error 405 (method not allowed) using ajax method post laravel

There is an ajax script to remove comments under posts. When I click the delete button, I get a 405 error.
The console displays this: DELETE http://127.0.0.1:8000/id2/post/582 405 (Method Not Allowed), although the method is different url
My route Route::delete('/id{id}/post/{postId}/comment/{commentId}/delete', 'CommentController#deleteComment')->name('deleteComment');
And script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "DELETE",
data: {_token: token, id: id},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});
I need that when I press delete, the record disappears, but it does not disappear. To make the entry disappear, you need to reload the page
Under the hood Laravel actually uses POST request within an _method as parameter when you perform destroy operation, so your JavaScript section should looks like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e) {
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "POST",
data: {_token: token, id: id, _method: 'DELETE'},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});

Strong customer authentication in stripe

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.

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!!

Knockout object passed to Controller as JSon MVC ASP.Net

I am trying to pass knockout object as below,
When i pass the data using // ko.utils.postJson only without any the AJAx the data is passed to my controller to the "task", but when i try to post by Ajax I get a null value for task
function TaskListViewModel() {
var self = this;
self.availableMeals = [
{ UserName: "Standard", UserId: 0 },
{ UserName: "Premium", UserId: 34 },
{ UserName: "Ultimate", UserId: 290 }
];
self.save = function () {
// ko.utils.postJson(location.href, { task: this.availableMeals });
$.ajax(location.href,{
data: ko.toJSON({ task: this.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
}
ko.applyBindings(new TaskListViewModel());
To the Controller as below,
[HttpPost]
public ActionResult About([FromJson] IEnumerable<UserProfile> task)
{
return RedirectToAction("Login","Account");
}
I would try changing your code to call the stored self reference in your Ajax call as follows:
$.ajax(location.href,{
data: ko.toJSON({ task: self.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
I'm guessing that you are having a scope issues where this is losing it's reference in your Ajax call.

401 (Unauthorized) error with ajax request (requires username and password)

I'm making an ajax request to retrieve json data from webtrends - a service that requires a login. I'm passing the username and password in my ajax request, but still gives me a 401 unauthorized error. I've tried 3 different methods - but no luck. Can someone pls help me find a solution?
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
Method 3 might work when you use a named callback function and use basic authentication in the url. Mind though that a lot of browsers don't accept url-authentication (or whatever the name is). If you want to try it, you can rewrite it like this:
window.onload = function() {
var url = "https://xxx:xxx#ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}

Resources