redirect to stripe checkout - ruby-on-rails-4

i have my website in ruby on rails 5 and i'm updating my stripe payment gateway with this link but clicking my button doesn't redirect me to the stripe checkout, this is what i have in the controller:
def index
Stripe.api_key = Rails.configuration.stripe[:secret_key]
session = Stripe::Checkout::Session.create(
payment_method_types: ['card'],
line_items: [{
price: 'price_1HKywnBS16ZK5Vr3GYCRvTir',
quantity: 1,
}],
mode: 'subscription',
success_url: 'https://www.my_site.network/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url: 'https://www.my_site.network/cancel',
)
end
I think the error may be when replacing the session id in the javascript code of my index view:
<button id="checkout-button">Pay</button>
<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
var stripe = Stripe('<%= Rails.configuration.stripe[:publishable_key] %>');
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function() {
stripe.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as argument here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: '<%=session.id%>'
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
});
</script>

you don't have to use '<%=session.id%>'.
The value that you must to use there is the entire value that you store in session when you do: Stripe::Checkout::Session.create in your controller.

Related

how to set cookies during vuejs post

I am trying to send post data to a django Restful API using vuejs. here is the code I have so far:
<script>
import axios from 'axios'
import VueCookies from 'vue-cookies'
//3RD ATTEMPT
VueCookies.set("csrftoken","00000000000000000000000000000000");
// # is an alias to /src
export default {
name: "Signup",
components: {},
data: () => {
},
methods: {
sendData(){
// 2ND ATTEMPT
// $cookies.set("csrftoken", "00000000000000000000000000000000");
axios({
method: 'post', //you can set what request you want to be
url: 'https://localhost:8000/indy/signup/',
data: {
csrfmiddlewaretoken: "00000000000000000000000000000000",
first_name: "wade",
last_name: "king",
email: "wade%40mail.com",
password1: "05470a5bfe",
password2: "05470a5bfe"
},
// 1ST ATTEMPT
// headers: {
// Cookie: "csrftoken= 00000000000000000000000000000000"
// },
withCredentials: true
})
}
}
</script>
I have a button which executes the sendData() method on a click. The code uses the axios library to send a post request to the django API running on http://localhost:800/indy/signup/
The problem with just sending a post request to the API is that it will get blocked in order to prevent Cross Site Response Forgery (CSRF), I dont quite understand CSRF but I know if the csrftoken is set as a cookie and has the same value as the csrfmiddlewaretoken then the post should go through to the API.
You can see my attempts to set the cookie in the code I provided
1ST ATTEMPT)
headers: {
Cookie: "csrftoken= 00000000000000000000000000000000"
},
Here I'm trying to set the cookie directly in the header. When I click send I get an error in my browser console saying refused to set unsafe header "Cookie"
2ND ATTEMPT)
$cookies.set("csrftoken", "00000000000000000000000000000000");
Here I'm trying to set the cookie using the vue-cookies module. When i click send I get the following error, net::ERR_SSL_PROTOCOL_ERROR
3RD ATTEMPT)
VueCookies.set("csrftoken","00000000000000000000000000000000");
Here I'm trying to set a global cookie using the vue-cookies module. When I click send I get the same error as attempt 2
IMPORTANT:
However when I send post data to the API from my terminal using the following curl command, it works perfectly
curl -s -D - -o /dev/null \
-H 'Cookie: csrftoken= 00000000000000000000000000000000' \
--data 'csrfmiddlewaretoken=00000000000000000000000000000000&first_name=wade&last_name=king&email=wade%40mail.com&password1=05470a5bfe&password2=05470a5bfe' \
http://localhost:8000/indy/signup/
my main question is How can I replicate this curl request using vuejs? I've looked all over on line and none of the tutorials deal with setting cookies.
I posted this question some time ago, I have managed to work around it by running the vue frontend on the same network as the django backend. Follow this tutorial for instructions: integrating vuejs and django
Once I had the application set up I was able to set the cookies much more cleanly using :
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
Here is my login page for example
<template>
<div class = "container">
<h2>Sign In</h2>
<b-form v-on:submit.prevent="submit()">
<b-form-group id="signin" label="">
<!-- dynamic error message -->
<p class="loginErr" v-if="logErr">Incorrect Username or Password</p>
<b-form-input
id="signin-email"
v-model="username"
placeholder="Email"
required
></b-form-input>
<b-form-input
id="signin-password"
v-model="password"
placeholder="Password"
required
type="password"
></b-form-input>
</b-form-group>
<b-button v-if="!loading" type="submit" variant="primary">Submit</b-button>
<b-spinner v-if="loading"></b-spinner>
</b-form>
</div>
</template>
<script>
import axios from 'axios'
import Vue from 'vue'
export default {
data: ()=>{
return{
loading: false,
logErr: false,
username:'',
password:'',
next: '%2Findy%2Fprofile%2F'
}
},
created: function(){
},
methods: {
submit(){
var vm = this;
vm.loading = true;
var dataStr = 'username='+vm.username+'&password='+vm.password
//set the csrf tokens so django doesn't get fussy when we post
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
axios.post('http://localhost:8000/api/signin/', dataStr)
.then(function (response) {
vm.loading = false;
//determine if indy accepts the login request
var res = response.data
console.log(response.data)
if(!res.login){
vm.logErr = true;
}else{
vm.redirect('home');
}
})
.catch(function (error) {
//currentObj.output = error;
});
},
redirect(path) {
this.$router.push('/' + path);
}
}
}
</script>
<style>
.loginErr{
color: orange;
}
</style>

How can I render AccountKit UI

