i am trying to Post the player ID from onesignal to a caspio table. I have read dozens of forums etc and cant seem to get it right. Any Ideas? Custom is the Existing parameter for username on this page that i want sent along with the user id.
OneSignal.push(function() {
OneSignal.on('subscriptionChange', function (isSubscribed) {
if (isSubscribed) {
OneSignal.getUserId(function(userId) {
$.post(https://xxxxxxxx.caspio.com/rest/v1/tables/User_ID_Test/rows,( User_ID = 'userId' User_Name = '[#custom]' ), function (data));
});
}
});
Before doing a POST call to Caspio API, you must generate an access token. I will share an AJAX solution which may represent security issues due to you are exposing your secret and client keys, also every call would generate a new token but it could be useful for any non tech user looking for an easy solution.
If you want a more robust solution, I could recommend the following service: Caspio API Library
At this point in time, v2 of Caspio API has been released so I am using this latest version of Caspio Rest API. The steps to run a POST call to Caspio service are these:
Include jQuery in your web page head section or in your caspio datapage header. Do not include it in both as it may cause conflicts and it could increase the loading time of your page. Help to include jQuery in your project
Generate an access token from Caspio API.
Caspio Documentation / $.post() jQuery Documentation
Run the POST call. Full Caspio API documentation
Complete code is shown bellow
<script>
var cbIntegrationId = "<your-integration-id>"; //Required
var clientId = "<your-client-id>"; //Required
var clientSecret = "<your-client-secret>"; //Required
var tableName = "<table-name>"; //Required
//Get access token
$.post(
"https://" + cbIntegrationId + ".caspio.com/oauth/token",
{
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret
},
function(cbAuth){
//Run POST call
$.ajax({
url: "https://" + cbIntegrationId + ".caspio.com/rest/v2/tables/" + tableName + "/records?response=rows",
type: 'POST',
data: '{"<field1>": "<value-to-be-inserted>", "<field2>": "<value-to-be-inserted>"}', //Define record values
headers: {
"Authorization": "Bearer " + cbAuth.access_token, //Extracts the access token from the initial authorization call
"Content-Type": "application/json", //Required, otherwise 415 error is returned
"Accept": "application/json"
},
dataType: 'json',
success: function (data) {
console.log(data.Result); //Check the console to view the new added row
},
error: function(data) {
console.log(data.responseJSON); //Check the console to view error message if any
}
});
}
);
</script>
I strongly recommend taking a look at this article. Please read about Permissions for your API profile(s)
Related
I am making a simple website where I have to save some of my data to sharepoint list. I am using only html css js only. I need to make REST calls to Sharepoint APIs to post data on SP. I am trying to get data from my list(in SP) as follow:
$(document).ready(function() {
processListItems(hostweburl, 'ListName');
});
function processListItems(url, listname) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
It returns this response:
"{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}"
I am referencing only two scripts:
<script src="js/jquery-3.1.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
It says I am unauthorised to access. Although I am having admin rights to my list. Please tell me how to fix this issue. Do I need any authorization header for ajax call to Rest Api? I am new to Sharepoint. Please Help!
I think that custom scripting is disabled by default in SPOnline. You may have to enable it. These links may help:
Access denied office 365 / SharePoint online with Global Admin account
http://vamsi-sharepointhandbook.blogspot.com/2015/07/turn-scripting-capabilities-on-or-off.html
When you are trying to pull items from a list, specify the URL up to items. See below line for syntax -
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('"+listName+"')/items",
// Rest of the code
});
Yes you would need a authorization header for your requests. So your headers should be like this:
headers: {
"Accept": "application/json; odata=verbose",
"Authorization": 'Bearer '+ **access_token**
}
access_token: You would need to acquire access token to make requests. You can use adal library provided by Microsoft for that.
Here is the link to the Web API notes on how to create a new playlist. https://developer.spotify.com/web-api/create-playlist/
As far as I understand, the POST requests the url https://api.spotify.com/v1/users/{user_id}/playlists. This is requested while passing the access token and data. The content type of the data being 'application/json'.
For some reason this is failing and returning a Error 403 (Forbidden) in the console.
Anything I'm missing?
//(playlistName, userId, accessToken) are passed to this.
var urlString = 'https://api.spotify.com/v1/users/' + userId + '/playlists';
var jsonData = {
"name": playlistName,
"public": false
};
$.ajax({
type: 'POST',
url: urlString,
data: jsonData,
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
},
contentType: 'application/json',
success: function(result) {
console.log('Woo! :)');
},
error: function() {
console.log('Error! :(');
}
})
Having tried your example, I get a 401 unauthorized when filling in bogus data. So you are authorized, but the API really does not grant you the rights (403 forbidden).
Please have a look at the authorization guide. I am pretty sure, your error is there. Especially have a look at scope. You might simply not grant enough power in the login. And therefore ending up with only public access, which does not include adding playlists.
I cite form the API docs:
To be able to create private playlists, the user must have granted the
playlist-modify-private scope.
https://developer.spotify.com/web-api/authorization-guide/
I've already had a look around and i can't seem to find an answer to this, I'm needing my access token to last longer than the 2 hours that it currently does. unless you are able to suggest another method of getting a json result. Thanks
Heres my code
//first define a function
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://graph.facebook.com/v2.3/147733805246675?fields=posts&access_token=CAACEdEose0cBALZA1JuPZCO5MW3WZAX2ERa3RJ7PA5QKawTRGH9Yg0tdv4ENVJeZAqFchh9mNJuHu75gKv6QkHj63ezAZBGUm1OnpHWurJM4Aa0J71hFsCr27ZCSz43IuYs7QoBomtHVJCiex6ZBRZAovNybDf5XhfyaPNt5CHhvAhnoSZAXFO8q8c2na1ndztlp1zY2ftvsc9QVZCboEwdLAQnZA4zejYvM7kZD',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.posts.data.length; i++) {
var section = json.posts.data[i].message;
$("#tableid").append("<tr><td style='width:70px'><img id='theImg' src='img/fb.png'/></td><td><b>" + section +
"</b></td></tr>");
}
},
error: function(error) {
console.log(error);
}
});
The Javascript SDK will handle all token-related logic for you. Why do you want to have a long-lived token in the browser?
You should use the Javascript SDK and the features it provides. The only use-case to generate long-lived tokens yourself is if you want to make API calls from your server.
Since extending and token involves sending over your App Secret, you should not do that in the browser; your app secret should only be on your server.
I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.
I am using a function from Spotify Playlist Creator in my file to send a POST request to the API to create a new playlist. The function works fine when i run the "Spotify Playlist Creator" code, with the POST request returning a response object with a new playlist id. But the same POST request returns "400 : Bad Request" when run from my code.
Other GET requests (user profile requests) are working fine (and hence i am guessng the authorization flow is successful and the access_token is valid.)
When i used the Chrome inspector, one thing that i noticed is that in the working app, the POST url is Request URL:https://api.spotify.com/v1/users/121856107/playlists
In my app it is Request URL:https://api.spotify.com/v1/users/121856107/playlists?{%22name%22:%22test_playlist%22,%22public%22:false}
Here the url has the data elements appended to it. Why is this happening? Any pointers ?
Below i have pasted the function which is behaving differently in two different sites.
Update: It appears that the POST request is somehow converted to OPTIONS. A quick search showed that this behaviour might be related to "Same origin policy".
How do i get my function to start working?
function createPlaylist(username, name, callback) {
var url = 'https://api.spotify.com/v1/users/' + username +
'/playlists';
$.ajax(url, {
method: 'POST',
data: JSON.stringify({
'name': name,
'public': false
}),
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + g_access_token,
'Content-Type': 'application/json'
},
success: function(r) {
console.log('create playlist response', r);
callback(r.id);
},
error: function(r) {
callback(null);
}
});
}