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

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();
});
}
});
};

Related

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

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;
}
});
});
})();

Handle Push notification in Nativescript

I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});

Protractor: Non angular login to angular site

Before I can reach the site to be tested I have to visit a login (non-angular) page first
var url = 'http://localhost:9999/login?usern=bar';
browser.driver.get(url);
Although that is a non-angular page, passing the ?usern=bar into the url the server gives an HTTP CODE of 302, and redirects to the page /new-user. Inside the new-user page I have to click a button before I can begin testing
But whatever I do I always get
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
There is something wrong in my flow, because I can see the new-user page, but the button is not clicked (and long after that the errors appear)
The spec file:
var Site = require('helper/site');
describe('Main', function {
beforeAll(function () {
return Site.login();
});
it('should show the main page', function () {
epect(browser.getCurrentUrl()).toMatch(/\/main/);
});
});
Site.js:
function login() {
browser.driver.get('http://localhost:9999/login?usern=bar');
browser.driver.wait(function () {
return browser.driver.getCurrentUrl().then(function (url) {
return /\/new-user/.test(url);
});
});
element(by.css('.save')).click();
}
module.exports = {
login: login
};
Any help would be appreciated
You have to turn the sync off:
describe('Main', function {
beforeAll(function () {
browser.ignoreSynchronization = true;
return Site.login();
});
it('should show the main page', function () {
browser.ignoreSynchronization = false;
expect(browser.getCurrentUrl()).toMatch(/\/main/);
});
});
Though, think of better places to turn it off and then on again once you are on the main page.
I used browser.waitForAngularEnabled(false) to turn off waiting for angular app. My app used O365 login.
public async HandleO365Login() {
await browser.waitForAngularEnabled(false);
await this.o365usernameTextBox.sendKeys(Constants.USER_EMAIL);
await this.o365NextButton.click();
}
You can turn it on after your angular app gets loaded.

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

Triggering Javascript Code from PHP Laravel Controller

I'm using OAuth for login in my Laravel Controller. Its working fine but the thing is when the user is registered for the first time, I wanna trigger the HTML 5 geolocation API to fetch the user's current location and do some mixpanel stuff. Earlier I was using AJAX in the JS for the login so there was no such problem but now that I've implemented a complete server side solution, I'm stuck with this one problem.
The Laravel Controller code looks something like this :
function callback(){
\\ fetch the access token and graph data
if($res = \Auth::mjAuthenticate('facebook', $fbData)){
$user = \Auth::scope()->getUser();
return \Redirect::to('events');
}
if (\Auth::mjRegister('facebook', $fbData)) {
$user = \Auth::scope()->getUser();
return \Redirect::to('events');
}
return $this->handleFailure('Some Problem Occured');
}
The Earlier JS Code was :
ajax
.post('auth/login', {
data: {
oauth_provider: 'facebook',
oauth_token: accessToken
},
cache: false
})
.done(function(data) {
mixpanel.track('User Logged In', {
id: data.resource.id,
provider: 'Facebook',
email: data.resource.email,
first_name: data.resource.first_name,
last_name: data.resource.last_name
});
if (data.msg == 'Resource registered') {
if(navigator.geolocation){
// Prompt for Allow Deny Geolocation popup.
}
}
});

Categories

Resources