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

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');").

Related

How to interact with html response from http request in Flutter

I have a Flutter app where I am running a Google Apps Script through an http request. The purpose of the script is to create a Form and link the responses to a spreadsheetID that is passed in. The script is configured to only allow Google accounts access it and I've set up the flutter app to use a Service Account to access the script using the format:
getCredentials().then( (AuthClient client){
response = client.get(url, headers{"Authorization": "Bearer ${client.access_token}");
});
Issue: The issue is that the first time that the Service Account makes a request it will get an HTML response saying that it the account needs to give permission to the script to access its data and I'm not sure how to do that.
I'm fairly new to making http requests and using it with the GoogleAPI so I'm stuck. Any advice?
Goal
Create a web page which anyone can use to submit a Google sheet link and for the app to create a form and link the sheet to that.
Authorization
For this users will require a google account and they will be required to go through the OAuth process to authorize your app.
To create the form and link it from client-side JavaScript you would indeed need to call the Apps Script API, though you cannot do this with a service account.
From: https://developers.google.com/apps-script/api/how-tos/execute
Warning: The Apps Script API doesn't work with service accounts.
Luckily, you don't need a service account to do this.
Instructions
Create an Apps Script project with a function something like:
function createForm(ssID){
form = FormApp.create("Your New Form");
form.setDestination(FormApp.DestinationType.SPREADSHEET, ssID);
let formLink = form.getPublishedUrl();
return formLink;
}
Save and take a note of the ID of the script project.
Set up a GCP project (sounds like you already have one).
Make sure the Apps Script API is enabled in your GCP.
Configure the OAuth consent screen and add the scope - https://www.googleapis.com/auth/forms.
Create an API key and a Client ID - add http://localhost:8000 or whatever port you are testing on to the "Authorized JavaScript Origins"
Create OAuth credentials "web browser (JavaScript)".
Link your Apps Script project to the same GCP project - Instructions
Deploy the Apps Script project as an API executable - take not of the deployment ID, although the documentation says that you need the script ID, it is wrong, at least with the new Apps Script IDE.
Write the client-side JavaScript in your app like what is found in the quickstart. Which will enable users to authorize the app. You need to add in the scopes and keys there too. I recommend just following the quick start steps first to get a feel for it. You can use the authorization parts without modification.
Then add in the function that will call your Apps Script, something like this:
function appsScriptCreateForm(ssId) {
var scriptId = "<DEPLOYMENT_ID>";
// Run your Apps Script function
gapi.client.script.scripts
.run({
scriptId: scriptId,
resource: {
function: "createForm",
parameters: [ssId],
},
})
.then(function (resp) {
var result = resp.result;
// ERROR HANDLING
if (result.error && result.error.status) {
appendPre("Error calling API:");
appendPre(JSON.stringify(result, null, 2));
} else if (result.error) {
var error = result.error.details[0];
appendPre("Script error message: " + error.errorMessage);
if (error.scriptStackTraceElements) {
appendPre("Script error stacktrace:");
for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
var trace = error.scriptStackTraceElements[i];
appendPre("\t" + trace.function + ":" + trace.lineNumber);
}
}
// IF SUCCESSFUL
} else {
console.log("success", resp);
}
});
}
Write your HTML with the buttons and inputs necessary.
Add event listeners where appropriate.
Profit!
Please note
This set up is your project running with the authorization of other accounts.
The API requests count against your quota.
You can see details of all the executions in your GCP Project Dashboard.
Users require a Google account and need to authorize the app.
In the Apps Script function above, you just need to pass in the Spreadsheet ID. Not the whole link. You could ask for the whole link and then use Regex to extract the ID if you wanted.
This can be quite tricky and easy to miss a step or make a mistake, so double check your work.
If, after successful authorization, when trying to run the script you get a 404 error, the request has been built wrong, check your IDs. If you get a 500 error, that can mean that the Apps Script function has successfully been called, but, there was an error within Apps Script and failed, check the executions page of the Apps Script editor.
References
Apps Script How to Execute
Apps Script JS Quickstart - Highly recommended you follow these steps first and get that working!
How to link your Apps Script to GCP

Running Google Apps Script through https request with Service Account credentials

