How to run Twilio API code using Javascript? - javascript

I am using twilio api code in jquery,its working fine.
but i want to implement it in pure javascript,how can i do that with only javascript?
My code is here.
$(document).ready(function() {
$("#btnSubmit").click(function(){
var SID = "AC654656****************"
var Key = "df5456**************"
$.ajax({
type: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/' + SID +'/Messages.json',
data: {
"To" : "+919580834781",
"From" : "+12018647238",
"Body" : "Test"
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(SID + ':' + Key));
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
can anyone please suggest me the solution?

Twilio developer evangelist here.
We do not recommend you use front end JavaScript to make calls to the Twilio API. It requires you to embed your Account Sid and Auth Token in your front end (or make it accessible from your front end) which means that an attacker could steal your credentials and use them to abuse your account.
We recommend you perform any actions with the Twilio API on the server. We do have a Node.js module on npm to make that easy to work with. Here's an example of sending an SMS message with the Node.js module:
var client = require("twilio")(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
client.messages.create({
body: "Hello",
to: TO_NUMBER,
from: FROM_NUMBER
}).
then(function(result) {
console.log("Message sent!");
}).
catch(function(err) {
console.log("Error sending message: ", err);
})
Check out this blog post introducing the Twilio Node.js module for more information.
Let me know if that helps at all.

Related

.Net core AntiForgeryToken is not matching with server

I am working on Asp.Net core application and Application is running fine on my local but I am not able to validate Antiforgery token on the server.
Error: "Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted."
Below is the code.
#section scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#btnstart").click(function(e) {
let productvals = $("#productlist").val();
let runnumber = $("#runnum").val();
let btnval = $("#btnstart").val();
e.preventDefault();
$.ajax({
url: "#Url.Action("
CheckRunnumber ","
Validation ")",
type: "POST",
dataType: "json",
data: {
runnumber: $('#runnum').val()
},
success: function(data) {
if (data.success == "True") {
console.log(data);
console.log(data.btnstartval);
//$("#Runform").submit();
if ($("#Runform").valid()) {
console.log(productvals, runnumber, data.btnstartval);
console.log(gettoken());
$.ajax({
url: "#Url.Action("
RunCase ", "
CallService ")",
type: "POST",
dataType: "json",
data: {
products: productvals,
runnumber: runnumber,
button: data.btnstartval,
__RequestVerificationToken: gettoken()
},
contentType: 'application/x-www-form-urlencoded; charset=utf-8'
});
} else {
alert("Error");
e.preventDefault();
}
}
}
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
}
}
</script>
}
To compare this token I logged it on the console window and it is different then the one under Application tab inside the inspect window.
Below is the error log I am getting.
2020-10-08T13:00:05.5115395-05:00 0HM3BMFTTVJ22:00000001 [ERR] An exception was thrown while deserializing the token. (348bf365)
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
---> System.Security.Cryptography.CryptographicException: The key {dbeef040-4a73-45ff-8b62-064683015ea1} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)
2020-10-08T13:00:35.9439222-05:00 0HM3BMFTTVJ22:00000004 [INF] Process not found (d326d86c)
Do you host your application on shared server backend or else? It seems that your application doesn't have enough permission to read the key.
I suggest you could try to modify the IIS application pool identity to have enough permission to read the key. More details ,you could refer to below steps:
1.Open IIS management console:
2.Select your application pool
3.Modify the application pool identity to local system or other domain account which has enough permission to access your keys.
If this couldn't solve your issue, could you please share the startup.cs settings?

Create a gist using GitHub API

I wanna create a gist using GitHub API. I tried an POST ajax request:
var gist = {
"description": "Avatars",
"public": true,
"files": {
"check.txt": {
"content": "Avatars list..."
}
}
};
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(gist),
success: function(e) {
console.log(e);
},
error: function(e) {
console.error("Error!: ", e);
}
});
But I always get the following error:
jquery-3.1.1.min.js:4 POST https://api.github.com/gists 401 (Unauthorized)
Can anyone help me?
Thanks
When you want to edit things on Github, you need to authorize your request. Either by adding a username and password to the request or an oauth token.
More information can be found in the authorization documentation: https://developer.github.com/v3/auth/
Since I ran across the same problem recently, let me add the examples requested by T.Todua
If you want to authenticate with username and password, add the following lines to your $.ajax request:
crossDomain: true,
beforeSend: function (XHR) {
XHR.setRequestHeader(
'Authorization','Basic ' + btoa(Username + ':' + Password)
);
},
If, however, you created an access token for your gists (see Github help and don't forget to check the "Gist" permission!) then add the following lines instead
crossDomain: true,
headers: {
'Authorization':'bearer ' + GitHubAccessToken
},
The GitHubAccessToken will be shown once (and only once!) immediately after creation, so make sure to store it in a safe location as everybody knowing this access token will be able to modify your gists (until you revoke it again).

How to use an API with an app Fiori (SAPUI5)

I am trying to use this Mercedes Benz API in my app. Inside controller I have a ajax request:
onInit : function () {
var oModel = new JSONModel();
var url = 'https://api.mercedes-benz.com/image/v1/vehicles/WDDZH3HB8JA394212/components?apikey=my_apikey';
$.ajax({
beforeSend: function() {
//armamos la url y la asignamos a una var
},
url: url,
type: 'GET',
accepts: "application/json",
success: function (resp) {
console.log(resp)
},
error: function (jqXHR, estado, error) {
console.log(error +":" + " " + estado)
},
timeout: 10000
});
},
I just want response as OK but getting some error:
Request header field X-XHR-Logon is not allowed by
Access-Control-Allow-Headers in preflight response.
Responses
If you take a look to the documentation API I just need the API key. Maybe I am doing something wrong? Guide me if you has use an API inside a FIORI app it will be thankful
NOTE: my fiori server is on premise so we don't use SCP
If you really want to do an XHR you need to whitelist APIKEY in neo-app.json like this
{
"welcomeFile": "/webapp/index.html",
"routes": [{
...
],
"sendWelcomeFileRedirect": true,
"headerWhiteList": [
"APIKey"
]
}
Otherwise I strictly recommend using destinations, explained in here:
SAPUI5 / AJAX, submitting Basic Authentication Details (solved)
Authentication API in SAPUI5 without SAP Cloud Platform and Destinations (not solved)

HTTP request through Parse Cloud code

So I am trying to get the cloud code to do an aftersave event that pings another location to do some data saving.
It has some data that needs to be sent as well.
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var pieceName = "Robert Rauschenberg Quote";
var url = 'http://www.gilmancontemporary.com/wp-content/uploads/2015/06/Delicate_Garden.The_Bear.48x42.jpeg';
Parse.Cloud.httpRequest({
url: artistURL,
dataType : "text",
crossDomain: true,
type:"GET",
data : {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response(httpResponse.text);
},
error: function(httpResponse) {
response('Request failed with response code ' + httpResponse.status)
}
});
});
The code does not give an error, or any warnings. Me saving/creating entries works fine.
Cors is already handled, as I can successfully make this call with an ajax script.
Any clue why this is not sending?
Can I not have data in a parse httpRequest?
Can it not be crossdomain?
Alternatively
Is there a way to test this code outside of the Parse Cloud???
The way you call httpRequest function is not correct in cloud. You also do not need to worry about CORS as you are not working in a browser environment. Try this instead:
Parse.Cloud.httpRequest({
url: artistURL,
params: {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response(httpResponse.text);
},
error: function(httpResponse) {
response('Request failed with response code ' + httpResponse.status)
}
});
To test this outside cloud environment you can use the curl command. It will be something like:
curl -G -v "http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php" --data-urlencode "pieceName=Robert Rauschenberg Quote,url=http://www.gilmancontemporary.com/wp-content/uploads/2015/06/Delicate_Garden.The_Bear.48x42.jpeg"

How to send the parse users objectId with the twilio module

I have been trying to get the Object id of the parse user, so that i can send it to the users phone number. The cloud code is done in javascript which i am not familiar with. I believe the problem is with my code. Here is what i have done so far:
var twilio = require("twilio");
twilio.initialize("myAccountSid","myAuthToken");
// Create the Cloud Function
Parse.Cloud.define("inviteWithTwilio", function(request, response) {
// getting objectId from Parse
var query = new Parse.Query("objectId");
query.equalTo("username", request.params.number);
query.find({
success: function(httpResponse){
response.success("Code found");
},
error: function(httpResponse){
response.error("Code not found");
}
});
// Use the Twilio Cloud Module to send an SMS
twilio.sendSMS({
From: "myTwilioPhoneNumber",
To: request.params.number,
Body: "Start using Parse and Twilio!" + query
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
I need help making this code work. And advice on books i can read to improve my understanding of JavaScript would be useful.
Was finally able to solve my problem. All i actually needed was Parse.User.current().id. Here is the working code:
var twilio = require("twilio");
twilio.initialize("myAccountSid","myAuthToken");
// Create the Cloud Function
Parse.Cloud.define("inviteWithTwilio", function(request, response) {
// Use the Twilio Cloud Module to send an SMS
var objectId = Parse.User.current().id ;
twilio.sendSMS({
From: "myTwilioPhoneNumber",
To: request.params.number,
Body: "Your Apps verification code is " + objectId
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});

Categories