How can I authenticate the Microsoft translate API and gt it working on my localhost ?
I have attempted to use my microsoft primary key and client_id to no avail. I really have no clue. Help!!
**note: ** the client.setRequestHeader() method below.
Thanks in advance.
function _translate(text, to, from){
var promise = new Promise(function(resolve, reject){
var API = "https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/translate?" +
"Text=" + encodeURIComponent(text) +
"&To=" + encodeURIComponent(to) +
"&From=" + encodeURIComponent(from);
var client = new XMLHttpRequest();
client.open('POST', API, true);
client.setRequestHeader('Authorization', 'Basic ' + 'what-goes-here-exactly??');
client.onload = function(){
if (client.status >= 200 && client.status > 300){
resolve(client.responseText);
}else{
reject(client.response);
}
};
client.error = function(){
reject(client.response);
};
client.send();
});
return promise;
}
_translate("I love pizza", 'en', 'es')
.then(function(translation){
alert(translation);
});
According to this msdn page you would set the header as follows:
client.setRequestHeader('Authorization', 'Bearer ' + your_access_key);
You obtain your access token by following these instructions, in short:
Subscribe to the Microsoft Translator API on Azure Marketplace
Register your application Azure DataMarket
Make an HTTP POST request to the token service
Related
So i have this project to access my ip cam stream through a website, but my camera interface has a header basic authentication.
I tried to use user credentials in my url but it doesnt work :
http://username:password#192.168.my-ip/
Also my password contains "#" so i encoded them with %40 and tried %2540 (for the encoding of %) too, doesnt work either.
I saw that maybe a JS post request like this could do the trick but i don't know where to find the clientSecret :
var clientId = "MyApp";
var clientSecret = "MySecret";
// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
var authorizationBasic = window.btoa(clientId + ':' + clientSecret);
var request = new XMLHttpRequest();
request.open('POST', oAuth.AuthorizationServer, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("username=John&password=Smith&grant_type=password");
request.onreadystatechange = function () {
if (request.readyState === 4) {
alert(request.responseText);
}
};
today i started learning js with api and i want to ask how to fix this.
I registred on fortnite tracker and created api.
api is like:
GET https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname}
and api key is like:
TRN-Api-Key: xxxxxxx-xxxxxxxxxxx-xxxxxxxxxx
I found something here that i need to do it:
var xhttp = new XMLHttpRequest();
xhttp.request("GET", "api", true);
xhttp.setRequestHeader('TRN-Api-Key' "KEY");
xhttp.send();
but when i do it like this, it will show me error CORS and i don't know how ti fix that.
Thanks <3
i think you need to set these headers to allow cors origin
var xhttp = new XMLHttpRequest();
xhttp.request("GET", "api", true);
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xhttp.setRequestHeader('Access-Control-Allow-Headers', '*');
xhttp.setRequestHeader('Access-Control-Allow-Methods', '*');
xhttp.setRequestHeader('TRN-Api-Key' "KEY");
xhttp.send();
I didn't found solution for this api so i looked for other apis.
i found Fortnite api by https://fortniteapi.com/
name api is:
https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=YOUR_NAME
example name api:
https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=Ninja
there you get UID. You copy that UID and place it to this api with platfrom (pc,ps4)
https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=UID&platform=pc
example stats api:
https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=4735ce9132924caf8a5b17789b40f79c&platform=pc
JS CODE:
/* your uid and platform */
let uid = "4735ce9132924caf8a5b17789b40f79c";
let platform = "pc";
/* fortnite api link provided by <fortniteapi.com> */
let statApi = "https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=" + uid + "&platform=" + platform;
httpRequestAsync(statApi, theResponse);
/* getting response from API and defining variables */
function theResponse(response){
console.log("getting stats of " + uid);
let jsonObject = JSON.parse(response);
//example of getting data from api
console.log("Name: " + jsonObject.username);
console.log("Wins: " + jsonObject.totals.wins);
console.log("Kills: " + jsonObject.totals.kills);
console.log("K/D: " + jsonObject.totals.kd);
console.log("Matches: " + jsonObject.totals.matchesplayed);
console.log("Winrate: " + jsonObject.totals.winrate + "%");
};
/* sending XMLHHttpRequest api */
function httpRequestAsync(api, callback){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", api, true);
httpRequest.send();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
hope that will help someone
I am trying to get the locations list of a user with Google My Business Javascript API (https://developers.google.com/my-business/quickstarts/javascript). A user logs in successfully with his google credentials and oauth token is generated. But When I am trying to get the locations--->
var apiKey = 'xxxxxxxxxxxxxx';
var clientId = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var gmb_api_version = 'https://mybusiness.googleapis.com/v4';
let user = gapi.auth2.getAuthInstance().currentUser.get();
let oauthToken = user.getAuthResponse().access_token;
let xhr = new XMLHttpRequest();
let req = gmb_api_version + '/' + 'accounts/' + user.getId() + '/locations';
xhr.responseType = 'json';
xhr.open('GET', req);
xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken);
xhr.send();
I am getting null in xhr.response object.
It is somehow late to answer but in case somebody needs:
If you do not have the error then probably, just the account has no locations. first check the google response in [https://developers.google.com/oauthplayground/], trying to see if you have the different response.
I tried to access my OAuth2 Token via XHR-Request in TypeScript. I keep getting either 400: {"error":"unsupported_grant_type","error_description":"Grant Type is NULL"}
I am making my call via a NativeScript Application (in TypeScript Template) running on an iOS emulator.
My code:
var oReq = new XMLHttpRequest();
oReq.open("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", true);
// oReq.withCredentials = true;
// oReq.setRequestHeader('grant_type', "client_credentials");
// where client_credentials = clientID:secret
oReq.setRequestHeader('Authorization', "Basic " + this.authorizationBasic);
//where AutorizationBasic is the base64 String of my credentials
oReq.setRequestHeader('Accept', "application/json");
oReq.setRequestHeader('Accept-Language', "en_US");
oReq.onreadystatechange = function () {
console.log("state changed - new state: " + oReq.readyState + " and Status: " + oReq.status);
if (oReq.readyState === 4) {
if (oReq.status === 200) {
console.log(oReq.responseText);
} else {
console.log("Error: " + oReq.status + " Message: " + oReq.responseText);
}
}
};
console.log("Status: " + oReq.status);
oReq.send();
After doing some research I found out, that some others had the same issue with the PayPal API (e.g. here). Did someone solve that issue? Is it perhaps my code that is just wrong? In the code above I commented some other things that I tried, nothing seems to work.
The API:
https://developer.paypal.com/docs/integration/direct/make-your-first-call/
I am trying quite desperately since this is taking far too long to simple call that API. I tried the curl-command with my clientID + secret, which worked for me. Does anyone have an idea what to do? Is there perhaps an easier way than using XHR?
If someone else is searching for this:
You need to provide the Grant Type as the body in xhr.send()-Method:
xhr.send('grant_type=client_credentials');
I'm trying to add a user who clicks on a button in a SharePoint (online) site to a Office 365 group. I know this can be done via JSON using the Add Member API.
https://github.com/OfficeDev/microsoft-graph-docs/blob/master/api-reference/v1.0/api/group_post_members.md
I am however really inexperienced when it comes to JSON and keep messing up the POST function. This is the code I have currently, everything before the comma has been working fine.
function showButton() {
$('btn-1').on('click', function(event) {
var userProfileProperties
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
userProfileProperties = peopleManager.getMyProperties();
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(onSuccess, onFail);
function onSuccess(){
accountProperties = userProfileProperties.get_userProfileProperties();
accountId = accountProperties['msOnline-ObjectId'];
//JSON Query
jQuery.ajax({
url: "https://mysite.sharepoint.com/groups/groupID/members/$ref";
method: "POST";
contentType: "application/json";
dataType: 'json',
{
"#odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/" + accountId
};
});
};
function onFail(){
alert(failed);
};
});
};
In your document , you will find authentication token is required in the Request headers .Without authentication token ,you will receive an error as :
"code": "InvalidAuthenticationToken", "message": "Bearer access token is empty."
As a solution , you could try following steps :
1.Register a javascript Application in Azure AD and configure your app to allow the OAuth 2.0 implicit grant flow.Tokens are obtained using the OAuth 2.0 implicit grant flow. Using implicit grant, your application requests an access token from Azure AD for the currently signed-in user by sending the user to an authorization URL where the user signs in with their Office 365 credentials and then is redirected back to the app with the access token in the URL .
2.Add permissions to Graph API .
3.Add an html page to your sharepoint online(using Explorer mode) .
4.Edit the html , write below function to get an access token:
function requestToken() {
// Change clientId and replyUrl to reflect your app's values
// found on the Configure tab in the Azure Management Portal.
// Also change {your_subdomain} to your subdomain for both endpointUrl and resource.
var clientId = '3dadb44e-feaa-4158-90f5-e129e15db66d';//ID of your App in Azure
var replyUrl = 'https://o365e3w15.sharepoint.com/sites/XXX/app.html'; //my sharepoint page that requests
//an oauth 2 authentification and data
//It is also referenced in the REPLY URL field of my App in Azure
var endpointUrl = 'https://graph.microsoft.com/v1.0/me/messages';
var resource = "https://graph.microsoft.com/";
var authServer = 'https://login.windows.net/common/oauth2/authorize?';
//var authServer = 'https://login.microsoftonline.com/common/oauth2/authorize?';//this works either
var responseType = 'token';
var url = authServer +
"response_type=" + encodeURI(responseType) + "&" +
"client_id=" + encodeURI(clientId) + "&" +
"resource=" + encodeURI(resource) + "&" +
"redirect_uri=" + encodeURI(replyUrl);
window.location = url;
}
After that ,you could make an ajax call to graph api endpoint to get/post request, for example, get current user's messages:
var endpointUrl = "https://graph.microsoft.com/v1.0/me/messages";
var xhr = new XMLHttpRequest();
xhr.open("GET", endpointUrl);
var myToken = getToken();
// The APIs require an OAuth access token in the Authorization header, formatted like this:
//'Authorization: Bearer <token>'.
xhr.setRequestHeader("Authorization", "Bearer " + myToken);
// Process the response from the API.
xhr.onload = function () {
if (xhr.status == 200) {
//alert('data received');
var message="";
var object = JSON.parse(xhr.response);
for(i=0;i<object.value.length;i++){
message+='Subject: ' + object.value[i].subject + '<br>';
}
document.getElementById("results").innerHTML = message;
} else { }
}
// Make request.
xhr.send();
display this app.html into any SharePoint Webpart page by calling it within an iframe tag.
All detail steps you will find in this article , i have tested and work fine in my side .