I'm working on a Flutter app. And I've been trying to run my web-app Google Apps Script through http request since I'm required to use a Service Account and that access isn't supported in the Apps Script API. But I keep getting a 403/Forbidden response to the requests. I have the credentials for the Service Account and I am using its access token in my request but it still doesn't work.
I'm a novice at http requests and new to Google's authentication protocols so I'd appreciate some insight.
Thanks in advance.
Code:
return await driveUtils.getCreds(context).then((creds) async {
final drive_scopes = [drive.DriveApi.DriveReadonlyScope, "https://www.googleapis.com/auth/drive.file"];
final script_scopes = [app_scripts.ScriptApi.ScriptDeploymentsScope];
return await clientViaServiceAccount(creds, script_scopes+drive_scopes).then((AuthClient client) async {
debugPrint("url = " + url);
debugPrint("token = " + client.credentials.accessToken.data);
return await client.get(url,
headers: {
"Authorization": "Bearer ${client.credentials.accessToken.data}"
}
);
}, onError: onClientError);
}, onError: onCredsError);
Background: The script creates a Form and sets it Destination to a Spreadsheet's ID. Hence, the app requires that anyone who runs it to have a Google account to become the owner of the new Form and obtain access to the Sheet.
Update: It seems that Service Accounts can only access scripts that are within the same Google Cloud Project. This is a big issue since the point of the script is to create a central place for acquiring Form creation functionality for my app. And the app is intended to be used by anyone.
Does anyone have any ideas? Assuming a Service Account is the right Google Credentials for my app, I essentially need the ability to:
Create a Form that can be assigned to a user
Designate a user's spreadsheet as the forms response location
Retrieve the forms publishedURL
#Tanaike helped me figure out the issue. In order to make the script visible and able to run with a Service Account I had to change the Share setting for viewing the script. Simple solution

Is there a way to get a users Bitmoji using Access tokens from Snapkit login web api?

I am attempting to use the snapkit login web api for a hybrid application. I have successfully been able to intercept the access token in the redirectURL. I was wondering if there was a way to get the users Bitmoji using this access_token and either the functions found in login.js or an http get call?
Api docs: https://docs.snapchat.com/docs/login-kit/#web
currently I have the access_token in a deeplinking function on my app.component.ts . I have attempted to push to a new page with the navController and passing in the access_token as a parameter, but this doesn't help when attempting to get the users information.
Thanks in advance for your help.
Here is the Deeplinking where I intercept the access_token using myapp://settings-set/ as the URL redirect and attempt to push a new page with the matching url.
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
this.deeplinks.routeWithNavController(this.nav,{
'/settings-set/:token': SettingsSetPage
}).subscribe((match) => {
// match.$route - the route we matched, which is the matched entry from the arguments to route()
// match.$args - the args passed in the link
// match.$link - the full link data
this.nav.push(SettingsSetPage, {
args: match
});
console.log('Successfully matched route', match.$args);
},
(nomatch) => {
// nomatch.$link - the full link data
console.error('Got a deeplink that didn\'t match', nomatch);
});
});
}
In the setting-set page I recieve the parameter using:
this.args = navParams.get('args');
console.log("this is args", JSON.stringify(this.args));
but don't know how to use the information to get the users information
The Bitmoji API can be very confusing at times. I suggest using Passport, a Node JS tool for OAuth, along with the Ionic framework. Snapchat has a guide that explains how to grab specific fields, such as user name and Bitmoji avatar, from a user's Snapchat profile using passport. You can follow this tutorial to learn how to integrate Node JS into your existing ionic app.
So in conclusion, try following these steps:
Integrate Node JS into your existing ionic app
Install Passport and follow Snapchat's guide for obtaining specific fields from the user's profile
Yes, like Mora said you can use passport which will make your life easier. We also have a sample passport app running here:
From the context you provided it seems like you have generated the code and not the access_token. After you get the code from the redirect url, you need to use the code to generate the access token. Check section 2.5 here.
Once you have the access token you can use that to request information. The crux of this lies in setting the "scope" correctly. To get the Bitmoji avatar make sure you set your scope to this at the very least:
var scope = ['https://auth.snapchat.com/oauth2/api/user.bitmoji.avatar'];
Hope this helps!

Google places api error in ionic 2

I am using google places api in ionic app.I places google places api script in index.html. The app allow the user to access wifi within specific place. User get internet access after login with our app. When application launch and user is connecting with our network, user do not have access to the internet. So i get error:
Application Error connection to the server was unsuccessful.
Is there anyway to call the google places api after user has access to the internet to avoid the error?
This has been quickly tested in ionic 1 and it works, no reason it shouldn't in ionic 2. But if you know a proper way to add the script tag in angular, just replace this part. The logic is simply to add your resource on the fly to index.html. Don't forget that connexion can appear while app is already started, and that you don't need to add the tag twice (verifications have to be done). Some edits might be done to adapt to ionic 2, sorry my version was made on the 1.
the function to add the script:
function addScriptTag(){
//STORE HERE VALUE TO VERIFY SCRIPT HAS ALREADY BEEN ADDED
var script = document.createElement('script');
script.src = 'http://maps.google.com...';
script.type = 'text/javascript';
document.head.appendChild(script);
}
in $ionicPlatform.ready (network is not available before that)
//CONNECTED AT APP LOADING
var networkState = navigator.connection.type;
if(networkState !== Connection.NONE){
addScriptTag();
}
//IN CASE CONNEXION ARRIVES LATER
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
if( /* VERIFY SCRIPT NOT ADDED BEFORE */ ){
addScriptTag();
}
}, false);

