Stripe client intergration not taking affect after I click buy now link - javascript

I followed this documentation and my stripe checkout is not working. I have taken out the sku and pk from the SO snippet below but can anybody see what I have done wrong as I thought I implemented it correctly.
When I click the buy now link, nothing happens, don't even redirect to the checkout page.
HTML link:
<a class="buy-btn">Buy Now</a>
...
Javascript:
<script>
(function () {
var stripe = Stripe('pk_test_xxx');
var checkoutButton = document.getElementsByClassName('buy-btn');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
items: [{ sku: 'sku_xxx', quantity: 1 }],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//www.xxx-online.com/xxx-leap/success',
cancelUrl: window.location.protocol + '//www.xxx-online.com/xxx-leap/cancelled',
})
.then(function (result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
});
})();

Related

How to get Profile info from Google Signin with redirect mode (no-popup)?

Here's how I do it, after getting the signin's client file :
// HTML
<script type='text/javascript' src="https://apis.google.com/js/api:client.js" async defer></script>
I called gapi.load() function into a HTML button
// load the startApp function after the page loads
jQuery(function () {
$(window).load(function () {
startApp()
})
})
var startApp = function () {
gapi.load('auth2', function () {
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: 'xxxxxxxx-xxxxxxxxxx.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
ux_mode: 'redirect', // I don't want it to display a pop-up
scope: 'profile email' // I just need to get user's name, profile picture and email address
});
// attach this function into a button element with id = "customBtn"
attachSignin(document.getElementById('customBtn'));
});
};
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function (googleUser) {
// it never calls this block of code.
// this never runs
console.log(googleUser.getBasicProfile().getName())
var gProfile = googleUser.getBasicProfile();
var name = gProfile.getName();
var email = gProfile.getEmail();
var imgUrl = gProfile.getImageUrl();
}, function (error) {
return alert("Google Sign in error!")
});
}
It load the necessary functions into a button. If user click on that button, user will be redirected into Google's signin page. After user manages to sign in then Google will redirect the URL back into my website.
It should also send the user's profile info into my attachClickHandler() function within the attachSignin(). But it never happens since it reloads the page before the handler function gets called.
It only works if I change the ux_mode: 'redirect' into default' popup
The best I can do right now is just to get the email address from the token_id parameter that Google give in URL after signin. The id_token field from the URL is a jwt that can be decoded
http://localhost:3006/login#scope=email%20profile%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20openid&id_token=xxxxxxxxx&client_id=xxxxxxxxxxxx-xxxxxx.apps.googleusercontent.com
So How to get the user's profile information with ux_mode set to redirect ?
I modified your code so it works:
var startApp = function () {
gapi.load('auth2', function () {
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: 'xxxxxxxx-xxxxxxxxxx.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
ux_mode: 'redirect', // I don't want it to display a pop-up
scope: 'profile email' // I just need to get user's name, profile picture and email address
});
// attach this function into a button element with id = "customBtn"
attachSignin(document.getElementById('customBtn'));
// START NEW CODE
auth2.currentUser.listen(function(googleUser) {
if (googleUser && (gProfile = googleUser.getBasicProfile())) {
var name = gProfile.getName();
var email = gProfile.getEmail();
var imgUrl = gProfile.getImageUrl();
console.log({name, email, imgUrl});
}
});
// END NEW CODE
});
};
// Can remove callbacks if not using pop-up
function attachSignin(element) {
auth2.attachClickHandler(element, {});
}
Explanation:
When using redirect instead of pop-up, listen on currentUser instead of the attachClickHandler() callbacks. The Google API will detect and consume the redirect parameters, firing the currentUser.listen handler.
Sources:
https://github.com/google/google-api-javascript-client/issues/477#issuecomment-430299619
https://developers.google.com/identity/sign-in/web/listeners

Get parameters and store and use them on variables to use on my method

