Converting facebook button template from json to c# - c#

Hello i am trying to do this template on my C# code for Bot Framework V4.
This is the code from facebook.
"payload": {
"template_type":"button",
"text":"<MESSAGE_TEXT>",
"buttons":[
<BUTTON_OBJECT>,
<BUTTON_OBJECT>,
...
]
}
And this is my attempt of doing it. I can't debug the error cause it only works on messenger. Any help would be appreciated thank you.
Activity reply = stepContext.Context.Activity.CreateReply();
reply.ChannelData = JObject.FromObject(
new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "button",
text = "xx",
buttons = new[]
{
new
{
type = "web_url",
title = "take test",
url = "xx",
messenger_extensions="true",
webview_height_ratio = "tall",
},
},
},
},
});
await stepContext.Context.SendActivityAsync(reply);

Your code looks fine. Make sure to Whitelist any URLs you use with Facebook. Note, they must be https URLs. Additionally, unless the website is configured to be a webview, you do not need the messenger_extensions and webview_height_ratio properties in the button.
var reply = turnContext.Activity.CreateReply();
var attachment = new
{
type = "template",
payload = new
{
template_type = "button",
text = "Sign up for our mailing list!",
buttons = new[]
{
new
{
type = "web_url",
url = "https://mybot.azurewebsites.net/",
title = "Sign Up!"
},
},
},
};
reply.ChannelData = JObject.FromObject(new { attachment });
await turnContext.SendActivityAsync(reply, cancellationToken);
Take a look at Messengers Documentation on Button Templates for more details.
Hope this helps!

Related

DocuSign : Template Radio Button Selection Programmatically through c#

I already have the radio button in DocuSign template, I want to select one of correct option from True and False programmatically. With the help of radioGroup.Radios.Add(, I am getting overwrite button on template button. Can you please suggest the solution how i can select radio button through c# code.
RadioGroup radioGroup = new RadioGroup { GroupName =
templateField.DocuSignFieldName, DocumentId = "1",
Radios = new List<Radio>() };
radioGroup.Radios.Add(
new Radio { PageNumber = "3", Value = "Radio 1",
XPosition = "52", YPosition = "344", Selected = "true",
TabId = templateField.DocuSignFieldName });
radioGroup.Radios.Add(
new Radio { PageNumber = "3", Value = "Radio 2",
XPosition = "85", YPosition = "344", Selected = "false",
TabId = templateField.DocuSignFieldName });
radioTabs.Add(radioGroup);
Your template has a radio group
When you use the API to send the envelope, you want to choose the initial value of the radio group. (If you want the radio buttons to be read-only, then use the locked attribute.)
You will need the tabId and value for the radio button you want to set.
Here is the request object that uses a template on the server, and then sets the name/email of the signer, and sets which radio button is selected.
{
"envelopeDefinition": {
"status": "sent",
"compositeTemplates": [
{
"compositeTemplateId": "1",
"serverTemplates": [
{
"sequence": "1",
"templateId": "12345-678-91023"
}
],
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"email": "larry#example.com",
"name": "Larry K",
"roleName": "Signer1",
"recipientId": "1",
"tabs": {
"radioGroupTabs": [
{
"groupName": "Radio Group 1",
"radios": [
{
"selected": "true",
"tabId": "615d0f54-8754-459e-9f79-e72ad427557c",
"value": "Radio3"
}
]
}
]
}
}
]
}
}
]
}
]
}
}
Here is the same JSON when it is created with the C# SDK
ServerTemplate serverTemplate1 = new ServerTemplate
{
Sequence = "1",
TemplateId = "12345-678-91023"
};
List<ServerTemplate> serverTemplates1 = new List<ServerTemplate> {serverTemplate1};
Radio radio1 = new Radio
{
Selected = "true",
TabId = "615d0f54-8754-459e-9f79-e72ad427557c",
Value = "Radio3"
};
List<Radio> radios1 = new List<Radio> {radio1};
RadioGroup radioGroupTab1 = new RadioGroup
{
GroupName = "Radio Group 1",
Radios = radios1
};
List<RadioGroup> radioGroupTabs1 = new List<RadioGroup> {radioGroupTab1};
Tabs tabs1 = new Tabs
{
RadioGroupTabs = radioGroupTabs1
};
Signer signer1 = new Signer
{
Email = "larry#example.com",
Name = "Larry K",
RecipientId = "1",
RoleName = "Signer1",
Tabs = tabs1
};
List<Signer> signers1 = new List<Signer> {signer1};
Recipients recipients1 = new Recipients
{
Signers = signers1
};
InlineTemplate inlineTemplate1 = new InlineTemplate
{
Recipients = recipients1,
Sequence = "1"
};
List<InlineTemplate> inlineTemplates1 = new List<InlineTemplate> {inlineTemplate1};
CompositeTemplate compositeTemplate1 = new CompositeTemplate
{
CompositeTemplateId = "1",
InlineTemplates = inlineTemplates1,
ServerTemplates = serverTemplates1
};
List<CompositeTemplate> compositeTemplates1 = new List<CompositeTemplate> {compositeTemplate1};
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition
{
CompositeTemplates = compositeTemplates1,
Status = "sent"
};
ApiClient apiClient = new ApiClient(basePath);
apiClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + accessToken);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient);
try
{
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);
Console.WriteLine($"Envelope status: {results.Status}. Envelope ID: {results.EnvelopeId}");
return results.EnvelopeId;
}
catch (ApiException e)
{
Console.WriteLine("Exception while creating envelope!");
Console.WriteLine($"Code: {e.ErrorCode}\nContent: {e.ErrorContent}");
//Console.WriteLine(e.Message);
return "";
}
}
Please find the correct answer .
RadioGroup radioGroup = new RadioGroup
{
GroupName = templateField.DocuSignFieldName,
Radios = new List<Radio>()
};
if (_applicationAnswerMapService.GetRadioboxFieldValue(templateField, application) == "true")
{
radioGroup.Radios.Add(new Radio { Value = "Radio1", Selected = "true" });
}
else
{
radioGroup.Radios.Add(new Radio { Value = "Radio2", Selected = "false" });
}

