Stripe payment intents examples for server side submit - c#

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);

Related

Request.Files Comes Empty on Occasion

I am using FineUploader plug-in to upload some files to the server. For some reason, Request.Files array comes empty like in every 10 in 100 page loads. It's null sometimes. After hit Ctrl+F5, everything works properly. I know that FineUploader is no longer supported. But it's probably not related with FineUploader.
ServerSide Code:
var request = controllerContext.RequestContext.HttpContext.Request;
var formUpload = request.Files.Count > 0;
// find filename
var xFileName = request.Headers["X-File-Name"];
var qqFile = request["qqfile"];
var formFilename = formUpload ? request.Files[0].FileName : null;
var upload = new FineUpload
{
Filename = xFileName ?? qqFile ?? formFilename,
InputStream = formUpload ? request.Files[0].InputStream : request.InputStream
};
return upload;
Client Side JavaScript code:
<script>
var uploader = new qq.FineUploader({
debug: true,
multiple: false,
element: document.getElementById('fine-uploader'),
request: {
endpoint: '/SystemDefinitions/ProcessImportFile',
params: { "operationType": $("#operationType").val() }
},
deleteFile: {
enabled: true,
endpoint: '/SystemDefinitions/DeleteFile'
},
retry: {
enableAuto: false
},
failedUploadTextDisplay: {
mode: 'custom', // Display error responses from the server.
responseProperty: 'error' // Default is 'error', change this to match the
// property that contains the error message from
// your server
},
callbacks: {
onComplete: function (id, name, xhr) {
if (xhr.errorMessage !== "") {
showResult("Error", xhr.errorMessage);
return false;
}
},
onSubmit: function (id, fileName) {
var newParams = {
operationType: $("#operationType option:selected").val()
},
finalParams = defaultParams;
qq.extend(finalParams, newParams);
this.setParams(finalParams);
}
}
});
</script>

how to add soap header to react-native?

I use soap header in c# like this :
MeyerWebService.WebServiceEmployees tasnifWS = new MeyerWebService.WebServiceEmployees();
tasnifWS.UserDetailsValue = new UserDetails()
{
userName = "**",
password = "**"
};
But I dont know how to do this in react-native
You can use a simple module for making SOAP requests with WSSecurity
npm install react-native-soap-request --save
Example
const soapRequest = new SoapRequest({
security: {
username: 'username',
password: 'password'
},
targetNamespace: 'http://soap.acme.com/2.0/soap-access-services',
commonTypes: 'http://soap.acme.com/2.0/soap-common-types',
requestURL: soapWebserviceURL
});
const xmlRequest = soapRequest.createRequest({
'soap:ProductRegistrationRequest': {
attributes: {
'xmlns:soap': 'http://soap.acme.com/2.0/soap-access-services',
'xmlns:cmn': 'http://soap.acme.com/2.0/soap-common-types'
},
'soap:productId': {
'cmn:internalId': {
'cmn:id': productId
}
},
'soap:userId': {
'cmn:internalId': {
'cmn:id': userId
}
}
}
});
const response = await soapRequest.sendRequest();

WCF Service's JSON string response to Ajax POST request is not accepted. Method always goes to error.