Here is my form which is on my login.php page:
<form id="LoginForm">
<input value="+1" id="country_code" />
<input placeholder="phone number" id="phone_number"/>
<button onclick="smsLogin();">Login via SMS</button>
</form>
<script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:"{{FACEBOOK_APP_ID}}",
state:"{{csrf}}",
version:"{{ACCOUNT_KIT_API_VERSION}}",
fbAppEventsEnabled:true,
redirect:"{{REDIRECT_URL}}"
}
);
};
// login callback
function loginCallback(response) {
if (response.status === "PARTIALLY_AUTHENTICATED") {
var code = response.code;
var csrf = response.state;
// Send code to server to exchange for access token
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
}
}
// phone form submission handler
function smsLogin() {
var countryCode = document.getElementById("country_code").value;
var phoneNumber = document.getElementById("phone_number").value;
AccountKit.login(
'PHONE',
{countryCode: countryCode, phoneNumber: phoneNumber}, // will use default values if not specified
loginCallback
);
}
// email form submission handler
function emailLogin() {
var emailAddress = document.getElementById("email").value;
AccountKit.login(
'EMAIL',
{emailAddress: emailAddress},
loginCallback
);
}
</script>
And here is the expected interface to send the code :
The problem I have is before AccountKIt UI get rendered the user has to click Login via SMS button... which I am not finding interesting, I want if the user goes on login.php page the AccountKit UI should be rendered automatically without showing my form.
I tried to do to remove the form and modified the function smsLogin() to be immediately called as follow :
function {
var countryCode = document.getElementById("country_code").value;
var phoneNumber = document.getElementById("phone_number").value;
AccountKit.login(
'PHONE',
{countryCode: countryCode, phoneNumber: phoneNumber}, // will use default values if not specified
loginCallback
);
}();
But I received the error saying :
TypeError: AccountKit.login is not a function
I need some tips to see how I can acheive what I want to do.
I am redirecting the user directly on the page of accountkit when he visit my login page.The link of accountkit is : https://www.accountkit.com/v1.0/basic/dialog/sms_login/ and has parameter I am passing the phonenumber, country_code,redirect url(which is my page on which the user will be sent). So everything is working as I wanted.

facebook connect SDK sample: how to retrieve location and birthday?

I am using the offcial sample from facebook: it works fine, except I cannot retrieve the birthday and location.
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me?fields=id,first_name,last_name,gender,location,email,birthday', {fields: 'name, email,gender,first_name,last_name,location,birthday' }, function(response) {
console.log(response);
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</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="false" scope="public_profile,email,user_birthday,user_location" size="medium" onlogin="checkLoginState();">Connect with facebook</fb:login-button>
<div id="status">
</div>
</body>
</html>
This works fine but no borthday nor location in response.
I spent a lot of time and it looks that nowdays to retrieve these informations I need to nowdays to REVIEW the application before accessing these data
https://developers.facebook.com/docs/facebook-login/review/what-is-login-review
Is this correct: do I need to submit the application for review or is it something wrong I am doing ?
Yes, it's true, and it's all in the docs:
https://developers.facebook.com/docs/facebook-login/review
https://developers.facebook.com/docs/apps/review
But, if you're using the an admin/tester/developer of the said app, you are able to give and test these permission with your app. Only if third parties will need to access the app, you'll need to pass Login Review.

firebase + facebook front end - Front end query

I am trying to do a facebook login for my firebase app. This is the first time I am using a FB login. I went through the article and small tutorials. But I am stuck at the front end
i.e the button creating part in my index.html and linking it to my firebase variable.
I saw the firefeed example and it is very differently done from the procedure on the FB developers guide. Any help will be great.
As an extension to the login I also want to access the graph data of the user logging in
This is my javascript, What will go in my HTML.
var myDataRef = new Firebase('[myFirebase]');
var authClient = new FirebaseAuthClient(myDataRef);
authClient.login("facebook", function (err, token, info) {
if (!err) {
console.log("Got token " + token + " for user " + info.name);
}
});
Check out http://firebase.github.io/firebase-simple-login/ for an example of Firebase Simple Login in action that you can copy / fork and drop into your application.
Here's a simple example of an application which allows you to login to Facebook upon link click:
Login
<script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js"></script>
<script type="text/javascript" src="https://cdn.firebase.com/v0/firebase-auth-client.js"></script>
<script type="text/javascript">
var firebaseRef = new Firebase("[myFirebase]");
var authClient = new FirebaseAuthClient(firebaseRef, function(error, user) {
if (error) {
// an error occurred while attempting login
console.log('an error occurred:');
console.log(error);
} else if (user) {
// user authenticated with Firebase
console.log('logged in:');
console.log(user);
} else {
// user is logged out
console.log('logged out');
}
});
</script>
</body>
</html>

Click facebook like button and be taken to another url

Is something like this possible?
I have a client launching an online magazine for his business. He wants to add a facebook like button (for the magazine fanpage) on his current corporate site and ask users to 'like it' in order to be taken to the magazine website. Can it be done? Are there drawbacks to this approach? For example, the same user will have to 'like it' every time they want to access the magazine site?
Thank you for any suggestion, I'm pretty new to facebook.
You can redirect a user on clicking a like button using the Javascript SDK and FB.Event.Subscribe
FB.Event.subscribe('edge.create', function(response) {
window.parent.location = 'http://www.google.com';
});
edge.create is called when ever a user likes something on the page
response is the url that has just been liked.
If there are multiple like buttons on the page you could use an if statement with the response to make sure the page only redirects for a particular like button
Here's the full javascript code and a like button
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
FB.Event.subscribe('edge.create', function(response) {
window.parent.location = 'http://www.google.com';
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/<?php if(isset($fb_user['locale'])){echo $fb_user['locale'];}else{echo'en_US';}?>/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<fb:like href="http://www.google.com" send="false" width="450" show_faces="true"></fb:like>