Go back to Ionic application after payment success from Paypal - ionic-framework

I have created an Ionic app. I have some items to order. Payment is done using Paypal. I have called a web url using window.open(url) which is redirecting me to the Paypal.
I'm able to do the payment successfully, but Can anyone please let me know how I can come back to my ionic app after successful payment.
Note: I have not used Paypal plugin as it is not developed for windows

Few days back even i was facing the same issue, i was able to do payment where the ionic app drags to the third party api but after the payment it was not redirecting to the ionic app in the mobile/smartphone.
after soing dome R and D i got the solution that when the app is running on the mobile it will not be having any port number running on i,e., http://localhost/dashboard instead of http:localhost:8100/dashboard, where 8100 is the port number running for the ionic server.
after specifying the return back url as http://localhost/dashboard i was able to redirect back to the ionic app.

Use loadsart event of the InAppBrowser to catch the urls when load pages after payment was done. Then you can process your tasks according to those urls and their parameters as you prefer. As an example, when you have the payment successful url you can navigate back to your app after closing the open browser. Also you can have the data passing back when the payment is success or fail, into your application using this way. Hope this will help to you.
addEventListener('loadstart', function(event) { var currentUrl = event.url /*do the rest according to the url inside your application */});
I just add a pseudo-code below.
browserRef.addEventListener('loadstart', function(event) {
var param = getParameters(event.url); //Read the parameters from the url
if (isCorrectParameters(param)) { //Check parameters agaist the payment gateway response url
browserRef.close(); // colse the browser
//Handle the success and failed scenarios
if(success){
$state.go('test');
}else{
// handle fail scenario
}
}
});

Related

Flutter oAuth : how to get started with OAuth and Stripe connect

