How to send user information through directline botconnector - javascript

I'm building a mobile client to talk to a bot built with microsoft botbuilder through botconnector directline. I want to send things like the unique id of the user speaking with the bot, so my bot can operate on this user. Currently I'm just POSTing to directline, but when I add additional things in the body, my bot can't retrieve it. I'm probably doing something really simple wrong. Would love to get your help on this!
POST code from client:
sendToBot: function(setUpObj, message, returnCallback){
var postURL=baseURL+"/"+setUpObj.conversationId+"/messages"
var postOptions ={
method: 'POST',
headers: {
"Authorization": setUpObj.conversationToken,
"content-type": "application/json"
},
body: JSON.stringify({
"text": message,
"from": {
'address': setUpObj.currentUserUid
}
})
}
fetch(postURL, postOptions)
.then(
(response)=>response.text()
)
.then(
(responseText)=>{
this.getResponse(setUpObj, returnCallback)
}
)
}
and I'm accessing the the currentUserUid on the server by
session.message.from.address
Thanks for you patience.

Have you tried setting the channelData in the json? It's described as "data sent unmodified between client and bot" and can look like:
{
"id": "CuvLPID4kDb|000000000000000004",
"conversationId": "CuvLPID4kDb",
"created": "2017-02-22T21:19:51.0357965Z",
"from": "examplebot",
"text": "Hello!",
"channelData": {
"examplefield": "abc123"
}
}
https://docs.botframework.com/en-us/core-concepts/channeldata/
So in your code it could look like:
var postOptions ={
method: 'POST',
headers: {
"Authorization": setUpObj.conversationToken,
"content-type": "application/json"
},
body: JSON.stringify({
"text": message,
"channelData": {
"from": {
"address": setUpObj.currentUserUid
}
}
})
}

Related

Checkout.com Payment response JavaScript

I am trying to integrate https://www.checkout.com/ in my app.
I tried there sample code to get token.
Frames.addEventHandler(
Frames.Events.CARD_TOKENIZED,
function (data) {
Frames.addCardToken(form, data.token);
if (data.token) {
confirmPayment(data.token);
} else {
console.log(data);
}
}
);
I tried https://api.sandbox.checkout.com/payments/ api to do the payments,
payment successfully captures, but I am unable to read its response to or redirect user on successfully attempt.
async function confirmPayment(token) {
// Storing response
const response = await fetch('https://api.sandbox.checkout.com/payments/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk_sbox_..abc'
},
body: JSON.stringify({
"source": {
"type": "token",
"token": token
},
"Capture": true,
"processing_channel_id": "pc_..abc",
'amount': 1000,
'currency': 'USD',
"3ds": {
"enabled": false
},
"customer": {
"email": "test.testUI#example.com",
"name": "John Test"
},
'reference': 'ORD-175-759',
"metadata": {
"udf1": "UI-CALL-TEST",
"coupon_code": "NY2018",
"partner_id": 123989
},
"success_url": "http://example.com/payments/success",
"failure_url": "http://example.com/payments/fail"
})
});
// Storing data in form of JSON
var data = await response.json();
console.log(data);
if (response) {
}
show(data);
}
I want to get a payment response like errors "card invalid" etc
Also redirect to Url if successful.
Please let me know if this is a correct way to do the payment or If there any JavaScript library that I can use?
I want to do payment on client side and use webhook later.
Thank you

POST to API using JavaScript returns 401

I am posting data to a web API. The response is a 401 error. I don't know what is wrong with my code.
This is the code:
var form = document.getElementById("form");
form.addEventListener("submit", function (e) {
e.preventDefault();
var edition= document.getElementById("edition").value;
var competition= document.getElementById("competition").value;
var price= document.getElementById("price").value;
var firstname= document.getElementById("firstname").value;
var lastname= document.getElementById("lastname").value;
var email= document.getElementById("email").value;
fetch("https://front-api.njuko.com/partner/registration", {
method: "POST",
body: JSON.stringify({
edition: edition,
competition: competition,
price: price,
firstname: firstname,
lastname: lastname,
email: email,
}),
headers: {
"Content-Type": "application/json",
},
})
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
});
});
As i am new to the programming i don't how i can send the data into the website. This are the request sample of the website.
{
"edition": "5d888c93df85b80006f54265",
"competition": "5d888c93df85b80006f54265",
"price": "5d888c93df85b80006f54265",
"firstname": "John",
"lastname": "Doe",
"email": "john.doe#acme.com",
"methodName": "Partner payment (VISA)",
"datas": [
{
"value": "Detroit, Michigan",
"field": "5d888c93df85b80006f54255"
}
],
"metaData": [
{
"key": "stravaActivityId",
"label": "strava-activity-id",
"value": "329859FNENF29492Ifnjnfe93"
}
]
}
This are the Actual Picture
401 Error Code means Unauthorized.
I don't see any authentication in your code.
The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.
I dont know the implementation of the exact API,
but mostly used is this :
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer <API_TOKEN>"
}