I want to get some parameters and use them to reset password function from firebase.
This is how my link looks like:
http://localhost:8080/passwordreset?mode=resetPassword&oobCode=y6FIOAtRUKYf88Rt5OlEwxUuTyEmb3M4gquZSIseX2UAAAFevpj-gw&apiKey=AIzaSyBaCCvq-ZEfQmdrL7fmElXDjZF_J-tku2I
I want to get mode, oobCode and apiKey.
Here is what I have for now:
export default {
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode:'',
actionCode: '',
continueUrl: '',
}
},
methods: {
handleResetPassword: function() {
var accountEmail;
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
var accountEmail = email;
firebase.auth().confirmPasswordReset(this.actionCode, this.passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
// Error occurred during confirmation. The code might have expired or the
// password is too weak.
console.log("error 1")
});
}).catch(function(error) {
// Invalid or expired action code. Ask user to try to reset the password
// again.
console.log("error 2")
});
},
}
}
From Firebase documentation:
Some user management actions, such as updating a user's email address
and resetting a user's password, result in emails being sent to the
user. These emails contain links that recipients can open to complete
or cancel the user management action. By default, user management
emails link to the default action handler, which is a web page hosted
at a URL in your project's Firebase Hosting domain.
link: https://firebase.google.com/docs/auth/custom-email-handler
You need to get those parameters and store them on variables, from firebase documentation i got those snippets and just wrote the getParameterByName function:
function getParameterByName( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Get the action to complete.
var mode = getParameterByName('mode');
// Get the one-time code from the query parameter.
var actionCode = getParameterByName('oobCode');
// (Optional) Get the continue URL from the query parameter if available.
var continueUrl = getParameterByName('continueUrl');
You need to get those parameters first and verify the actioncode on the verifyPasswordResetCode method, then you can change the password and store it along with the action code to the method.
In your export default :
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode: mode,
actionCode: actionCode,
continueUrl: continueUrl,
}
},
methods: {
handleResetPassword: function() {
var passwordNew = this.passwordNew
var actionCode = this.actionCode
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
console.log("ActionCode: "+ actionCode);
firebase.auth().confirmPasswordReset(actionCode, passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
console.log("error 1"+ error)
});
}).catch(function(error) {
console.log("Action code is invalid"+ error)
});
},
}

Integrate Paypal and Paypal Express with PayPal REST API

I try to integrate Paypal as a payment method.
When the User clicks on "checkout", it should be able that the user click's on 'direct to paypal' to do the express checkout. Or going the "normal" way, entering his shipping data and clicks on the last page "pay with paypal"
I follow the Paypal REST API documentation and the express checkout works fine. But I didn't get the "normal" checkout to run.
The problem isn't in the backend. So all backend operations (create payment, accept payment, etc.) running well.
But in the frontend I'm getting errors.
My Code for the Express checkout is:
<script type="text/javascript" src="https://www.paypalobjects.com/api/checkout.js?ver=4.6.1">
//....
if (jQuery('#paypal_express_btn_div').length > 0) {
paypal.Button.render({
env: 'sandbox'
payment: function(resolve, reject) {
var orderId = jQuery("#orderPostId").val();
// Set up the payment here, when the buyer clicks on the button
var CREATE_PAYMENT_URL = ajaxObject.ajaxURL;
paypal.request.post(
CREATE_PAYMENT_URL,
{
action: 'create_paypal_payment',
orderId: orderId,
}
)
.then(function(data) {
resolve(data.paymentID);
})
.catch(function(err) {
reject(err);
});
},
onAuthorize: function(data, actions) {
//After the reload, a confirm page will be shown
window.location = data.returnUrl;
},
onCancel: function(data, actions) {
return actions.redirect();
},
}, '#paypal_express_btn_div');
}
As I said, this works well.
When the user clicks the button, the method "create_paypal_payment" runs on the backend. The payment get's created and when the payment is created, the paypal window get's shown to the user.
Now he can confirm the payment by clicking "next". Then (after the page reload) a confim page is shown to the user (with all payment and shipping data) and when he clicks "confirm payment" everything is fine.
But now I try to do the payment at the end of the order. (So the user has entered his shipping data etc.)
The first steps running well. So I can create the payment in the backend.
But now I'm getting an error when I try to run the payment execute method in the "onAuthorize" Action. My method "executePayPerPayPalBasic" will not be executed. I'm getting directly an error.
My Code:
if (jQuery("#paypal_btn_div").length > 0) {
var RS_IB_PAYMENT_URL = ajaxObject.ajaxURL;
paypal.Button.render({
env: 'sandbox'
commit: true, //button "pay now" in the paypal window
payment: function(resolve, reject) {
var orderId = jQuery("orderPostId").val();
// Set up the payment here, when the buyer clicks on the button
paypal.request.post(
RS_IB_PAYMENT_URL,
{
action: 'create_paypal_payment',
orderId: orderId,
}
)
.then(function(data) {
resolve(data.paymentID);
})
.catch(function(err) {
reject(err);
});
},
onAuthorize: function(data, actions) {
// Execute the payment here, when the buyer approves the transaction
var payerID = data.payerID;
var paymentID = data.paymentID;
var paymentToken = data.paymentToken;
var returnUrl = data.returnUrl;
paypal.request.post(
RS_IB_PAYMENT_URL,
{
action: 'executePayPerPayPalBasic',
orderId: orderId,
payerID: payerID,
paymentID: paymentID,
paymentToken: paymentToken,
returnUrl: returnUrl
}
)
.then(function(data) {
var paypallink = data.data["PERMALINK"];
window.location = paypallink;
})
.catch(function(err) {
reject(err);
});
}
}, '#paypal_btn_div');
}
The error:
"Error: window.paypal<["./node_modules/post-robot/src/drivers/receive/types.js"]/exports.RECEIVE_MESSAGE_TYPES<#https://www.paypalobjects.com/api/checkout.js:3319:40
receiveMessage#https://www.paypalobjects.com/api/checkout.js:1444:13
messageListener#https://www.paypalobjects.com/api/checkout.js:1462:13
"
Another strange thing is, as I understand, normaly the "commit" parameter should handle if the paypal button is "pay now" or "next".
Because of this, I'm not set the parameter in my express checkout (because I want the "next" button) and setting the parameter to true in my normal checkout.
But since I used the commit Parameter 1 time. I always getting the "pay now" button. Even in my Express Checkout Button.
I have tried to set the parameter to false manually. But it doensn't work.
I tried this with Firefox, Google Chrome and Microsoft Edge.
The error only occurs on Firefox.
In Google Chrome and Microsoft Edge it works like a charm.
But on each of these three Browsers the Button Text has the Text "pay now" and never shows "next".
Also, all payments are marked as Paypal Express Payments. Is there any Parameter to check my second code als 'normal' payment. Or is it normal, that when I do the payment with the checkout.js all payments are marked as Express Payment?
Where is my failure? Can anybody help me?

