IBM Connections Cloud custom contextual data - ibm-cloud

I followed the official documentation and created a minor community app for my website.
What I'd like to know is if there's a way "to shim" custom data to IBM Connections Cloud when uploading my app as a JSON and then retrieve it inside the message handler after my app loads:
window.addEventListener('message', function(event) {
if (event.origin === "https://apps.collabservnext.com"){
// event.data contains the full context
console.log("Running in community named " + event.data.source.resourceId);
}
}, false);
parent.postMessage("appReady", "*");
So far I'm only getting the extraContent, source and user JSON keys in event.data. It would be awesome if there was a way to retrieve say hello: world.
Thanks.

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.

POST to Salesforce API using Google Tag Manager and JSforce not working?

I want to use Google Tag Manager to send data to our Salesforce org for certain events on our website (user signup, conversion etc). After some research, I realized JSforce would be the easiest way to achieve this. I created a new connected app in Salesforce, tried out the Salesforce API using Postman and successfully managed to create a new user account via the API. Then I moved on to try and achieve the same thing in Google Tag Manager. I read JSforce's docs and attempted to implement everything. But, after multiple hours of troubleshooting and Google searching, I can't seem to make it work.
Here is my current code, which is in a 'tag' in Google Tag Manager that triggers on all pages (just for testing):
https://jsforce.github.io/start/#web-browser
<script src="//cdnjs.cloudflare.com/ajax/libs/jsforce/1.9.1/jsforce.min.js"></script>
<script>
jsforce.browser.init({
clientId: '<MYCLIENTID>',
redirectUri: 'https://cuttersclub.com'
});
https://jsforce.github.io/document/#access-token
var jsforce = require('jsforce');
var conn = new jsforce.Connection({
instanceUrl : 'https://um5.salesforce.com',
accessToken : '<MYACCESSTOKEN>',
});
https://jsforce.github.io/document/#create
conn.sobject("Account").create({ Name : 'My Account #1' }, function(err, ret) {
if (err || !ret.success) { return console.error(err, ret); }
console.log("Created record id : " + ret.id);
});
</script>
I'm getting this error in the browser console:
Uncaught ReferenceError: require is not defined
EDIT: Removing var jsforce = require('jsforce'); solved this problem and accounts are being created in Salesforce. But, now I am getting the following error in the browser console:
Access to XMLHttpRequest at '<URL>' from origin '<CALLBACKURL>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
As mentioned in the JSforce docs, I think it may be something to do with proxy servers: https://github.com/jsforce/jsforce-ajax-proxy
I don't know that much about salesforce, but "require" is something from node.js, not a function that is implemented in the browser.
If I understand the documentation correctly, then for a browser project it should be enough to call the jsforce script via a script tag. You should not need any way to "require" files after that, since the jsforce script already contains everything you need. So you should be fine if you just remove the offending lines (i.e. all references to "require('jsforce');").

How can I use Botkit Middleware with Watson Assistant dialog server actions?

I followed this tutorial to deploy a Slackbot with Watson Assistant. The tutorial uses server actions in the dialog to directly interface with a database. To connect Slack with Watson Assistant the tutorial uses the Conversation connector. That works fine, but I am interested in how to do the same with Botkit and the Botkit Middleware provided by Watson Developer Cloud.
How can I use the serverless actions, how do I obtain and pass the necessary API key?
There is actually code that demonstrates how to configure the API key for IBM Cloud Functions and pass it as context variable to Watson Assistant. It makes use of the before method to add the API key to the context variable. The value is configured in a separate file together with the other app-related credentials. The code tests whether the context variable and the key exist, else it is added:
middleware.before = function(message, conversationPayload, callback) {
// Code here gets executed before making the call to Conversation.
// retrieve API Key from environment and split it into user / password
var arr=process.env.ICF_KEY.split(":");
// check if context exists
if (typeof(conversationPayload.context) === 'undefined') {
var context={context: {}}
Object.assign(conversationPayload, context);
}
// if credentials already exists, we don't have to add them
// else add credentials under private element in context
if (typeof(conversationPayload.context.icfcreds) === 'undefined') {
var privcontext = {"private": {icfcreds: {user: arr[0], password: arr[1]}}};
Object.assign(conversationPayload.context, privcontext);
}
// log the payload structure for debugging
// console.log(conversationPayload)
callback(null, conversationPayload);
}

SAP Fiori Get logged in user details in UI5 application

I've a SAP Fiori application and I need to get the current logged in user details.
I've searched web but unable to find a solution.
is there any way to get current logged in user details from launchpad.
There is a UserInfo service from the FLP shell which can be retrieved like this:
{ // In Controller
doSomethingUserDetails: async function() {
const oUserInfo = await this.getUserInfoService();
const sUserId = oUserInfo.getId(); // And in SAPUI5 1.86, those became public: .getEmail(), .getFirstName(), .getLastName(), .getFullName(), ...
// ...
},
getUserInfoService: function() {
return new Promise(resolve => sap.ui.require([
"sap/ushell/library"
], oSapUshellLib => {
const oContainer = oSapUshellLib.Container;
const pService = oContainer.getServiceAsync("UserInfo"); // .getService is deprecated!
resolve(pService);
}));
},
}
To align with the current best practices, avoid calling sap.ushell.Container.getService directly!
getService is deprecated. Use getServiceAsync instead.
Require the library instead of referencing the Container via global namespace (sap.ushell.*) as shown above.
Alternatively, information about the the current user can be also retrieved via the user API service exposed by the application router from the SAP Business Technology Platform (SAP BTP).
* In case the app is deployed to the old Neo environment, see the previous edit.
The User-ID can be retrieved from SDK.
Please refer to class sap.ushell.services.UserInfo
Try this:
new sap.ushell.services.UserInfo().getId()
If you want to access the user detail when you are running your application in launchpad. then you can retrieve current user detail by adding following code snippet:
var userInfo = sap.ushell.Container.getService("UserInfo");
var email = userInfo.getEmail();
Then further detail about the user can be retrieved like email and fullname. See the API here.