I am trying to implement stripe connect in my flutter app. Here are the steps I need to implement. Can anyone please navigate me on how I could achieve this in Flutter?
I am able to create a button with the endpointUrl but that's all..
Thanks
I found out this myself using firebase cloud functions:
first you create an https function in the firebase cloud function
then you add the link created by the function to your stripe dashboard
then you write the following logic to your function
obtain the the authorisation code
fetch data from stripe
save the response somewhere (in my case in realtime database)
Here is the function
exports.connectStripeStandardAccount = functions.https.onRequest((req, res) => {
let authCode = req.query.code;
return stripe.oauth.token({
grant_type: 'authorization_code',
code: authCode,
}).then(async response => {
await admin.database()
.ref(`/accounts/${authCode}`)
.set(response);
return res.send("Well done, account integration is completed. You can now close the window and go back to the app");
});
});
The answer selected is not completely correct:
If you dont assign the account_id to a user then it's of no use.
The only way to pass the user_id (fUser.uid) is to pass it using the state parameter.
exports.StripePI = functions.https.onRequest(async (req, res) => {
// console.log('accountIdq ' + req.query.error);
// console.log('accountIdq ' + req.query.state);
// return;
// if(!req.query.code)
// return res.send("An Error has occured please try again");
const response = await stripe.oauth.token({
grant_type: 'authorization_code',
code: req.query.code,
}).then(async response => {
var connected_account_id = response.stripe_user_id;
await admin.firestore().collection('Registration').doc(req.query.state)
.update({customer_id : connected_account_id});
return res.send("Well done, account integration is completed. You can now close the window and go back to the app");
});
});
If you want to create an in-app stripe connect account registration with flutter you will need these:
A server or service to complete the OAuth like Firebase Functions or Integromat (I used Integromat)
A link that will redirect to your app (I used Firebase Dynamic Link)
STEPS TO CREATE THE REGISTRATION FLOW
INTEGROMAT/FIREBASE FUNCTIONS SETUP
I decided to use Integromat instead of Firebase Functions because is easier to set up, doesn't need any code, and decreases my server load.
If you want to create it on Firebase Functions you will need to have a Blaze Plan
If you don't know it, Integromat will automate processes that you currently handle manually, via webhooks. It is not only capable of connecting apps (like GoogleCloud, Facebook, AWS...) but can also transfer and transform data.
Create a new scenario and add a Custom Webhook. Click on it and click on add, name it, and save it. It will now create a custom link to your webhook.
Close and click on the semi-sphere next to the webhook, to add the new module.
Select HTTP and Make a Request.
In the URL section insert https://connect.stripe.com/oauth/token.
Method POST.
Body Type Application/x-www-form-urlencoded.
Create now those fields :
Key client_secret - value your stripe client secret You can find it on your stripe dashboard. I advise you to first use the test mode and after that, change the value to the live key.
Key grant_type - value authorization_code
Key code - leave the value blank. We will add it later.
Save and close
For Firebase Functions you can create a new HTTPS function (I didn't test this)
var stripe = require("stripe")(*your stripe client secret*);
exports.connectStripeStandardAccount = functions.https.onRequest((req, res) =>{
let authCode = req.query.code;
return stripe.oauth.token({
grant_type: 'authorization_code',
code: authCode,
});
});
Remember to install stripe package npm install stripe
STRIPE SETUP
If you are in the test mode go to this link
If you are in the live mode go to this link
Go on the bottom and activate oAuth for standard accounts or for Express Account.
Click on Add URI and add the webhook link of Integromat that you created or the link related to your Firebase function.
If you used Firebase add this link https://us-central1-<project-id>.cloudfunctions.net/connectStripeStandardAccount
For Integromat you will need to create the structure. To do this click on Test OAuth, copy the link, and open it in incognito mode. Open your Integromat scenario and click on your webhook. Now click on Re-determine data structure.
Return to your stripe registration page and click on Ignore account form at the top.
Return on Integromat and select the HTTPS request, modify the field code, and insert the variable code (will open a dialog with all queries from the webhook). Confirm and save.
Now click on the play button and reopen the stripe registration link in incognito mode and click on Ignore account form. Return in Integromat and add a JSON module after the HTTPS request. In the JSON string insert the Data variable and save. Create a Webhook Response module after the JSON module.
In the status put 301, then click on Ok.
DEEP LINK SETUP
It's time to set up the redirect link that will return the user to our flutter app or on our website if the user hasn't it installed.
I used Firebase Dynamic Link You can follow this tutorial for set up.
Go to the dashboard and create a new Link prefix and a new dynamic link, remember to select to redirect your users to the right app.
Click on the three dots in your dynamic link row and click on Link Details. Copy the extended link.
Open Integromat and select the last module you created (Webhook Response). Click on Show advanced settings and on the Header add :
Key Location - value the extended dynamic link that you copied.
If you want your app to elaborate data from the stripe OAuth response you can modify the extended dynamic link by adding ? on the link parameter: link=https://test.page.link?stripe_user_id={{14.stripe_user_id}}
And select the variable parsed from the JSON module. Remember to click on the save icon to save your scenario.
On Firebase Functions you can do this when the function stripe.oauth.token finish (I didn't test it):
res.setHeader('Location', your dynamic link);
res.status(301).send();
Remember to deploy it.
FLUTTER APP SETUP
The code here is very simple. To initialize the connect account registration you only need to set up a button that will launch the stripe connect URL. You can use launch(url);
You can find that URL here. Remember to be logged in to your stripe account to get the right stripe client id. You can easily get it in the same section you added the webhook link in your stripe connect settings.
Delete &redirect_uri=https://sub2.example.com on the URL.
Now you can test your app and will see that when you complete your stripe connect registration/login you will be redirected to your app.
If you want to have an in-app web view you can use this package
To handle the response, you need to have installed the package firebase_dynamic_links
Set your Main widget Stateful and on the initState run the method getDynamic() :
void getDynamic() {
FirebaseDynamicLinks.instance.getInitialLink().then((value) {
if (value != null) {
_connect(value);
}
});
FirebaseDynamicLinks.instance.onLink(onSuccess: (value) async {
if (value != null) {
_connect(value);
}
}, onError: (error) async {
debugPrint('DynamicLinks onError $error');
});
}
void _connect(value) {
Uri deepLink = value.link;
print("Link :" + deepLink.path);
print("Query :" + deepLink.queryParameters.toString());
String stripeUserId = deepLink.queryParameters["stripe_user_id"];
}
You need to have both of them to handle dynamic links when your app is running and when it's closed.

Actions on Google implicit account linking works in simulator/browser, but not on device (via Google Home app)

I've implemented the implicit flow for Actions on Google account linking, and am using Dialogflow (previously API.AI) to define intents.
The full flow works in the device simulator (from AOG). The first intent gets a "It looks like your account isn't linked yet..." response, and the debug pane includes a URL to initiate linking:
https://assistant.google.com/services/auth/handoffs/auth/start?account_name=[account]#gmail.com&provider=[project_id]_dev&scopes=email&return_url=https://www.google.com/
If I follow this URI in a cache-less window:
I'm redirected to my app's authentication page
I choose to sign in with my Google account (same as [account] above)
I'm redirected to google.com with a success message in the URI bar
The simulator now accepts actions via my app and responds correctly
However, if I follow the same flow using a physical Google Home & the gH app for Android.
Device tells me account not yet linked
Open Google home and follow 'Link to [my app]' link
Browser opens to authentication page
Sign in as user
Redirected to a white page with a single link "Return to app", which has an href: about:invalid#zClosurez
Linking was unsuccessful, so additional attempts to run intents on the Google Home get the same "Account not yet linked" response.
I've inspected the intermediate access_token and state variables at length, and they all match and look to be correctly formatted:
Authentication URL (app sign in page): https://flowdash.co/auth/google?response_type=token&client_id=[client_id]&redirect_uri=https://oauth-redirect.googleusercontent.com/r/[project_id]&scope=email&state=[state]
After authenticating, redirected to (this is the white screen with 'return to app' broken link): https://oauth-redirect.googleusercontent.com/r/genzai-app#access_token=[token]&token_type=bearer&state=[state]
So, it seems there's something non-parallel about the way the simulator and physical devices work in terms of implicit flow account linking.
I've been struggling with this, and with the AOG support team for a very long time to no avail. Anyone else see a similar issue?
Updated with response redirect code:
Login handled by react-google-login component with profile & email scopes. On success we call:
finish_auth(id_token) {
let provider = {
uri: '/api/auth/google_auth',
params: ['client_id', 'redirect_uri', 'state', 'response_type'],
name: "Google Assistant"
}
if (provider) {
let data = {};
provider.params.forEach((p) => {
data[p] = this.props.location.query[p];
});
if (id_token) data.id_token = id_token;
api.post(provider.uri, data, (res) => {
if (res.redirect) window.location = res.redirect;
else if (res.error) toastr.error(res.error);
});
} else {
toastr.error("Provider not found");
}
}
provider.uri hits this API endpoint:
def google_auth(self):
client_id = self.request.get('client_id')
redirect_uri = self.request.get('redirect_uri')
state = self.request.get('state')
id_token = self.request.get('id_token')
redir_url = user = None
if client_id == DF_CLIENT_ID:
# Part of Google Home / API.AI auth flow
if redirect_uri == "https://oauth-redirect.googleusercontent.com/r/%s" % secrets.GOOGLE_PROJECT_ID:
if not user:
ok, _email, name = self.validate_google_id_token(id_token)
if ok:
user = User.GetByEmail(_email, create_if_missing=True, name=name)
if user:
access_token = user.aes_access_token(client_id=DF_CLIENT_ID)
redir_url = 'https://oauth-redirect.googleusercontent.com/r/%s#' % secrets.GOOGLE_PROJECT_ID
redir_url += urllib.urlencode({
'access_token': access_token,
'token_type': 'bearer',
'state': state
})
self.success = True
else:
self.message = "Malformed"
else:
self.message = "Malformed"
self.set_response({'redirect': redir_url}, debug=True)
I am able to make it work after a long time. We have to enable the webhook first and we can see how to enable the webhook in the dialog flow fulfillment docs If we are going to use Google Assistant, then we have to enable the Google Assistant Integration in the integrations first. Then follow the steps mentioned below for the Account Linking in actions on google:-
Go to google cloud console -> APIsand Services -> Credentials -> OAuth 2.0 client IDs -> Web client -> Note the client ID, client secret from there -> Download JSON - from json note down the project id, auth_uri, token_uri -> Authorised Redirect URIs -> White list our app's URL -> in this URL fixed part is https://oauth-redirect.googleusercontent.com/r/ and append the project id in the URL -> Save the changes
Actions on Google -> Account linking setup 1. Grant type = Authorisation code 2. Client info 1. Fill up client id,client secrtet, auth_uri, token_uri 2. Enter the auth uri as https://www.googleapis.com/auth and token_uri as https://www.googleapis.com/token 3. Save and run 4. It will show an error while running on the google assistant, but dont worry 5. Come back to the account linking section in the assistant settings and enter auth_uri as https://accounts.google.com/o/oauth2/auth and token_uri as https://accounts.google.com/o/oauth2/token 6. Put the scopes as https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email and weare good to go. 7. Save the changes.
In the hosting server(heroku)logs, we can see the access token value and through access token, we can get the details regarding the email address.
Append the access token to this link "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" and we can get the required details in the resulting json page.
`accessToken = req.get("originalRequest").get("data").get("user").get("accessToken")
r = requests.get(link)
print("Email Id= " + r.json()["email"])
print("Name= " + r.json()["name"])`
Not sure which python middleware or modules you are using but
self.set_response({'redirect': redir_url}, debug=True)
seems to be setting parameters for a returning a response which isn't correct. Instead you should redirect your response to the redirect_url. For example importing the redirect module in Flask or Django like:
from flask import redirect or from django.shortcuts import redirect
then redirect like:
return redirect(redirect_url)
It appears Google has made a change that has partially solved this problem in that it is now possible to complete the implicit account linking flow outside of the simulator, in the way outlined in my question.
It seems the problem stemmed from an odd handling (on the AOG side) of the client-side redirect case used after sign in with the Google sign-in button.
From Jeff Craig in this thread:
The current workaround, where we provide the "Return to app" link
currently what we're able to provide. The issue is with the way that
redirecting to custom-scheme URIs is handled in Chrome, specifically,
with regard to the redirect happening in the context of a user action.
XHR will break that context, so what is happening is that you click
the Google Sign-In Button, which triggers an XHR to Google's servers,
and then you (most likely) do a client-side redirect back to the
redirect_url we supply, our handler executes, and isn't able to do a
JS redirect to the custom scheme URI of the app, because were outside
of the context of a direct user click.
This is more of a problem with the Implicit (response_type=token) flow
than with the authorization code (response_type=code) flow, and the
"Return to app" link is the best fallback case we currently have,
though we are always looking for better solutions here as well.
The current behavior shows the 'Return to app' link, but as of last week, this link's href is no longer about:invalid#zClosurez, but instead successfully completes the sign-in and linking process. It's an odd and confusing UX that I hope Google will improve in the future, but it was sufficient to get my app approved by the AOG team without any changes to my flow.

Codenameone browser issues with paypal checkout express

So I've been trying to find an API to integrate PayPal Payment into my Codename One App, except that I didn't find enough documentation to use the Purchase builtin feature. So I tried to use a WebView of a page hosted on my server and implemented using the paypal "checkout.js" Api.
When I load the page into Chrome, it works perfectly and the transaction is complete. But when I load it using the codename one BrowserComponent it gets stuck (See screenshot). What is the root of this problem ? Is it the fact that the browser does not support popus ? and Is there a way to fix it ?
Button payButton = new Button("Checkout");
payButton.addActionListener((ActionEvent evt) -> {
Form payForm = new Form("Payment", new BorderLayout());
WebBrowser webBrowser = new WebBrowser("http://localhost/paymentserver/web/app_dev.php/payerParticipation/5");
payForm.add(BorderLayout.CENTER, webBrowser);
payForm.show();
});
Screenshot
Try embedding firebug into the of your page to see if it reports any errors:
<script>
if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document'createElement' + 'NS' : document'createElement';E'setAttribute';E'setAttribute';E'setAttribute';(document'getElementsByTagName'[0] || document'getElementsByTagName'[0]).appendChild(E);E = new Image;E'setAttribute';}
</script>
Thanks for the help everybody,
I finally found a turnaround and implemented this feature on a PHP server using PayPal PHP SDK. I used the browser Navigation Callback in order to check when the payment was successful/failed.
browser.setNavigationCallback((url)->{
if (url.indexOf("success=true")!=-1){
System.out.println("Payment complete");
}
else if (url.indexOf("success=false")!=-1){
System.out.println("Payment failed");
}
return true;
});
I don't have an answer for that but I did implement Braintree support for Codename One which is the official PayPal mobile API. I have a cn1lib for it implemented but I didn't get around to publishing it because of the bootcamp. Keep an eye on the blog I'll probably publish it in the next couple of weeks.

Adaptive Payments without modal box or popups?

Is it possible to launch the payflow entirely inline (a la Express Checkout)? How?
We're using chained payments and everything works on non-iOS-mobile devices (and in Chrome for iOS), but we're making a web app, so we need this to work on phones. Testing on the iPhone, we have this problem with PayPal's code that I've already asked about, as well as the fact that when I get around that bug by doing a location.replace with the URL to PayPal (or loading it in a lightbox of my own design), iOS and mobile Safari kill the "Log In" popup (without giving the user an opportunity to view it if they so choose).
In short, is there any way I can use Adaptive Payments without ridiculous 1990s-era popups???
Here's what I'm doing to use PayPal's mobile web flow. I'm testing on Android and it's working well. The only hang up is the callbackFunction is not firing in mobile browsers and works fine in desktop browsers. (I'm still working on this part. Let me know if you solve it.) Here's an example on how to do it using expType=mini to launch the PayPal mini browser experience.
First include the Javascript for the Mini flow:
<script src="http://www.paypalobjects.com/js/external/apdg.js"></script>
Then a link to launch the redirect:
<a id="payPalRedirect" href="https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay?paykey={paykey}&expType=mini" target="_blank">Complete PayPal Payment</a>
<br /><br />
<div id="resultDiv"></div>
And some Javascript to initiate the Mini Flow process and the callbackFunction:
var returnFromPayPal = function () {
alert("Returned from PayPal");
var div = document.getElementById('resultDiv');
div.innerHTML = "Returned from PayPal!";
// Here you would need to pass on the payKey to your server side handle to call the PaymentDetails API to make sure Payment has been successful or not
// based on the payment status- redirect to your success or cancel/failed urls
}
var dgFlowMini = new PAYPAL.apps.DGFlowMini({ trigger: 'payPalRedirect', expType: 'mini', callbackFunction: 'returnFromPayPal' });
More insights and solution options to this issue can be found here:
Paypal Embedded Flow not using returnUrl or cancelUrl