Stripe payment intents examples for server side submit

I am looking at Stripe payment gateway with Payment intent API. All examples on the official page consist of example with jquery submit with function - payWithCard (function name).
Do we have any example where we could submit on server and do some validation before sending for payment?
With Charge API, we could post data on server and then we could send for payment.
Is it possible with Payment Intent API or I need to go with Jquery ?
You can go through Stripe documentation for details. When implementing Stripe we actually use both Server Side and Javascript. I am providing here sample working code.
Download Stripe package, I am using PHP here from the Github repository.
Then in the html page use the below javascript
function handleStripe() {
var stripe = Stripe("STRIPE PUBLISHABLE KEY");
var data = {
"sess": "Some valuable data",
"rcom": "Some valuable data"
};
fetch("stripe-intent-book.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(result) {
return result.json();
})
.then(function(data) {
var elements = stripe.elements({
fonts: [
{
cssSrc: 'https://fonts.googleapis.com/css?family=Quicksand',
},
],
locale: window.__exampleLocale,
});
var elementStyles = {
base: {
color: '#32325D',
fontWeight: 500,
fontFamily: 'Source Code Pro, Consolas, Menlo, monospace',
fontSize: '16px',
fontSmoothing: 'antialiased',
'::placeholder': {
color: '#CFD7DF',
},
':-webkit-autofill': {
color: '#e39f48',
},
},
invalid: {
color: '#E25950',
'::placeholder': {
color: '#FFCCA5',
},
},
};
var elementClasses = {
focus: 'focused',
empty: 'empty',
invalid: 'invalid',
};
var cardNumber = elements.create('cardNumber', {
style: elementStyles,
classes: elementClasses,
});
cardNumber.mount('#card-number');
var cardExpiry = elements.create('cardExpiry', {
style: elementStyles,
classes: elementClasses,
});
cardExpiry.mount('#card-expiry');
var cardCvc = elements.create('cardCvc', {
style: elementStyles,
classes: elementClasses,
});
cardCvc.mount('#card-cvc');
var inputs = document.querySelectorAll('.stripeCC .input');
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener('focus', function() {
input.classList.add('focused');
});
input.addEventListener('blur', function() {
input.classList.remove('focused');
});
input.addEventListener('keyup', function() {
if (input.value.length === 0) {
input.classList.add('empty');
} else {
input.classList.remove('empty');
}
});
});
cardNumber.on("change", function (event) {
document.querySelector("button").disabled = event.empty;
document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});
$('#submit').click(function() {
payWithCard(stripe, cardNumber, data.clientSecret);
});
});
}
And the server side PHP code below
<?php
\Stripe\Stripe::setApiKey("Stripe Secret key");
header('Content-Type: application/json');
try {
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$sess = $json_obj->sess;
$rcom = $json_obj->rcom;
$amt = 10; /* Specify the amount to be charged here */
$amt = $amt * 100;
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $amt,
'currency' => 'gbp'
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
?>
From the Stripe API reference below is the .Net code, requesting you to go through the Stripe API doc please
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
StripeConfiguration.ApiKey = "sk_test_tR3PYbcVNZZ796tH88S4VQ2u";
var options = new PaymentIntentCreateOptions
{
Amount = 1099,
Currency = "usd",
PaymentMethodTypes = new List<string> {
"card",
},
};
var service = new PaymentIntentService();
var intent = service.Create(options);

Onesignal c# web_buttons

I am trying to send a notification from my backend with the following code:
var obj = new
{
app_id = new Guid(ConfigurationManager.AppSettings["oneSignalAppid"]),
contents = new { en = "English Message"},
headings = new { en = "English heading" },
chrome_web_image = https://pixabay.com/static/img/no_hotlinking.png",
web_buttons = #"[
{
'id': 'like-button',
'text': 'Like',
'icon': 'http://i.imgur.com/N8SN8ZS.png',
'url': 'https://yoursite.com'},
{
'id': 'read-more-button',
'text': 'Read more',
'icon': 'http://i.imgur.com/MIxJp1L.png',
'url': 'https://yoursite.com'
}]",
included_segments = new string[] { "All" }
};
either i get a 400 response or i get my notification without the buttons.
How do i set the web_buttons properly?
the solution is to serialize the array object using anonymous array of anonymous types:
web_buttons = new[] {
new {id="id-1", text= buttonText, url="http://yourDomain.com" },
}
...

