Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/dotnet core 3.1 #11

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
# CyberSource Flex Samples (.NET)

This repository provides simple examples demonstrating usage of the CyberSource Flex SDK using either a headless JavaScript call (flex-js-sample) or a fully customizable hosted field/microform which is incorporated into your checkout page (flex-microform-sample). For more details on Secure Acceptance Flex visit our Developer Guide at https://developer.cybersource.com/api/developer-guides/dita-flex/SAFlexibleToken.html
This repository provides simple examples demonstrating usage of the CyberSource Flex SDK using either
1. a headless JavaScript call (`flex-js-sample`) or
2. a fully customizable hosted field/microform which is incorporated into your checkout page (`flex-microform-sample` for .NET Framework 4.6.1 or `flex_microform_dotnet_core_sample` for .NET Core 3.1)

For more details on Secure Acceptance Flex visit our Developer Guide at https://developer.cybersource.com/api/developer-guides/dita-flex/SAFlexibleToken.html

## Usage

1. Clone or download this repository.
2. Open the solution cybersource-flex-samples-dotnet.sln in Visual Studio
2. Open the solution `cybersource-flex-samples-dotnet.sln` in Visual Studio
3. Update the Configuration class in HomeController.cs with your [CyberSource sandbox credentials](https://ebc2test.cybersource.com).
4. Choose either the flex-js-sample or flex-microform-sample as your startup project
4. Choose either the `flex-js-sample` or `flex-microform-sample` or `flex_microform_dotnet_core_sample` as your startup project
4. Run the Program (F5)


Note:
It may be nessesary to reinsatll the packages
execute the following command in the NuGet package manager
```powershell
PM> Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
```

## Requirements
* Visual Studio 2017
* Visual Studio 2017+

**_NOTE: We also have samples for Flex available in Java, PHP & Node.js _**
**_NOTE: We also have samples for Flex available in Java, PHP & Node.js_**

## API Reference
While these examples use the JavaScript libraries which we recommend as the most convenient option, you can try out the APIs behind the JavaScript SDKs by visiting our API Reference at https://developer.cybersource.com/api/reference/api-reference.html
Expand Down
10 changes: 8 additions & 2 deletions cybersource-flex-samples-dotnet.sln
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.329
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "flex-microform-sample", "flex-microform-sample\flex-microform-sample.csproj", "{8664E36A-7BEF-4EF8-90E2-51F42FC8D192}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "flex-js-sample", "flex-js-sample\flex-js-sample.csproj", "{43352956-8844-4E83-AD6A-10A451B05618}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "flex-microform-dotnet-core-sample", "flex-microform-dotnet-core-sample\flex-microform-dotnet-core-sample.csproj", "{795DA2D4-DA19-44C1-A12D-B9F480BDDA4E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -21,6 +23,10 @@ Global
{43352956-8844-4E83-AD6A-10A451B05618}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43352956-8844-4E83-AD6A-10A451B05618}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43352956-8844-4E83-AD6A-10A451B05618}.Release|Any CPU.Build.0 = Release|Any CPU
{795DA2D4-DA19-44C1-A12D-B9F480BDDA4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{795DA2D4-DA19-44C1-A12D-B9F480BDDA4E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{795DA2D4-DA19-44C1-A12D-B9F480BDDA4E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{795DA2D4-DA19-44C1-A12D-B9F480BDDA4E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
3 changes: 3 additions & 0 deletions cybersource-flex-samples-dotnet.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Cyber/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=microform/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
153 changes: 153 additions & 0 deletions flex-microform-dotnet-core-sample/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
using CyberSource.Api;
using CyberSource.Model;
using flex_microform_dotnet_core_sample.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace flex_microform_dotnet_core_sample.Controllers
{
public static class Configuration
{
public static Dictionary<string, string> GetDictionary()
=> new Dictionary<string, string>
{
{ "authenticationType", "HTTP_SIGNATURE" },
{ "merchantID", "testrest" },
{ "merchantsecretKey", "yBJxy6LjM2TmcPGu+GaJrHtkke25fPpUX+UY6/L/1tE=" },
{ "merchantKeyId", "08c94330-f618-42a3-b09d-e1e43be5efda" },
{ "keysDirectory", "Resource" },
{ "keyFilename", "testrest" },
{ "runEnvironment", "apitest.cybersource.com" },
{ "keyAlias", "testrest" },
{ "keyPass", "testrest" },
{ "enableLog", "FALSE" },
{ "logDirectory", string.Empty },
{ "logFileName", string.Empty },
{ "logFileMaxSize", "5242880" },
{ "timeout", "1000" },
{ "proxyAddress", string.Empty },
{ "proxyPort", string.Empty }
};
}

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger) => _logger = logger;

public IActionResult Index() => View();

public async Task<IActionResult> CheckoutAsync()
{
try
{
var apiInstance = new KeyGenerationApi(
new CyberSource.Client.Configuration(
merchConfigDictObj: Configuration.GetDictionary()));

// Generating Capture Context Request Payload
// Defining Encryption Type = RsaOaep
// Defining TargetOrigin = http://localhost:65309
var requestObj = new GeneratePublicKeyRequest("RsaOaep256", "http://localhost:65309");

// Initiating public Key request
// query parameter set to format=JWT for Flex 11
var result = await apiInstance.GeneratePublicKeyAsync("JWT", requestObj);

_logger.LogInformation(JsonConvert.SerializeObject(result));
_logger.LogInformation(result.KeyId);

// result.KeyId here is the temporary token
ViewBag.Jwk = result.KeyId;
}
catch (Exception e)
{
_logger.LogError("Exception on calling the API: " + e.Message);
}

return View();
}

/// <summary>
/// This is not important, just to show the token
/// </summary>
public IActionResult Token()
{
var flexObj = Request.Form["flexResponse"];
var cardHolderName = Request.Form["cardholderName"];

ViewBag.CardHolderName = cardHolderName[0];
ViewBag.JWT = flexObj[0].Replace("\r\n", "").Replace("\"", "");

return View();
}

public async Task<IActionResult> Receipt()
{
// This is the Transient token combining temporary token and the credit card info
var transientToken = Request.Form["flexResponse"][0];

try
{
// Same as above
var apiInstance = new PaymentsApi(
new CyberSource.Client.Configuration(
merchConfigDictObj: Configuration.GetDictionary()));

var requestObj = new CreatePaymentRequest
{
// Processing Authorization Request
// Code developed from CyberSource Rest Samples csharp
// https://github.com/CyberSource/cybersource-rest-samples-csharp
ProcessingInformation = new Ptsv2paymentsProcessingInformation { CommerceIndicator = "internet" },
ClientReferenceInformation = new Ptsv2paymentsClientReferenceInformation { Code = "test_payment" },
OrderInformation = new Ptsv2paymentsOrderInformation
{
BillTo = new Ptsv2paymentsOrderInformationBillTo
{
Country = "US",
FirstName = "John",
LastName = "Doe",
Address1 = "1 Market St",
PostalCode = "94105",
Locality = "San Francisco",
AdministrativeArea = "CA",
Email = "[email protected]"
},
AmountDetails = new Ptsv2paymentsOrderInformationAmountDetails
{
TotalAmount = "102.21",
Currency = "USD"
}
},
// Passing Transient token
TokenInformation = new Ptsv2paymentsTokenInformation { TransientTokenJwt = transientToken }
};

var result = await apiInstance.CreatePaymentAsync(requestObj);

_logger.LogInformation(JsonConvert.SerializeObject(result));

//Making response pretty & passing to page
ViewBag.PaymentResponse = result;
}
catch (Exception e)
{
_logger.LogError("Exception on calling the API: " + e.Message);
return null;
}

return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
=> View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
11 changes: 11 additions & 0 deletions flex-microform-dotnet-core-sample/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace flex_microform_dotnet_core_sample.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
26 changes: 26 additions & 0 deletions flex-microform-dotnet-core-sample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace flex_microform_dotnet_core_sample
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
53 changes: 53 additions & 0 deletions flex-microform-dotnet-core-sample/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace flex_microform_dotnet_core_sample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Loading