PayPal in-context checkout doesn't always trigger startFlow?

We've built an online store that integrates the PayPal in-context / express checkout. This is using the Classic NVP API.
It has been receiving the token every time and logging to the console that it is starting the payment flow. However, every now and then it will not redirect the modal to the checkout, but I can run paypal.checkout.startFlow('<token_from_console>'); in the console and it successfully redirects.
Here's the js for the checkout process:
window.paypalCheckoutReady = function () {
paypal.checkout.setup('<?=$paypal_merchantID?>', {
locale: 'en_AU',
<? if ($paypal_platform == 'sandbox') { ?>environment: 'sandbox',<? } ?>
button: ['submitButton'],
condition: function() {
return $('#orderForm').valid();
},
click: function() {
// INITIALISE CHECKOUT
paypal.checkout.initXO();
// SET EXPRESS CHECKOUT AND GET TOKEN
setCheckout = $.post("/checkout.php?mode=setExpressCheckout", $("#orderForm").serialize());
setCheckout.done(function(response){
console.log(response);
if (response.substr(0,2) == 'EC') {
paypal.checkout.startFlow(response);
console.log('starting paypal flow');
}
});
setCheckout.fail(function(reponse){
paypal.checkout.closeFlow();
});
}
});
};

Twitter authentication in Codebird JS

I am very new to integrating social sites into a website. I somewhat managed to integrate Facebook, but I have no idea how to integrate Twitter.
I want to login through a Twitter account, then get the username and some other data from Twitter. I have a consumer key and consumer secret. I'm not sure how to proceed from here, and my Google searches haven't helped so far.
I am trying with codebird js:
$(function() {
$('#twitter').click(function(e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("redacted", "redacted");
cb.__call(
"oauth_requestToken",
{ oauth_callback: "http://127.0.0.1:49479/" },
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize",
{},
function (auth_url) {
window.codebird_auth = window.open(auth_url);
}
);
}
}
);
cb.__call(
"account_verifyCredentials",
{},
function(reply) {
console.log(reply);
}
);
})
});
But I get
Your credentials do not allow access to this resource
How can I resolve this and get the user data? I am open to using an alternate Twitter implementation.
You cannot call cb._call( "account_verifyCredentials"... there.
The code only has a request token, NOT an access token, which you will only receive after the user authorizes your app (on the Twitter auth popup).
You are using the "callback URL without PIN" method, as documented on the README. So you'll need to implement that example code on your http://127.0.0.1:49479/ page.
Also, this essentially requires that you store the oauth credentials somewhere. In my example below, I've used localStorage.
$(function () {
$('#twitter').click(function (e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("CeDhZjVa0d8W02gWuflPWQmmo", "YO4RI2UoinJ95sonHGnxtYt4XFtlAhIEyt89oJ8ZajClOyZhka");
var oauth_token = localStorage.getItem("oauth_token");
var oauth_token_secret = localStorage.getItem("oauth_token_secret");
if (oauth_token && oauth_token_secret) {
cb.setToken(oauth_token, oauth_token_secret);
} else {
cb.__call(
"oauth_requestToken", {
oauth_callback: "http://127.0.0.1:49479/"
},
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
console.log("reply", reply)
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// save the token for the redirect (after user authorizes)
// we'll want to compare these values
localStorage.setItem("oauth_token", reply.oauth_token);
localStorage.setItem("oauth_token_secret", reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize", {},
function (auth_url) {
console.log("auth_url", auth_url);
// JSFiddle doesn't open windows:
// window.open(auth_url);
$("#authorize").attr("href", auth_url);
// after user authorizes, user will be redirected to
// http://127.0.0.1:49479/?oauth_token=[some_token]&oauth_verifier=[some_verifier]
// then follow this section for coding that page:
// https://github.com/jublonet/codebird-js#authenticating-using-a-callback-url-without-pin
});
}
});
}
})
});
Also made a JSFiddle

Categories

Resources