How to wrap an existing chatbot for Google Assistant (Google Home)

We have a chatbot for our website today, that is not build using Google technology. The bot has a JSON REST API where you can send the question to and which replies with the corresponding answers. So all the intents and entities are being resolved by the existing chatbot.
What is the best way to wrap this functionality in Google Assistant / for Google Home?
To me it seems I need to extract the "original" question from the JSON that is send to our webservice (when I enable fullfilment).
But since context is used to exchange "state" I have to find a way to exchange the context between the dialogflow and our own chatbot (see above).
But maybe there are other ways ? Can it (invoke our chatbot) be done directly (without DialogFlow as man in the middle) ?
This is one of the those responses that may not be enough for someone who doesn't know what I am talking about and too much for someone who does. Here goes:
It sounds to me as if you need to build an Action with the Actions SDK rather than with Dialog flow. Then you implement a text "intent" in your Action - i.e. one that runs every time the user speaks something. In that text intent you ask the AoG platform for the text - see getRawInput(). Now you do two things. One, you take that raw input and pass it to your bot. Two, you return a promise to tell AoG that you are working on a reply but you don't have it yet. Once the promise is fulfilled - i.e. when your bot replies - you reply with the text you got from your bot.
I have a sample Action called the French Parrot here https://github.com/unclewill/french_parrot. As far as speech goes it simply speaks back whatever it hears as a parrot would. It also goes to a translation service to translate the text and return the (loose) French equivalent.
Your mission, should you choose to accept it, is to take the sample, rip out the code that goes to the translation service and insert the code that goes to your bot. :-)
Two things I should mention. One, it is not "idiomatic" Node or JavaScript you'll find in my sample. What can I say - I think the rest of the world is confused. Really. Two, I have a minimal sample of about 50 lines that eschews the translation here https://github.com/unclewill/parrot. Another option is to use that as a base and add code to call your bot and the Promise-y code to wait on it to it.
If you go the latter route remove the trigger phrases from the action package (action.json).
So you already have a Backend that process user inputs and sends responses back and you want to use it to process a new input flow (coming from Google Assistant)?
That actually my case, I've a service as a Facebook Messenger ChatBot and recently started developing a Google Home Action for it.
It's quite simple. You just need to:
Create an action here https://console.actions.google.com
Download GActions-Cli from here https://developers.google.com/actions/tools/gactions-cli
Create a JSON file action.[fr/en/de/it].json (choose a language). The file is your mean to define your intents and the URL to your webhook (a middleware between your backend and google assistant). It may look like this:
{
"locale": "en",
"actions": [
{
"name": "MAIN",
"description": "Default Welcome Intent",
"fulfillment": {
"conversationName": "app name"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"Talk to app name"
]
}
}
}
],
"conversations": {
"app name": {
"name": "app name",
"url": "https://your_nodejs_middleware.com/"
}
}
}
Upload the JSON file using gactions update --action_package action.en.json --project PROJECT_ID
AFAIK, there only a Node.js client library for Actions-on-google https://github.com/actions-on-google/actions-on-google-nodejs that why you need a Node.js middleware before hitting your backend
Now, user inputs will be sent to your Node.js middleware (app.js) hosted at https://your_nodejs_middleware.com/ which may look like:
//require express and all required staff to build a Node.js server,
//look on internet how to build a simple web server in Node.js
//if you a new to this domain. const {
ActionsSdkApp } = require('actions-on-google');
app.post('/', (req, res) => {
req.body = JSON.parse(req.body);
const app = new ActionsSdkApp({
request: req,
response: res
});
// Create functions to handle requests here
function mainIntent(app) {
let inputPrompt = app.buildInputPrompt(false,
'Hey! Welcome to app name!');
app.ask(inputPrompt);
}
function respond(app) {
let userInput = app.getRawInput();
//HERE you get what user typed/said to Google Assistant.
//NOW you can send the input to your BACKEND, process it, get the response_from_your_backend and send it back
app.ask(response_from_your_backend);
}
let actionMap = new Map();
actionMap.set('actions.intent.MAIN', mainIntent);
actionMap.set('actions.intent.TEXT', respond);
app.handleRequest(actionMap); });
Hope that helped!
Thanks for all the help, the main parts of the solution are already given, but I summarize them here
action.json that passes on everything to fullfilment service
man in the middle (in my case IBM Cloud Function) to map JSON between services
Share context/state through the conversationToken property
You can find the demo here: Hey Google talk to Watson