/// <summary> /// Processes the specified trans data. /// </summary> /// <param name="transData">The trans data.</param> /// <returns></returns> public ResponsePackage Process(TransactionData transData) { if (transData.card == null) { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Credit Card not defined"); } string requestXML = ""; ResponsePackage response = new ResponsePackage(); NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; nfi.NumberDecimalSeparator = "."; requestXML = String.Format("x_version=3.1&x_delim_data=True&" + "x_login={0}&" + "x_password={1}&" + "x_amount={2}&" + "x_card_num={3}&" + "x_exp_date={4}&" + "x_card_code={5}&", _user, _password, transData.totalAmount.ToString("####.00", nfi), transData.card.cardNr, transData.card.expDate.ToString("MMyyyy"), transData.card.CSC); requestXML += transData.card.MakeCustomerInformationString(); requestXML += String.Format( /*"x_test_request=TRUE&"+*/ "x_method=CC&" + "x_type={0}", transData.GetTransactionType()); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(requestXML); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(_serverURL); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); WebResponse myResponse = myRequest.GetResponse(); String rawResponseString = String.Empty; using (StreamReader sr = new StreamReader(myResponse.GetResponseStream())) { rawResponseString = sr.ReadToEnd(); response = ParseResponse(rawResponseString); sr.Close(); } return(response); }
/// <summary> /// Performs the card transaction. /// </summary> /// <param name="transData">The trans data.</param> /// <returns></returns> public ResponsePackage PerformCardTransaction(TransactionData transData) { RequestPackage request = new RequestPackage(_serverURL, _user, _password); ResponsePackage result = request.Process(transData); if (result.IsError) { PaymentException exception = new PaymentException(PaymentException.ErrorType.ProviderError, result.responseCode, result.responseReasonText); // Add additional parameters about the error, which might help end user exception.ResponseMessages.Add("CSCResponse", result.CSCResponse); exception.ResponseMessages.Add("ReasonCode", result.responseReasonCode); exception.ResponseMessages.Add("Subcode", result.responseSubcode); exception.ResponseMessages.Add("AVSResult", result.AVSResult); // now throw the exception throw exception; } return(result); }
/// <summary> /// Parses the response. /// </summary> /// <param name="responseString">The response string.</param> /// <returns></returns> public ResponsePackage ParseResponse(string responseString) { ResponsePackage response = new ResponsePackage(); string[] arr = responseString.Split(','); if (arr[0] != "1") { response.IsError = true; } response.responseCode = GetResponseCodeDescription(arr[0]); response.responseSubcode = arr[1]; response.responseReasonCode = arr[2]; response.responseReasonText = arr[3]; response.approvalCode = arr[4]; response.AVSResult = GetAVSResultCodeDescription(arr[5]); response.transactionID = arr[6]; response.MD5Hash = arr[37]; response.CSCResponse = GetCSCResponseCodeDescription(arr[38]); //response.cardholderAuthenticationResponse = GetCardholderAuthenticationResponseCodeDescription(arr[39]); return(response); }
/// <summary> /// Processes the payment. /// </summary> /// <param name="payment">The payment.</param> /// <param name="message">The message.</param> /// <returns></returns> public override bool ProcessPayment(Payment payment, ref string message) { string erroneousConfigurationMessage = "Authorize.NET payment gateway is not configured correctly. {0} is not set."; // cast the object first CreditCardPayment info = (CreditCardPayment)payment; if (info == null) { message = "Payment information is not specified."; throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } // Check if the gateway is configured correctly string processUrl = String.Empty; string user = String.Empty; string password = String.Empty; string recurringMethod = String.Empty; string cancelStatus = String.Empty; #region Getting parameters from the db // get user name if (!Settings.ContainsKey(_UserParameterName) || String.IsNullOrEmpty(Settings[_UserParameterName])) { message = String.Format(erroneousConfigurationMessage, _UserParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } user = Settings[_UserParameterName]; // get transaction key if (!Settings.ContainsKey(_TransactionKeyParameterName) || String.IsNullOrEmpty(Settings[_TransactionKeyParameterName])) { message = String.Format(erroneousConfigurationMessage, _TransactionKeyParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } password = Settings[_TransactionKeyParameterName]; #endregion bool processRegularTransaction = true; #region --------------- Process Transaction --------------- if (payment.Parent != null && (payment.Parent.Parent is PaymentPlan)) { // get recurring method and determine which type of transaction to perform if (!Settings.ContainsKey(_RecurringMethodParameterName) || String.IsNullOrEmpty(Settings[_RecurringMethodParameterName])) { message = String.Format(erroneousConfigurationMessage, _RecurringMethodParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } recurringMethod = Settings[_RecurringMethodParameterName]; if (String.Compare(recurringMethod, _AuthorizeRecurringMethodParameterValue, StringComparison.OrdinalIgnoreCase) == 0) { processRegularTransaction = false; } } if (processRegularTransaction) { #region Get parameters for the regular transaction // get processing url if (!Settings.ContainsKey(_ProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_ProcessUrlParameterName])) { message = String.Format(erroneousConfigurationMessage, _ProcessUrlParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } processUrl = Settings[_ProcessUrlParameterName]; #endregion #region Process regular transaction AuthorizeNetManager mgr = new AuthorizeNetManager(processUrl, user, password); TransactionData transData = new TransactionData(); transData.card = new CreditCard(); transData.type = Settings[_PaymentOptionParameterName] == "S" ? TransactionType.Sale : TransactionType.Authorization; transData.totalAmount = (double)GetSumInUSD(info.Amount, info.Parent.Parent.BillingCurrency); transData.card.cardNr = info.CreditCardNumber; transData.card.CSC = info.CreditCardSecurityCode; transData.card.expDate = new DateTime(info.ExpirationYear, info.ExpirationMonth, 1); // Find the address OrderAddress address = null; foreach (OrderAddress a in info.Parent.Parent.OrderAddresses) { if (a.Name == info.BillingAddressId) { address = a; break; } } if (address == null) { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Billing address was not specified."); } transData.card.customerAddress = new Authorize.Address(); transData.card.customerAddress.countryCode = address.CountryCode; transData.card.customerAddress.zipCode = address.PostalCode; transData.card.customerAddress.city = address.City; transData.card.customerAddress.state = address.State; transData.card.customerAddress.street = address.Line1; transData.card.customerFirstName = address.FirstName; transData.card.customerLastName = address.LastName; transData.card.customerFax = address.FaxNumber; transData.card.customerPhone = address.DaytimePhoneNumber; transData.card.customerEMail = address.Email; ResponsePackage pkg = null; try { pkg = mgr.PerformCardTransaction(transData); } catch (PaymentException ex) { throw; //message = ex.Message; //return false; } catch { throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway."); } //info.TextResponse = pkg.responseReasonText; info.AuthorizationCode = pkg.responseCode; info.ValidationCode = pkg.approvalCode; #endregion } else { #region Get parameters for the recurring transaction // get processing url if (!Settings.ContainsKey(_RecurringProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_RecurringProcessUrlParameterName])) { message = String.Format(erroneousConfigurationMessage, _RecurringProcessUrlParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } processUrl = Settings[_RecurringProcessUrlParameterName]; // get cancel status if (!Settings.ContainsKey(_CancelStatusParameterName) || String.IsNullOrEmpty(Settings[_CancelStatusParameterName])) { message = String.Format(erroneousConfigurationMessage, _CancelStatusParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } cancelStatus = Settings[_CancelStatusParameterName]; #endregion PaymentPlan plan = (PaymentPlan)payment.Parent.Parent; #region Process recurring Authorize.NET transaction // Payment Plan -> Recurring transaction AuthorizeNetRecurringManager recurringMgr = new AuthorizeNetRecurringManager(processUrl, user, password); ANetApiResponse response = null; try { if (String.Compare(plan.Status, cancelStatus, StringComparison.OrdinalIgnoreCase) == 0) { // cancel subscription if (!String.IsNullOrEmpty(payment.AuthorizationCode)) { ARBCancelSubscriptionResponse cancelResponse = recurringMgr.CancelSubscription(PopulateCancelSubscriptionRequest(info)); // clear the authorization code info.AuthorizationCode = String.Empty; } else { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "Payment AuthorizationCode cannot be null for the CancelSubscription operation", message); } } else if (plan.CompletedCyclesCount == 0) { if (String.IsNullOrEmpty(info.AuthorizationCode)) { // create subscription ARBCreateSubscriptionResponse createResponse = recurringMgr.CreateSubscription(PopulateCreateSubscriptionRequest(info)); response = (ANetApiResponse)createResponse; info.AuthorizationCode = createResponse.subscriptionId; } else { // update subscription recurringMgr.UpdateSubscription(PopulateUpdateSubscriptionRequest(info)); } } else { message = "The operation is invalid."; } } catch (PaymentException ex) { throw ex; } catch { throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway."); } #endregion } #endregion return(true); }