Creating JSON out of string

I want to get JSON similar to this
{
"Name": "xxxxx",
"ApplicationId": "xxxxx",
"Features": [
{
"Name": "xxxxx",
"Code": "xxxxx",
}
]
}
and my code is so far is
var json = JsonConvert.SerializeObject(
new {
Name = name ,
ApplicationId = applicationID ,
Features = (new[]{feature_name , feature_code})
}, Formatting.None);
I can not figure out the feature part, it won't get created as in the example.
I read so many post, but did not find anything about inner objects.
You didn't give the features appropriate names, hence then variable names are used.
Use this instead:
new[] { new { Name = feature_name, Code = feature_code } }
Also, you have to supply a list of features, for example using LINQ.
features.Select(f => new { Name = f.feature_name, Code = f.feature_code })
Another way of doing this can be like:
var createJson = new {
Name = "xxxxx",
ApplicationId = "xxxxx",
Features = new[] {
new { Name = "xxxxx", Code = "xxxxx" },
new { Name = "xxxxx", Code = "xxxxx" }
}
};
var json = JsonConvert.SerializeObject(createjson, Formatting.Indented);

JSON data in PUT request in C#

I am trying to make a PUT request with a C# client, this request has JSON data in it.
I use this, which I got from here: Passing values to a PUT JSON Request in C#
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
reg_FirstName = "Bob",
reg_LastName = "The Guy"
});
Ofcourse, the Json string looks like this:
{
"reg_FirstName":"Bob",
"reg_LastName":"The Guy"
}
But how would I go around creating a JSON string like this:
{
"main": {
"reg_FirstName": "Bob",
"reg_LastName": "The Guy"
},
"others": [
{
"reg_FirstName": "Robert",
"reg_LastName": "The Guy"
},
{
"reg_FirstName": "Rob",
"reg_LastName": "The Guy"
}
]
}
You can use the same way - dynamic objects, so in your case it would look like this:
var serializer = new JavaScriptSerializer();
string json =
serializer.Serialize(
new {
main = new
{
reg_FirstName = "Bob",
reg_LastName = "The Guy"
},
others = new[]
{
new { reg_FirstName = "Bob", reg_LastName = "The Guy" },
new { reg_FirstName = "Bob", reg_LastName = "The Guy" }
}
}
);

Categories

Resources