Facebook API: FB.Connect.requireSession issues

I have a Facebook app that is built as an iFrame. I am using the JavaScript client API loaded via:
http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php
In my initialization code, I use the requireLogin method to ensure that the user has authorized the app. I have found this to be necessary to be able to gather the user's name, avatar, etc. for the scoreboard. Here's a representative code snippet:
FB_RequireFeatures(["Connect","Api"], function() {
FB.Facebook.init("...API_KEY_HERE...", "xd_receiver.htm");
var api = FB.Facebook.apiClient;
api.requireLogin(function() {
api.users_getInfo(
FB.Connect.get_loggedInUser(),
["name", "pic_square", "profile_url"],
function(users, ex) {
/* use the data here */
});
});
});
This causes the iframe to redirect causing the Facebook authorization screen to load within my app's iFrame. This looks junky and is somewhat confusing to the user, e.g. there are two Facebook bars, etc.
Question 1: is there anything I can do to clean this up while still implementing as an iFrame, and still using the JavaScript APIs?
According to the FB API documentation:
FB.ApiClient.requireLogin
This method is deprecated - use
FB.Connect.requireSession instead.
My experience though when I replace api.requireLogin with FB.Connect.requireSession it never gets invoked. I'd prefer the recommended way of doing it but I struggled and was not able to find a way to get it to work. I tried adding various arguments for the other two parameters as well with seemingly no effect. My expectation is that this method will load in a dialog box inside my app iFrame with a similar authorization message.
Question 2: what am I missing with getting FB.Connect.requireSession to properly prompt the user for authorization?
Finally, at the end of the game, the app prompts the user for the ability to publish their score to their stream via FB.Connect.streamPublish. Which leads me to...
Question 3: am I loading the correct features? Do I need both "Api" and "Connect"? Am I missing any others?
Here is a summary of the changes I needed to make to clean up the authorization process. It appears that iFrames must fully redirect to properly authorize. I tried using the FBConnect authorization but it was a strange experience of popup windows and FBConnect buttons.
Ultimately this game me the expected experience that I've seen with other FB apps:
FB_RequireFeatures(["Connect","Api"], function() {
var apiKey = "...",
canvasUrl = "http://apps.facebook.com/...";
function authRedirect() {
// need to break out of iFrame
window.top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key="+encodeURIComponent(apiKey)+"&next="+encodeURIComponent(canvasUrl)+"&canvas=";
}
FB.Facebook.init(apiKey, "xd_receiver.htm");
FB.ensureInit(function() {
FB.Connect.ifUserConnected(
function() {
var uid = FB.Connect.get_loggedInUser();
if (!uid) {
authRedirect();
return;
}
FB.Facebook.apiClient.users_getInfo(
uid,
["name", "pic_square", "profile_url"],
function(users, ex) {
/* user the data here */
});
},
authRedirect);
});
For iFrames, the solution was ultimately to redirect to the login URL which becomes the authorization URL if they are not already logged in.
I think that FB.requireSession only works from a FB connect site outside of
Facebook. If you're using an app hosted on apps.facebook.com use the php api
call instead,
$facebook = new Facebook($appapikey, $appsecret);
$facebook->require_login();
or link to the login page.
Of these methods to login
* Using the PHP client library
* Directing users to login.php
* Including the requirelogin attribute in a link or form
* Using FBML
only the first 2 are available to iframe apps hosted on apps.facebook.com
I think requirelogin and fbml only work with fbml canvas apps.
see
http://wiki.developers.facebook.com/index.php/Authorization_and_Authentication_for_Canvas_Page_Applications_on_Facebook
Question 1: is there anything I can do
to clean this up while still
implementing as an iFrame, and still
using the JavaScript APIs?
Question 2: what am I missing with
getting FB.Connect.requireSession to
properly prompt the user for
authorization?
Please have a look at this. This article discusses correct use of require session and provides links on how to implement that. And yes, you are right, the requireLogin has been deprecated and won't help any more.
Question 3: am I loading the correct
features? Do I need both "Api" and
"Connect"? Am I missing any others?
As far as I know, you can use both API and Connect together, basically you access Facebook's API with the help of JavaScript.
For iframe apps however, there is no great help and minimum support of API with some handful functionality available. See this for more info.
This causes the iframe to redirect
causing the Facebook authorization
screen to load within my app's iFrame.
This looks junky and is somewhat
confusing to the user, e.g. there are
two Facebook bars, etc.
Finally and personally I have not seen any iframe app requiring user to add the app first. This will create the problem of two bars you mentioned as quoted above.
The link I posted at the beginning of my answer has some useful links to get you started and decide the next-steps or possibly making changes to your apps.