Clickatell One API Customer Call Back not returning anything - rest

I have developed a call back REST service using the following link as reference https://docs.clickatell.com/channels/one-api/one-api-reference/#tag/One-API-Client-Callbacks/operation/sendPostOmniReplyCallback. I am using the sample payload as supplied by the Clickatell example using Postman and I can process and post the payload without problems. It also works when I deploy this as a public URL on the web. However, when pasting my URL in the Clickatell Customer Call Back I do not receive any call backs. I am obviously missing something or misinterpreting the sample code provided by Clickatell. Please note that for testing purposes I write the full payload to MySQL - works when using Postman, but not from Clickatell Call Back URL.
enter code here
{
[Route("client-callback/one-api-reply")]
[ApiController]
public class MessageController : ControllerBase
{
[HttpPost]
public async Task<dynamic> StartProcessiongAsync([FromBody] dynamic obj)
{
string myObj = JsonConvert.SerializeObject(obj);
var data = JsonConvert.DeserializeObject<Rootobject>(myObj);
var context = new DataContext();
var command = context.Database.GetDbConnection().CreateCommand();
context.Database.OpenConnection();
command = context.Database.GetDbConnection().CreateCommand();
{
command.CommandText =
"INSERT INTO testcallback(message) VALUES ('" + myObj + "');";
command.ExecuteNonQuery();
}
return Ok(obj);
}
}
}
Postman Payload Sample
{
"integrationId": "fa8090815f05d5ed015f0b5b56080cd2",
"integrationName": "My integration",
"event": {
"moText": [
{
"channel": "sms",
"messageId": "3a89680503414383af44dcd0e4e5f184",
"relatedMessageId": "d33eef0838a121f71069a4cc8d55c19e",
"relatedClientMessageId": "d33eef0838a121f71069a4cc8d55c19e",
"from": "2799900001",
"to": "2799900001",
"timestamp": 1506607698000,
"content": "Text Content of the reply message",
"charset": "UTF-8",
"sms": {
"network": "Network ID"
},

Related

How to pass Json Request body from one HttpRequest as a value in the next http request?

I'm trying to capture payload (in JSON) created from an HTTP request and pass it as a value to the next API request.
Step1: Create Http Request Payload. Sample Below:
{
"fdCustomerId":"${cuid}",
"account":{
"type":"CREDIT",
"credit":{
"cardNumber":"ENC_[${Output2}]",
"nameOnCard":"John Smith",
"cardType":"${cardtype}",
"cardSubType": "${cardsubtype}",
"billingAddress":{
"type":"work",
"country":"US",
"primary":true
}
}
Step2: Capture the final Payload into a variable using post processes
var requestBody = ctx.getCurrentSampler().getArguments().getArgument(0).getValue();
vars.put("requestBody", requestBody);
log.info("###########################################Request Body are:##########" + requestBody);
Step3: Pass the RequestBody variable as a value to the next HTTP request
{
"category": "GBS_ExecMetrics_UCom",
"consumed": false,
"data": { "Test Case Id": "AB_CMS_006_CC_001_500_",
"Account Number": "0001210520779700304",
"Primary Card Number": "**${requestBody}**",
"Secondary Card Number": "0000377883144114646",
"Run Date Time": "03/26/201917:30"}
}
When I hit that to the endpoint I get below error message:
{"Error":"BadRequest: Please provide a valid Json"...
How to convert this to string or include escape characters with a function and pass the request-body?
My bad with the sample request syntax taken in step 1.Above steps worked as-is.
Corrected the syntax as below and was able to pass the json. Thanks.
{
"fdCustomerId":"${cuid}",
"account":{
"type":"CREDIT",
"credit":{
"cardNumber":"ENC_[${Output2}]",
"nameOnCard":"John Smith",
"cardType":"${cardtype}",
"cardSubType": "${cardsubtype}",
"billingAddress":{
"type":"work",
"country":"US",
"primary":true
}
}
}
}

Azure Function SendGrid

Hi I'm basically executing a query which returns x amount of emails that exist on a specific day and I want to send an email to all of these emails using sendgrid's api here is my code - I am running into alot of errors listed below could anyone shed some light?
[code]
**#r "System.Data"
#r "SendGrid"
using System;
using System.Data;
using SendGrid.Helpers.Mail;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
using SendGrid;
private SqlConnection conn = null;
private SqlDataAdapter da = null;
private SqlCommandBuilder cb = null;
private DataSet ds = null;
private String location = null;
public void Run(TimerInfo myTimer, TraceWriter log)
{
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
string connStr = "Data Source=sdc-hwsb.database.windows.net;Initial Catalog=SDC-HotelWSBooking;Integrated Security=False;User ID=sdchwsb;Password=Trivago17!;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string query = "SELECT email FROM dbo.test_bookings2 WHERE startDate = #startDate";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#startDate", DateTime.Today.ToShortDateString());
int k = 0;
int f = Convert.ToInt32(cmd.ExecuteNonQuery());
while (f > 0 & k < f)
{
conn = new SqlConnection(connStr);
da = new SqlDataAdapter(query, conn);
cb = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds);
String Email = Convert.ToString(ds.Tables[0].Rows[k]);
Run1(Email,message);
k++;
}
}
public static void Run1(string email, out Mail message)
{
message = new Mail
{
Subject = "Azure news"
};
var personalization = new Personalization();
// change to email of recipient
personalization.AddTo(new Email(email));
Content content = new Content
{
Type = "text/plain",
Value = "DD"
};
message.AddContent(content);
message.AddPersonalization(personalization);
}
**
I Am getting errors reffering to the Message object sendgrid is using such as:
2017-09-25T18:50:37.754 Function started (Id=067b32b9-7bc3-47ca-9f32-b8b92c3b57e9)
2017-09-25T18:50:37.770 Function compilation error
2017-09-25T18:50:37.770 run.csx(38,28): error CS0103: The name 'message' does not exist in the current context
2017-09-25T18:50:37.807 Exception while executing function: Functions.TimerTriggerCSharp1. Microsoft.Azure.WebJobs.Script: Script compilation failed.
2017-09-25T18:50:37.948 Function completed (Failure, Id=067b32b9-7bc3-47ca-9f32-b8b92c3b57e9, Duration=196ms)
As Mike S mentioned about sending multiple emails via use an ICollector, I checked the official document about SendGrid output binding and did not find any sample, then I followed the code sample from Queue output sample in C# to test this feature as follows:
run.csx
#r "SendGrid"
using System;
using SendGrid.Helpers.Mail;
public static void Run(TimerInfo myTimer, TraceWriter log, ICollector<Mail> mails)
{
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
for(int i=0;i<3;i++)
{
Mail message = new Mail()
{
Subject = $"Hello world from the SendGrid C# TimerTrigger!"
};
var personalization = new Personalization();
personalization.AddTo(new Email("the-email-address-of-recipient"));
Content content = new Content
{
Type = "text/plain",
Value = $"Hello world!{i}"
};
message.AddContent(content);
message.AddPersonalization(personalization);
mails.Add(message);
}
}
function.json
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
},
{
"type": "sendGrid",
"name": "mails",
"apiKey": "sendgrid-apikey",
"direction": "out",
"from":"<the-email-address-of-sender>"
}
],
"disabled": false
}
Result:
Additionally, for creating Functions class library project via VS2017, you could refer to this tutorial about SendGrid output.
Some of those errors are compilation errors - fix those first. For example, you're missing a ')' on line 28.
You can also author functions in Visual Studio - which will give you the power of a real IDE with C# intellisense and error checking. That would catch the errors above. That's useful as soon as your functions are non-trivial. Check out details here:
https://blogs.msdn.microsoft.com/appserviceteam/2017/08/14/azure-functions-tools-released-for-visual-studio-2017-update-3/
The SendGrid binding should be on your Run() function.
public void Run(TimerInfo myTimer, TraceWriter log, out Mail message)
And then Run1 is just an internal helper to generate the message.
If you need to send multiple messages, use ICollector / IAsyncCollector. That has an 'add' method.

How to receive an image in a Facebook Messenger bot

How can I receive an attachment in form of an image through the Facebook Messenger API?
Their documentation only provides instructions on how to receive text-based messages.
I am not sure what language you are using to code your bot but since you are referring to the facebook documents where most of the messenger code snippets are in node.js
Here's something for you to try, let me know if this helps.
app.post('/webhook/', function (req, res) {
//Getting the mesagess
var messaging_events = req.body.entry[0].messaging;
//Looping through all the messaging events
for (var i = 0; i < messaging_events.length; i++) {
var event = req.body.entry[0].messaging[i];
//Checking for attachments
if (event.message.attachments) {
//Checking if there are any image attachments
if(atts[0].type === "image"){
var imageURL = atts[0].payload.url;
console.log(imageURL);
}
}
}
}
In February 2017 I came across the same issue and struggled to get this up and running for a very long time. Turns out that the message.attachments comes in as object, where the actual attachment is within the object.
The structure goes like this:
Attachments Object > JSON Response >Type & Payload > URL
app.post('/webhook/', function(req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
// Check if it's a message
if (event.message) {
//Create the attachment
let attachment = event.message.attachments
// Here we access the JSON as object
let object1 = attachment[0];
//Here we access the payload property
let payload = object1.payload;
// Finally we access the URL
let url = payload.url;
console.log(url)
}
else if (event.message && event.message.text) {
// Here you can handle the text
console.log("Just Text")
}
}
res.sendStatus(200)
})
The more compact version without explanations looks like this:
if (event.message) {
let attachment = event.message.attachments
console.log(attachment[0].payload.url)
}
As added bonus, you could also check if the type is an Image. You can achieve that by adding doing this adjustment:
if (event.message && ) {
let attachment = event.message.attachments[0]
if (attachment.type === "image") {
console.log(attachment.payload.url)
}
}
Hope this helps,
Julian
While in PYTHON to receive and save an image attachment in your facebook chatbot works:
#app.route('/', methods=['POST'])
def webhook(): # endpoint for processing incoming messaging events
data = request.get_json()
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
if messaging_event["message"].get("attachments"):
attachment_link = messaging_event["message"]["attachments"][0]["payload"]["url"]
print("Image received, boss!")
print(attachment_link)
good chatbot-thing!
Marco
In PHP,
When user sents it to bot, below response we get which contains attachement type and url
{
"object": "page",
"entry": [
{
"id": "000000000000000",
"time": 1511956708068,
"messaging": [
{
"sender": {
"id": "000000000000000"
},
"recipient": {
"id": "000000000000000"
},
"timestamp": 1511956707862,
"message": {
"mid": "mid.$xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"seq": 42172,
"sticker_id": 369239263222822,
"attachments": [
{
"type": "image",
"payload": {
"url": "https:\/\/scontent.xx.fbcdn.net\/v\/t39.1997-6\/851557_369239266556155_759568595_n.png?_nc_ad=z-m&_nc_cid=0&oh=9058fb52f628d0a6ab92f85ea310db0a&oe=5A9DAADC",
"sticker_id": 369239263222822
}
}
]
}
}
]
}
]
}
This is how you get different type of messages from user
//get the response from user
$input = json_decode(file_get_contents('php://input'), true);
//first check if attachment is present
$attachment = array_key_exists('attachments', $input['entry'][0]['messaging'][0]['message']);
//get the attachement type and url
$type = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['type'];
$file_url = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['payload']['url'];
Hope this helps you
https://developers.facebook.com/docs/messenger-platform/implementation#receive_message
Check this link out.
It says that,
"Messages may have an image, video or audio attachment."
UPDATE:
The above link is broken as Facebook recently updated their documentations in a weirdly downgraded version with many contents missing.
To elaborate as pointed out in the comment, when a user sends a request, your server will receive such a json:
{
"mid": "some mid",
"seq": 26,
"attachments": [{
"type": "image",
"payload": {
"url": "some image url"
}
}]
}
and you can maybe create a download function to download the image to your server.
To use this data, as mentioned above, you can use the webhook.
app.post('/webhook', function (req, res) {
var data = req.body;
// Make sure this is a page subscription
if (data.object == 'page') {
console.log(data.entry);
// Iterate over each entry
// There may be multiple if batched
data.entry.forEach(function(pageEntry) {
var pageID = pageEntry.id;
var timeOfEvent = pageEntry.time;
// Iterate over each messaging event
pageEntry.messaging.forEach(function(messagingEvent) {
receivedMessage(messagingEvent);
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know you've
// successfully received the callback. Otherwise, the request will time out.
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
if (senderID == PAGE_ID) {
console.error("Sender is self.");
return;
}
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
// You may get a text or attachment but not both
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches any special
// keywords and send back the corresponding example. Otherwise, just echo
// the text we received.
} else if (messageAttachments) {
messageAttachments.forEach(function(messageAttachment) {
var attachmentUrl = messageAttachment.payload.url;
console.log("Received Attachment");
download(attachmentUrl);
}
}
This code was taken from the sample code of Facebook.

Cakephp 2.x get message { "name": "The request has been black-holed", "url": "\/rest_sms_boxs.json" } in Restfull api

I write a controller and it contain multi POST action but whene i post data to these actions my response is :
{ "name": "The request has been black-holed", "url": "/rest_sms_boxs.json" }
Now how can i resolve this problem.
Certainly the security mode.
Try in your controller:
public function beforeFilter()
{
parent::beforeFilter();
$this->Security->unlockedActions = array('your_method');
}

HTTP post to ASP MVC 3 from a client app

I have an ASP MVC 3 site that allows a user to submit some helpdesk information. I also have a client app (WPF) that users should be able to submit helpdesk information from. I would like to just do a HTTP POST to the same form that the user would use via the web site.
Is this possible? I've tried using RestSharp but I keep getting a 401.2 from my site.
Thoughts?
My MVC controller action is something like:
//
// POST: helpdesk/submit
[HttpPost]
public ActionResult Submit(HelpDeskRequest helpDeskRequest)
{
}
You could use a WebClient to POST values to your controller action:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "Id", "123" },
{ "Name", "abc" },
};
var result = client.UploadValues(
"http://www.domain.com/helpdesk/submit",
values
);
}
and inside the action you will get:
[HttpPost]
public ActionResult Submit(HelpDeskRequest helpDeskRequest)
{
// helpDeskRequest.Id = 123;
// helpDeskRequest.Name = "abc";
...
}