How can I handle Media sharing in my PWA app when sharing media from another app into my app? - progressive-web-apps

I am working on a Progressive web app that works on both web version and mobile version. I am sharing media files with others apps but when I share media from another app (Or any other social like Facebook, Messenger, LinkedIn) into my app after selecting my app it just opens up and turns into a black screen. I need help with how I can forward the screen into my share list screen and the data which is shared by another app how can I access them. Any Help?

Double check your method is "POST" and that enctype is present. enctype must be "multipart/form-data", and a files entry must be added in your manifest where you specify your share_target. files is an array that specifies the types of files your app accepts.
more info from: https://web.dev/web-share-target/
The foreground page cannot process this data directly. Since the page sees the data as a request, the page passes it to the service worker, where you can intercept it with a fetch event listener. From here, you can pass the data back to the foreground page using postMessage() or pass it on to the server:
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
// If this is an incoming POST request for the
// registered "action" URL, respond to it.
if (event.request.method === 'POST' &&
url.pathname === '/bookmark') {
event.respondWith((async () => {
const formData = await event.request.formData();
const link = formData.get('link') || '';
const responseUrl = await saveBookmark(link);
return Response.redirect(responseUrl, 303);
})());
}
});

Related

Open url and submitted data to app in flutter

I have a requirement ,in app I need to navigate the user to webview (website) and there will be a form with 5 fields and once the form is submitted a flag to be passed to app and app should work based on the flag .. So how it can be achieved
I have checked that there is a url_launcher or webview_flutter but i don know how to redirect the app once the form is submitted in website
I am not entirely sure if I understood the problem. But here is what can be done.
Open url in webview.
Now you should listen to webview state change. There must be a listener for this. say the listener is webViewStateChanged which will give you the state of webview.
Then you can check like
void webViewStateChanged(WebViewStateChanged newState) async {
if (newState.type != WebViewState.finishLoad ||
newState.url != desiredURL) {
return;
}
// At this point, you want to return to your app. If you need data from
// website, you can do so by accessing cookies of webview.
// Now you are back to the app, you can pop/replace the webview whatever
// is your requirement.

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.

Facebook Live Stream Static URL

I was curious as to if there is anyway to have a certain page on Facebook have a static URL for it's Live Streams. I want this so I can use that static URL and embed it on a website (Weebly or Wordpress). Does anyone know of a way to do this?
Any and all input is greatly appreciated.
Thanks much!
No, currently there is no such direct feature provided by Facebook to achieve what you want to do. But there is definitely an indirect way of doing this using Facebook Graph API.
Indirect method of doing so:
Use your page ID to get status of last live video of your page.
/Page_ID?fields=live_videos.limit(1){status}
If you get status field as 'LIVE', it means your video is still LIVE on your page. Then, use the returned Video Id of Live video to make next request.
You can get the embed html of the live video using this request:
/Video_ID?fields=embed_html
Use the returned embed_html to embed live video in your wordpress site.
You just need to write the script that executes the above task and embed video conditionally if the status of video is LIVE otherwise not.
This is a pretty old question, but here's my solution:
Make a GET request to https://facebook.com/PAGE_ID/live
Capture the redirect - this request redirects to the URL you want
How I did it in Node.JS
const https = require("follow-redirects").https;
const PageID = "nexe32"
let redirected = false;
https.get({
host: 'facebook.com',
path: `/${PageID}/live`,
headers: {
"User-Agent": 'curl/7.43.0'
},
beforeRedirect: (opts) => {
if(!redirected) {
redirected = true;
} else {
console.log(opts.href); // the URL you want
redirected = false;
}
}
});
``

Facebook Messenger Platform Setup

I have a general question regarding the setup for a "bot" in the Facebook Messenger Platform.
If I understand the architecture right, I can create an App as a developer add the Messenger function and associate 1 Page with the Messenger function.
Does this mean I need an app for each page ?
Or could I crete a "bot backend" serving multiple / different pages from different users ?
Yes, you can have one robot serving multiple pages. You just have to set <token> for different pages in API call, here is setup for a page. From documentation:
Graph API requires Page access tokens to manage Facebook Pages. They are unique to each Page, admin and app and have an expiration time.
Fritak is correct. You can use one app for multiple pages. For each page you will have to subscribe the app to that page and generate a page access token specifically for that page. At your webhook, you'll have to distinguish the callbacks for the specific page.
When you receive a request, you need to map the incoming page id to the access token as described in this answer: How can I use the same bot on multiple facebook pages using bot framework
app.post('/webhook', (req, res) => {
const data = req.body
// Make sure this is a page subscription
if (data.object === 'page') {
// Iterate over each entry
data.entry.forEach((pageEntry) => {
// get the pageId
const pageId = pageEntry.id
...
const accessTokens = {
myPageId1: 'myPageAccessToken1',
myPageId2: 'myPageAccessToken2',
}
const callSendAPI = (pageId, messageData) =>
rp({
uri: 'https://graph.facebook.com/v2.8/me/messages',
qs: { access_token: accessTokens[pageId] },
method: 'POST',
body: messageData,
json: true,
})

Deeplinking using GWT History Token within a Facebook iFrame Canvas

I would like to deep link directly to a GWT app page within a Facebook iFrame Canvas.
The first part is simple using GWT's History token with URLs like:
http://www.example.com/MyApp/#page1
which would open page1 within my app.
Facebook Apps use an application url like:
http://apps.facebook.com/myAppName
which frames my Canvas Callback URL
http://www.example.com/MyApp/
Is there a way to specify a canvas callback url (or bookmark url) which will take the user to a specific page rather than the index page?
Why? you may ask. Besides all the benefits of deep links...
I want the "Go To Application" url to take users to an index page w/ marketing material (the canvas callback url)
I want the "Bookmark URL" to take (likely returning) users to a login page and bypass downloading the marketing content (and that huge SWF file).
This may seem to be a hack but here it goes.
Facebook allows the application to tack on parameters to the url ?x=123
So I'm checking the window location to see if it contains my special 'page' parameter and loading that page. Below is my solution given that I'm using GWT + gwt-presenter's PlaceManager class.
The application deep url ends up being http://apps.facebook.com/myAppName?page=page1
EventBus eventBus = injector.getEventBus();
// Load PlaceManager so it can start listening
PlaceManager placeManager = injector.getPlaceManager();
String currentPlace = History.getToken();
String place = Window.Location.getParameter( "page" );
if (place != null && !place.isEmpty()) {
// send user to the place on the URL line
eventBus.fireEvent( new PlaceRequestEvent( new PlaceRequest( new Place (place) ) ));
} else if ("".equals(currentPlace)) {
// Nothing in URL, load default GWTpage
eventBus.fireEvent( new PlaceRequestEvent(new PlaceRequest( IndexPresenter.PLACE)));
} else {
// fire a body to the Place Manager to activate the requsted Place
placeManager.fireCurrentPlace();
}