can't fetch msgraph data using vanilla js

I am trying to pull data from the endpoint https://graph.microsoft.com/v1.0/me/. I have done this using python but I can't seem to fetch data from Microsoft Graph using vanilla js.
When I attempt to perform a fetch request. I get a 200 response but nothing is inside the response object.
Here is the fetch code:
fetch("https://graph.microsoft.com/v1.0/me/", {
method: "GET",
"headers": {
"authorization": "Bearer ENTERTOKENHERE"}
}).then(data =>{console.log(data)});
I get a response of:
Response {type: 'cors', url: 'https://graph.microsoft.com/v1.0/me/', redirected: false, status: 200, ok: true, …}
but I am expecting more of a response like the one I get from the https://developer.microsoft.com/en-us/graph/graph-explorer website like this:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"businessPhones": [],
"displayName": "Edd Bighead",
"givenName": "Edd",
"jobTitle": null,
"mail": "Edd#conglomo.onmicrosoft.com",
"mobilePhone": null,
"officeLocation": null,
"preferredLanguage": "en-US",
"surname": "Bighead",
"userPrincipalName": "Edd#conglomo.com",
"id": "2fa321d9-bda3-41c1-8be8-5d4049ed8765"
}
Is there anything I am missing to get the data from msgraph using vanilla js only?
I figured it out - I needed to jsonize the data then print that data. Can't believe I missed that. lol
fetch("https://graph.microsoft.com/v1.0/me/", {
method: "GET",
"headers": {
"authorization": "Bearer ENTERTOKENHERE"}
}).then(response => response.json())
.then(data => {console.log(data)})

Send Mail with attachment Microsoft Graph not working

I am making an application that sends emails from a User as described by this article.
Everything is working as expected, except for when I try to include an attachment. The email sends, but without the attachment. I'm not sure what the problem is as I've tried pretty much everything I could find online. I have made sure the file I am sending is properly encoded in base64.
var message = {
"subject": subject,
"hasAttachments":true,
"body": {
"contentType": "Text",
"content": emailBody
},
"toRecipients": toRecipients,
ccRecipients,
bccRecipients
};
function sendMailRequest(access_token, message, uriSend, file, base64, callback){
const attachments = [{
'#odata.type': '#microsoft.graph.fileAttachment',
"contentBytes": base64
"name": "example.jpg"
}];
// Configure the request
var options2 = {
"url": uriSend,
"method": 'POST',
"headers": {
'Authorization': access_token,
'Content-Type': 'application/json'
},
"body": JSON.stringify({
"message": message,
"SaveToSentItems": "true",
"Attachments": attachments
})
}
Attachments go inside the message JSON, not outside of it. This should work:
function sendMailRequest(access_token, message, uriSend, file, base64, callback) {
const attachments = [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"contentBytes": base64
"name": "example.jpg"
}
];
message["attachments"] = attachments;
// Configure the request
var options2 = {
"url": uriSend,
"method": "POST",
"headers": {
"Authorization": access_token,
"Content-Type": "application/json"
},
"body": JSON.stringify({
"message": message,
"SaveToSentItems": "true"
})
}
...
}

HTTPS request not posting body of REST request

I'm trying to POST to an API endpoint on my server. I know my endpoint works because if I use Advanced REST Client, I can hit it and get a JSON response as expected. The problem seems to be that no data is being sent in the body of my request despite calling request.write(postData) which contains a key, value pair. Without this data being sent in the body, my server returns a 401 error as expected without this information. Printing out the content of the POST server-side is empty but I'm clueless as to why it's empty.
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
I have testing you code again httpbin.org/post and it seems that it is working.
I believe that the issue related to, that your should POST application/json and not "application/x-www-form-urlencoded
Please try to change the header
headers: {
"Content-Type": "application/json"
}
Then, try to change the postData to JSON string:
var postData=JSON.stringify({access_token:"xxxxx"})
To be sure that problem you success to send and the problem is not local (maybe there is an issue in your server), change the target to mirror URL:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
If there is no problem in your NodeJS version, the is the response you should get: (It is mean that the server got the posted data)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
BTW: I really recommend you to move to a library to manage the request for you:
https://github.com/request/request - Very popular
https://github.com/request/request-promise - For popular who like to use the Promise syntax (The next thing in JavaScript)
https://github.com/visionmedia/superagent - For people who like to write same code in Browser & Server

Categories