how to send and receive data between phonegap child browser to main application

I'm working on a Facebook login authentication in a Phonegap child browser. For that externally I have a page that can initiate authentication process and redirects back after authentication (let's say www.mysite.com/Facebook.html). Now I have authentic user from Facebook, but how can I get that authentic user data from child browser to main application and close child browser. for security reason, I set "showLocationBar: false" , so there is no close button.
So, now let me know
how can I get Facebook authenticated user data (user email and access token for further transactions with Facebook) to main application and close child browser.
how to close child browser from child browser as I don't have close button on Child-browser.
is there any way to save data from Facebook to a JavaScript object in my main application
This is my first application with Phonegap, but im experienced with Facebook and JavaScript. So , please let me know if I'm wrong any where.
Thanks in advance,
Looking forward.
I am also using chilldbrowser for Facebook connect. Here is the link for complete source code for Facebook connect using childbrowser: http://www.drewdahlman.com/meusLabs/?p=88. You can get user's name using access_token using the code below:
var params='access_token='+accessToken;
$.get("https://graph.facebook.com/me",params,
function(response){
fbUesrName=response.name;
},"json");
You can close the childbrowser using:
window.plugins.childBrowser.close();
#Venkat : Not sure if you already got the answer for closing child browser from within app. This code worked for me. Put a close button on your site and put the URL as "google.com".From PG app you can write the code below
window.plugins.childBrowser.onLocationChange = function(locationLink){
if (locationLink.indexOf('google.com') > 0) {
window.plugins.childBrowser.close();
}
}