using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Security.Cryptography;
private const string xmlDoc = "<htmlSection class=\"payment-content\" xmlns=\"Paymetric:XiIntercept:MerchantHtmlPacketModel\"> <tag name=\"div\" class=\"merchant-logo\"> </tag> <tag name=\"div\" class=\"billing-content\"> <tag name=\"div\" class=\"billing-header\">Billing Information</tag> <tag name=\"div\" class=\"billing-info\"> <paymentOptionRadioSection> <tag name='div'> <tag name='div'>choose payment type</tag> </tag> <label text=\"echeck\" for=\"echeck\"/> <radPaymentOption for=\"echeck\"/> <label text=\"credit card\" for=\"card\"/> <radPaymentOption for=\"card\"/> </paymentOptionRadioSection> <cardDropdownSection> <tag name='div'>Enter your credit card information</tag> <tag name=\"div\"> <label for=\"cardType\" text=\"select a card\"/> <ddlCardType id=\"cd\"> <items> <item for=\"american express\"/> <item for=\"mastercard\"/> <item for=\"visa\"/> <customItem for=\"MSC\" text=\"My Super Card\"/> </items> </ddlCardType> </tag> <tag name='div'> <label for='cardNumber' text='card number'/> <tboxCardNumber tokenize='true'/> </tag> <tag name='div'> <label for='cardholderName' text='name on card'/> <tboxCardHolderName /> </tag> <tag name='div'> <label for='expMonth' text='exp date'/> <ddlExpMonth default-text=\"month\" class='merchant_combos'/> <ddlExpYear default-text=\"year\" class='merchant_combos' years-to-display='10'/> </tag> <tag name='div'> <label for=\"cvv\" text=\"card cvv:\"/> <tboxCvv/> <htmlCvvHelp name='div' raise-click='1'></htmlCvvHelp> </tag> </cardDropdownSection> <echeckRadioSection> <tag name='div'> <label for=\"checking\"/> <radAccountType for=\"checking\"/> <label for=\"savings\"/> <radAccountType for=\"savings\"/> </tag> <tag name='div'> <label for=\"accountNumber\" text=\"account number\"/> <tboxAccountNumber tokenize=\"true\"/> </tag> <tag name='div'> <label for=\"routingNumber\" text=\"routing number\"/> <tboxRoutingNumber/> </tag> <tag name='div'> <label for=\"nameOnAccount\" text=\"name on account\"/> <tboxNameOnAccount/> </tag> <tag name='div'> <label for=\"bankName\" text=\"bank name\"/> <tboxBankName/> </tag> </echeckRadioSection> </tag> <tag name=\"div\" class=\"payment-button\"> <cancelButton text=\"cancel\" class=\"cancel-button\"/> <submitButton text=\"submit\" class=\"submit-button\"/> </tag> </tag> </htmlSection>";
private const string MerchantDevelopmentEnvironment = "asp.net";
public static void Main()
var nextError = PmEvents.UnexpectedError;
string merchantGuid = "fb29a97a-4a98-497a-a187-745f7257bc9c";
string sharedKey = @"A_g4rZ9{R}y5=2JeMo7+s$D68Bk*L/3a";
string xiInterceptRootUrl = "https://qaapp02.xisecurenet.com/diecomm";
int sessionRequestType = (int)SessionCreateRequestTypes.Hosted;
MerchantHtmlPacketModel.CreditCardTemplate,
MerchantHtmlPacketModel.CreditCardCVVTemplate,
MerchantHtmlPacketModel.CreditCardCVVAddressTemplate
var merchantHtmlPacket = new MerchantHtmlPacketModel();
merchantHtmlPacket.PacketType = new PaymentPagePacket()
CssUri = "https://qaapp02.xisecurenet.com/diecomm/Content/PaymentStyleSheet.css",
RedirectUri = "https://goimmortalize.me/order/1/confirmation/"
merchantHtmlPacket.SetHtmlTemplateName(templates[0]);
merchantHtmlPacket.AddTemplatePaymentType(TemplatePaymentTypeCode.AmericanExpress);
merchantHtmlPacket.AddTemplatePaymentType(TemplatePaymentTypeCode.MasterCard);
merchantHtmlPacket.AddTemplatePaymentType(TemplatePaymentTypeCode.Maestro);
merchantHtmlPacket.AddTemplatePaymentType(TemplatePaymentTypeCode.Visa);
string packet = merchantHtmlPacket.Serialize();
var signature = Utility.SignData(packet, sharedKey);
var url = string.Format(@"{0}/AccessToken", xiInterceptRootUrl);
var postData = string.Format("MerchantGuid={0}&SessionRequestType={1}&Packet={2}&Signature={3}&MerchantDevelopmentEnvironment={4}",
HttpUtility.UrlEncode(packet),
HttpUtility.UrlEncode(signature),
MerchantDevelopmentEnvironment);
nextError = PmEvents.CreateRequestFailed;
var data = Encoding.ASCII.GetBytes(postData);
var request = WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
stream.Write(data, 0, data.Length);
nextError = PmEvents.GetResponseFailed;
var response = (HttpWebResponse)request.GetResponse();
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();
nextError = PmEvents.DeserializationFailed;
responseFromServer.Dump();
Console.WriteLine("StatusCode = {0}", (int) PmEvents.NoServerResponse);
Console.WriteLine("DT = {0}", DateTime.UtcNow);
Console.WriteLine("Message = {0}", Utility.GetDescription(PmEvents.NoServerResponse));
Console.WriteLine("StatusCode = {0}", (int) nextError);
Console.WriteLine("DT = {0}", DateTime.UtcNow);
Console.WriteLine("Message = {0}", Utility.GetDescription(PmEvents.NoServerResponse));
Console.WriteLine("ExceptionMessage = {0}", ex.Message);
public static class Utility
public static string Serialize<T>(T inputObject)
using (var memoryStream = new MemoryStream())
using (var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(xmlTextWriter, inputObject);
using (var xmlTextWriterMemoryStream = (MemoryStream)xmlTextWriter.BaseStream)
var utf8Encoding = new UTF8Encoding();
xml = utf8Encoding.GetString(xmlTextWriterMemoryStream.ToArray()).Substring(1);
xml = string.Format("Serialize Exception :{0}", ex.Message);
public static T Deserialize<T>(string xml) where T : class
var settings = new XmlReaderSettings();
var xmlReader = XmlReader.Create(new StringReader(xml), settings);
var serializer = new XmlSerializer(typeof(T));
var deserializedObject = serializer.Deserialize(xmlReader);
return (T)deserializedObject;
public static string SignData(string dataToSign, string signatureKey)
return Convert.ToBase64String(GetHmac(dataToSign, signatureKey));
private static byte[] GetHmac(string data, string key)
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
return GetHmac(dataBytes, keyBytes);
private static byte[] GetHmac(byte[] contents, byte[] key)
HMAC hashAlg = HMAC.Create("HMACSHA256");
byte[] returnValue = hashAlg.ComputeHash(contents);
return System.Text.Encoding.Default.GetBytes(e.Message);
internal static string GetDescription(Enum en)
var memInfo = type.GetMember(en.ToString());
if (memInfo.Length <= 0) return en.ToString();
var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return attrs.Length > 0 ? ((DescriptionAttribute)attrs[0]).Description : en.ToString();
[Description("An unexpected error occurred processing the server request")]
[Description("Failed to create the web request")]
CreateRequestFailed = -101,
[Description("Failed while retrieving the response")]
GetResponseFailed = -102,
[Description("The server did not return a response packet")]
[Description("Failed to deserialize the response packet")]
DeserializationFailed=-104,
[Description("Debug Trace: \n{0}\n")]
[Description("Internal DI eComm Error \n{0}")]
[Description("Merchant GUID is Invalid")]
InvalidMerchantGuid = 101,
[Description("Signature Validation Failed")]
[Description("Request Packet is Invalid \n{0}\n{1}\n{2}\n")]
[Description("Request Packet is Invalid")]
[Description("DI eComm Session has Expired")]
DIeCommSessionExpire = 104,
[Description("DI eComm Session Error")]
DIeCommSessionIssue = 105,
[Description("DI eComm Session Error - '{0}'")]
DIeCommSessionIssueWithParam = 105,
[Description("Error Decrypting Data")]
[Description("Get Access Token Error")]
GetAccessTokenError = 107,
[Description("Get Access Token Error - '{0}'")]
GetAccessTokenErrorWithParam = 107,
[Description("Requested type hasn't been purchased.")]
RequestedAccessTokenDenied = 108,
[Description("Error Retrieving Access Token")]
ErrorInRetrievingAccessToken = 109,
[Description("Error Writing Access Token ")]
ErrorWritingAccessToken = 110,
[Description("Invalid Redirect URL")]
InvalidRedirectUrl = 111,
[Description("Invalid Redirect URL: '{0}'")]
InvalidRedirectWithParam = 111,
[Description("XiSecure Error")]
[Description("XiSecure No Token")]
[Description("XiSecure Detokenized Value does not match original value. {0} != {1}")]
XiSecureDetokenizationMismatch = 121,
[Description("XiSecure Certificate Expired UID: {0}, Expiration Date {1}")]
XiSecureCertificateExpired = 122,
[Description("Error Accessing Database: {0}")]
[Description("No MasterPass Configuration")]
MasterPassNoConfiguration = 200,
[Description("Invalid MasterPass Credentials")]
MasterPassInvalidCredentials = 201,
[Description("Error Communicating with MasterPass")]
MasterPassCommunicationError = 202,
[Description("No Error, Customer Canceled MasterPass")]
MasterPassCustomerCancel = 203,
[Description("Cardinal Commerce Response: \n{0}")]
CardinalCommerceIssue = 300,
[Description("No Cardinal Commerce Configuration:")]
CardinalCommerceNoConfiguration = 301,
[Description("The Cardinal Commerce configuration is missing information:")]
CardinalCommerceInformationMissing = 302,
[Description("An attempt was made to load the payment page in an IFrame:")]
PaymentPageLoadedInIFrame = 401,
[Description("The Alliance Data web service could not accomodate version number.")]
AllianceDataVersion = 501,
[Description("The Alliance Data web service could not accomodate version number - version='{0}'.")]
AllianceDataVersionWithParam = 501,
[Description("No Alliance Data Configuration.")]
AllianceDataNoConfiguration = 502,
[Description("There was an error in communicating with the Alliance Data web service.")]
AllianceDataCommunicationIssue = 503,
[Description("The Alliance Data web service suggests it was given invalid credentials.")]
AllianceDataInvalidCredentials = 504,
[Description("The Alliance Data web service suggests it was given invalid credentials '{0}'.")]
AllianceDataInvalidCredentialsWithParam = 504,
[Description("There was an error in communicating with the Alliance Data web service '{0}'.")]
AllianceDataWebServiceCall = 505
[Description("DI eComm")]
[Description("MasterPass")]
[Description("Debugging")]
public enum SessionCreateRequestTypes
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "Paymetric:XiIntercept:MerchantHtmlPacketModel")]
public partial class PaymentPagePacket
private string redirectUriField;
private string cssUriField;
private PaymentPagePacketCardinal3DSecure cardinal3DSecureField;
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI", ElementName = "redirectUri")]
public string RedirectUri
return this.redirectUriField;
this.redirectUriField = value;
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI", ElementName = "cssUri")]
this.cssUriField = value;
[System.Xml.Serialization.XmlElementAttribute("cardinal3DSecure", typeof(PaymentPagePacketCardinal3DSecure))]
public PaymentPagePacketCardinal3DSecure Cardinal3DSecure
return this.cardinal3DSecureField;
this.cardinal3DSecureField = value;
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "Paymetric:XiIntercept:MerchantHtmlPacketModel")]
public partial class PaymentPagePacketCardinal3DSecure
private decimal amountField;
private string currencyCodeField;
private string orderNumberField;
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "amount")]
this.amountField = value;
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "currencyCode")]
public string CurrencyCode
return this.currencyCodeField;
this.currencyCodeField = value;
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "orderNumber")]
public string OrderNumber
return this.orderNumberField;
this.orderNumberField = value;
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class MerchantHtmlPacketModelMerchantHtml
[EditorBrowsable(EditorBrowsableState.Never)]
public XmlElement[] PaymentSectionContainerElements { get; set; }
public partial class MerchantHtmlPacketModel
public const string CreditCardTemplate = "CreditCard";
public const string CreditCardCVVTemplate = "CreditCardCVV";
public const string CreditCardCVVAddressTemplate = "CreditCardCVVAddress";
public PaymentPagePacket PaymentPagePacket
get { return packetTypeField as PaymentPagePacket; }
set { packetTypeField = value; }
public MerchantHtmlPacketModelTemplateHtml TemplateHtml
get { return htmlTypeField as MerchantHtmlPacketModelTemplateHtml; }
set { htmlTypeField = value; }
public MerchantHtmlPacketModelMerchantHtml MerchantHtml
get { return htmlTypeField as MerchantHtmlPacketModelMerchantHtml; }
set { htmlTypeField = value; }
public void SetMerchantHtmlString(string merchanHtml)
htmlTypeField = new MerchantHtmlPacketModelMerchantHtml();
var xdoc = new XmlDocument();
xdoc.LoadXml(merchanHtml.Trim());
this.HtmlType = new MerchantHtmlPacketModelMerchantHtml() { PaymentSectionContainerElements = new[] { xdoc.DocumentElement } };
public void SetHtmlTemplateName(string templateName)
htmlTypeField = new MerchantHtmlPacketModelTemplateHtml() {Name = templateName};
public void AddTemplatePaymentType(TemplatePaymentTypeCode paymentType)
if (TemplateHtml == null)
throw new ApplicationException("No template name is set. Call 'SetHtmlTemplateName' before adding payment types.");
throw new InvalidEnumArgumentException("parameter 'paymentType' is invalid.");
if (paymentType == TemplatePaymentTypeCode.Custom)
throw new ArgumentNullException("displayText", "Parameter 'displayText' is required for custom payment types.");
AddTemplatePaymentType(paymentType, null, null, null, null, null, null);
public void AddTemplatePaymentType(TemplatePaymentTypeCode paymentType, string displayText, string value,
bool? showStartDate, bool? showExpDate, bool? showCvv, bool? showCardholderName)
if (TemplateHtml == null)
throw new ApplicationException("No template name is set. Call 'SetHtmlTemplateName' before adding payment types.");
throw new InvalidEnumArgumentException("parameter 'paymentType' is invalid.");
if (paymentType == TemplatePaymentTypeCode.Custom)
if (string.IsNullOrEmpty(displayText))
throw new ArgumentNullException("displayText", "Parameter 'displayText' is required for custom payment types.");
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException("value", "Parameter 'value' is required for custom payment types.");
if (!string.IsNullOrEmpty(value))
throw new ArgumentException("Parameter 'value' cannot be used for non-custom payment types", "value");
if (showStartDate == null && paymentType == TemplatePaymentTypeCode.Maestro)
var templatePaymentType = new TemplatePaymentType()
if (showCardholderName != null)
templatePaymentType.ShowCardholderName = (bool)showCardholderName;
templatePaymentType.ShowCvv = (bool)showCvv;
templatePaymentType.ShowExpDate = (bool)showExpDate;
if (showStartDate != null)
templatePaymentType.ShowStartDate = (bool)showStartDate;
TemplateHtml.PaymentTypes.Add(templatePaymentType);
private object packetTypeField;
private object htmlTypeField;
[System.Xml.Serialization.XmlElementAttribute("paymentPagePacket", typeof(PaymentPagePacket))]
return this.packetTypeField;
this.packetTypeField = value;
[System.Xml.Serialization.XmlElementAttribute("merchantHtml", typeof(MerchantHtmlPacketModelMerchantHtml))]
[System.Xml.Serialization.XmlElementAttribute("templateHtml", typeof(MerchantHtmlPacketModelTemplateHtml))]
return this.htmlTypeField;
this.htmlTypeField = value;
public virtual string Serialize()
var result = Utility.Serialize(this);
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "Paymetric:XiIntercept:MerchantHtmlPacketModel")]
public partial class MerchantHtmlPacketModelTemplateHtml
private List<TemplatePaymentType> _paymentTypes;
public MerchantHtmlPacketModelTemplateHtml()
this._paymentTypes = new List<TemplatePaymentType>();
[System.Xml.Serialization.XmlArrayAttribute(ElementName = "paymentTypes")]
[System.Xml.Serialization.XmlArrayItemAttribute(ElementName = "paymentType", IsNullable = false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public List<TemplatePaymentType> PaymentTypes
return this._paymentTypes;
this._paymentTypes = value;
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "name")]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "Paymetric:XiIntercept:MerchantHtmlPacketModel")]
public partial class TemplatePaymentType
private System.Nullable<TemplatePaymentTypeCode> _type;
private System.Nullable<bool> _showexpdateField;
private System.Nullable<bool> _showstartdateField;
private System.Nullable<bool> _showcvvField;
private System.Nullable<bool> _showcardholdernameField;
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "type")]
public TemplatePaymentTypeCode Type
return default(TemplatePaymentTypeCode);
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool typeSpecified
return this._type.HasValue;
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "value")]
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "text")]
[System.Xml.Serialization.XmlAttributeAttribute("show-exp-date")]
if (this._showexpdateField.HasValue)
return this._showexpdateField.Value;
this._showexpdateField = value;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ShowExpDateSpecified
return this._showexpdateField.HasValue;
this._showexpdateField = null;
[System.Xml.Serialization.XmlAttributeAttribute("show-start-date")]
public bool ShowStartDate
if (this._showstartdateField.HasValue)
return this._showstartdateField.Value;
this._showstartdateField = value;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ShowStartDateSpecified
return this._showstartdateField.HasValue;
this._showstartdateField = null;
[System.Xml.Serialization.XmlAttributeAttribute("show-cvv")]
if (this._showcvvField.HasValue)
return this._showcvvField.Value;
this._showcvvField = value;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ShowCvvSpecified
return this._showcvvField.HasValue;
this._showcvvField = null;
[System.Xml.Serialization.XmlAttributeAttribute("show-cardholder-name")]
public bool ShowCardholderName
if (this._showcardholdernameField.HasValue)
return this._showcardholdernameField.Value;
this._showcardholdernameField = value;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ShowCardholderNameSpecified
return this._showcardholdernameField.HasValue;
this._showcardholdernameField = null;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "Paymetric:XiIntercept:MerchantHtmlPacketModel")]
public enum TemplatePaymentTypeCode
[System.Xml.Serialization.XmlEnumAttribute("american express")]
[System.Xml.Serialization.XmlEnumAttribute("discover")]
[System.Xml.Serialization.XmlEnumAttribute("jcb")]
[System.Xml.Serialization.XmlEnumAttribute("maestro")]
[System.Xml.Serialization.XmlEnumAttribute("mastercard")]
[System.Xml.Serialization.XmlEnumAttribute("visa")]
[System.Xml.Serialization.XmlEnumAttribute("custom")]