I have written a WCF service which in theory, should accept a JSON object from Ajax and return true or false as a response to indicate the JSON object was accepted from service and sent to the database.
This is how the interface is implemented in IService
[OperationContract]
[WebInvoke(Method ="POST",ResponseFormat=WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json,UriTemplate ="InsertPatient")]
String InsertPatient(Patient PatientObj);
The contract is implemented as follows
public String InsertPatient(Patient PatientObj)
{
PatientContext pat = new PatientContext();
Boolean boolObj = new Boolean();
string JsonString = "";
if (pat.Patients.Where(x => x.Username == PatientObj.Username).Any())
{
// Username already taken;
boolObj = false;
JsonString =JsonConvert.ToString(boolObj);
return JsonString;
}
else
{ //Initiate to add user to login table
Login log = new Login();
log.Username = PatientObj.Username;
log.Password = PatientObj.Password;
log.User_Type = PatientObj.User_Type;
if (InsertLogin(log)) //if login added
{
pat.Patients.Add(PatientObj); //add user to patient table
pat.SaveChanges();
boolObj = true;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
else //login was not added
{
boolObj = false;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
}
}
and finally the Ajax script is implemented as follows
<script>
$(document).ready(function () {
$("form").submit(function () {
var L_Username = $("#UN").val();
var L_User_Type = "patient";
var L_Name = $("#name").val();
var L_Birthday = $("#bday").val();
var L_Gender = $("input[name='optradio']:checked").val();
var L_Contact = $("#cNo").val();
var L_Password = $("#password").val();
var L_Address = $("#adress").val();
var jsondata = {
Username: L_Username,
User_Type: L_User_Type,
Address: L_Address,
Birthday: L_Birthday,
Contact: L_Contact,
Gender: L_Gender,
Name: L_Name,
Password: L_Password
};
console.log(JSON.stringify(jsondata));
$.ajax({
url: "http://localhost:50709/Service1.svc/rest/InsertPatient",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(jsondata),
success: function (resultdata) {
alert("inserted");
},
error: function (e) {
alert("Something went wrong");
}
});
});
});
</script>
When I test this through POST-man , I get the correct response as true or false. But when I run this from the website itself. Ajax always throw the error alert, but the values get successfully added to the tables.
What am I doing wrong , please help. Thank you in advance.

How can i get remote call on bootstrap twitter typeahead to work, by calling asp.net web method

I am trying to load my typeahead.js by using bloohound's remote function where i can call my Web Method. I have seen similar threads where a querystring is being used :
Integrating Typeahead.js with ASP.Net Webmethod
Typeahead.js and Bloodhound.js integration with C# WebForms WebMethod
http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/
And many more....
However, i cannot find an example where ajax is used to call the webmethod from typeahead.js.
So this is what i have currently and it works:
WebMethod
[WebMethod]
public static string GetEmployeeTypeahead()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = 100000000;
string json;
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1)
.Select(x => new {
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToList();
json = jss.Serialize(result);
}
return json;
}
The Client
function LoadEmployeeJSON() {
$.ajax({
type: "POST",
url: "/WebMethods/Test.aspx/GetEmployeeTypeahead",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
empList = $.parseJSON(msg.d); //otherwise does not work
LoadEmployeeTypeahead();
},
error: function (msg) {
alert("error:" + JSON.stringify(msg));
}
});
}
function LoadEmployeeTypeahead() {
var empData = empList;
var fullname = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: empData,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}
function clearAndReInitilize() {
$('.typeahead').typeahead('destroy');
$('.typeahead').val('');
}
So as you can see i am making a local call instead of remote.
How can i get the remote function to call my webthod and fill the typeahead without using any querystrings
Okay finally got it to work via an ashx generic handler. So instead of using a web method i used the following ashx handler:
public class Employess : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = Int32.MaxValue;
string json;
string prefixText = context.Request.QueryString["query"];
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1 && x.FULLNAME.Contains(prefixText.ToUpper()))
.Select(x => new
{
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToArray();
json = jss.Serialize(result);
}
context.Response.ContentType = "text/javascript";
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Below is the jquery and the ajax call to the ashx handler
$(document).ready(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
LoadEmployeeTypeahead();
// LoadEmployeeJSON();
});
function LoadEmployeeTypeahead() {
//var empData = empList;
var fullname = new Bloodhound({
remote: {
url: '/Employess.ashx?query=%QUERY',
wildcard: '%QUERY'
},
datumTokenizer: function (d) {
//var employees = $.parseJSON(msg.d);
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.MANNO + "</em></span><span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}

how to import JSON data into VS2012 to plot highcharts

I want to import the data from JSON file into my VS2012 c# code so that I can plot my highcharts based on the data in JSON file.
I have checked many video on youtube and file docs but couldnt locate single code that runs and give an output as required.
Do give me a sample code that will map a data from JSON file, use it in vs2012 and plot the highcharts.
----------------Updated Question-------------
Below is the function I am trying to call in java-script where I want to evoke data from JSON format, but I am not able to call my function, below is my code
<script>
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
alert("outside");
$.getJSON('data.json', function (data) {
alert("INside");
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
and want to pass the data to the highcharts ,Since I am novice, any help will be greatly appreciated.
==============EDIT 2 =====================================
the Json file am trying to use for the data is in following format.
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
Thank You.
If JSON file is not rendering on the browser and your are getting 404 error then you might be facing the mime type handling problem, please refer the below link which resolves the issue,
getJSON method does not work
ASP.NET MVC Server Code:
namespace ABPMVCTest.Web.Controllers
{
[AbpMvcAuthorize]
public class HomeController : ABPMVCTestControllerBase
{
static Random _ran=new Random();
public ActionResult Index()
{
return View();
}
public ContentResult GetJsonResult()
{
var dataList = new List<ChartDataFormat>();
GetData(dataList, "总收入");
GetData(dataList, "投币收入");
GetData(dataList, "扫码充电收入");
GetData(dataList, "售线收入");
var dataJsonStr=JsonConvert.SerializeObject(dataList,new JsonSerializerSettings(){ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Content(dataJsonStr);
}
private static List<ChartDataFormat> GetData(List<ChartDataFormat> dataList, string key)
{
var list = new List<int>();
for (int i = 0; i < 7; i++)
{
list.Add(_ran.Next(1, 3000));
}
dataList.Add(new ChartDataFormat
{
Name = key,
Data = list
});
return dataList;
}
}
class ChartDataFormat
{
public string Name { get; set; }
public List<int> Data { get; set; }
}
}
Client javascript Code:
$(function() {
Highcharts.setOptions({
lang: {
printChart: '打印图表',
downloadJPEG: '下载为JPEG图片',
downloadPDF: '下载为PDF',
downloadPNG: '下载为PNG图片',
downloadSVG: '下载为SVG矢量图',
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
weekdays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
}
});
var nowDate = new Date();
var option = {
chart: {
type: 'area'
},
title: {
text: '收入趋势图'
},
subtitle: {
text: '没有选择时间范围的话,默认显示当日/月前后3天/月的数据'
},
credits: {
enabled:false
},
xAxis: {
type: 'datetime',
tickmarkPlacement: 'on',
title: {
enabled: false
},
dateTimeLabelFormats: {
day: "%Y-%m-%d",
week: "%A",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: {
title: {
text: '单位:元'
},
labels: {
formatter: function() {
return this.value;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' 元',
dateTimeLabelFormats: {
day: "%Y-%m-%d,%A",
week: "%A开始, %Y-%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
},
series: {
pointStart:Date.UTC(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate()-3) ,
pointInterval: 24 * 36e5 //一天
}
},
series: [{}]
}
var url = "/Home/GetJsonResult";
$.getJSON(url, function(data) {
option.series = data;
$('#container').highcharts(option);
});
});

Categories

Resources