Posted on 3rd December 2010No Responses
Recurring payment with PayPal Payflow for NopCommerce

This code is for NopCommerce v 1.80

/// <summary>
/// Process recurring payment
/// </summary>
/// <param name=”paymentInfo”>Payment info required for an order processing</param>
/// <param name=”customer”>Customer</param>
/// <param name=”orderGuid”>Unique order identifier</param>
/// <param name=”processPaymentResult”>Process payment result</param>
public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
{
//throw new NopException(“Recurring payments not supported”);

InitSettings();
TransactMode transactionMode = GetCurrentTransactionMode();

//little hack here
CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;
NopContext.Current.SetCulture(new CultureInfo(“en-US”));
try
{
Invoice invoice = new Invoice();

BillTo to = new BillTo();
to.FirstName = paymentInfo.BillingAddress.FirstName;
to.LastName = paymentInfo.BillingAddress.LastName;
to.Street = paymentInfo.BillingAddress.Address1;
to.City = paymentInfo.BillingAddress.City;
to.Zip = paymentInfo.BillingAddress.ZipPostalCode;
to.BillToCountry = paymentInfo.BillingAddress.Country.TwoLetterIsoCode;
if (paymentInfo.BillingAddress.StateProvince != null)
to.State = paymentInfo.BillingAddress.StateProvince.Abbreviation;
invoice.BillTo = to;

if (paymentInfo.ShippingAddress != null)
{
ShipTo to2 = new ShipTo();
to2.ShipToFirstName = paymentInfo.ShippingAddress.FirstName;
to2.ShipToLastName = paymentInfo.ShippingAddress.LastName;
to2.ShipToStreet = paymentInfo.ShippingAddress.Address1;
to2.ShipToCity = paymentInfo.ShippingAddress.City;
to2.ShipToZip = paymentInfo.ShippingAddress.ZipPostalCode;
if (paymentInfo.ShippingAddress.StateProvince != null)
to2.ShipToState = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
invoice.ShipTo = to2;
}

invoice.InvNum = orderGuid.ToString();
decimal orderTotal = Math.Round(paymentInfo.OrderTotal, 2);
invoice.Amt = new PayPal.Payments.DataObjects.Currency(orderTotal, CurrencyManager.PrimaryStoreCurrency.CurrencyCode);

ShoppingCart cart = null;
decimal taxRate = decimal.Zero;
string shippingTotalError1 = string.Empty;
Discount shippingTotalDiscount = null;
decimal? orderShippingTotalInclTax = null;
decimal orderShippingInclTaxInCustomerCurrency = decimal.Zero;
decimal orderSubTotalInclTax = decimal.Zero;
decimal orderSubtotalInclTaxInCustomerCurrency = decimal.Zero;
string itemNames = string.Empty;
if (!paymentInfo.IsRecurringPayment)
{
cart = ShoppingCartManager.GetCustomerShoppingCart(customer.CustomerId, ShoppingCartTypeEnum.ShoppingCart);
foreach (var cartItem in cart) {
itemNames = itemNames + “;” + cartItem.ProductVariant.LocalizedFullProductName;
}
orderShippingTotalInclTax = ShippingManager.GetShoppingCartShippingTotal(cart, customer, true, out taxRate, out shippingTotalDiscount, ref shippingTotalError1);
//in customer currency
orderShippingInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderShippingTotalInclTax.Value, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

string subTotalError1 = ShoppingCartManager.GetShoppingCartSubTotal(cart, customer,
true, out orderSubTotalInclTax);
//in customer currency
orderSubtotalInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderSubTotalInclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

invoice.Amt = new PayPal.Payments.DataObjects.Currency(orderSubtotalInclTaxInCustomerCurrency, CurrencyManager.PrimaryStoreCurrency.CurrencyCode);

}

//Custom comments
invoice.Comment1 = “eStore” + itemNames;
invoice.CommCode = “eStore”;

string creditCardExp = string.Empty;
if (paymentInfo.CreditCardExpireMonth < 10)
{
creditCardExp = “0” + paymentInfo.CreditCardExpireMonth.ToString();
}
else
{
creditCardExp = paymentInfo.CreditCardExpireMonth.ToString();
}
creditCardExp = creditCardExp + paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2);
CreditCard credCard = new CreditCard(paymentInfo.CreditCardNumber, creditCardExp);
credCard.Cvv2 = paymentInfo.CreditCardCvv2;
CardTender tender = new CardTender(credCard);
// <vendor> = your merchant (login id)
// <user> = <vendor> unless you created a separate <user> for Payflow Pro
// partner = paypal
UserInfo userInfo = new UserInfo(user, vendor, partner, password);
string url = GetPaypalUrl();

PayflowConnectionData payflowConnectionData = new PayflowConnectionData(url, 443, 60);

//Set the Recurring related information.
RecurringInfo recurringInfo = new RecurringInfo();
// The date that the first payment will be processed.
// This will be of the format mmddyyyy.
// For billing purposes, assume start date is 48 hours after order is placed.
// If start date occurs in the first 10 days of the month, billing start date is the first of that month.
// If the start date occurs after the first 10 days of the month, the billing start date is the 1st of
// the month following.

DateTime billingStartDate = DateTime.Now.AddDays(2);

if (billingStartDate.Day > 12)
{
billingStartDate = billingStartDate.AddMonths(2);
} else {
billingStartDate = billingStartDate.AddMonths(1);
}

//set billling date to first date of the month
billingStartDate = new DateTime(billingStartDate.Year, billingStartDate.Month, 1, 0, 0, 0);
recurringInfo.Start = billingStartDate.ToString(“MMddyyyy”);

recurringInfo.ProfileName = customer.CustomerId.ToString(); // “PayPal”;
// Specifies how often the payment occurs. All PAYPERIOD values must use
// capital letters and can be any of WEEK / BIWK / SMMO / FRWK / MONT /
// QTER / SMYR / YEAR
recurringInfo.PayPeriod = ((PayPalCyclePeriodEnum)paymentInfo.RecurringCyclePeriod).ToString();
///////////////////////////////////////////////////////////////////

// Perform an Optional Transaction if we need to do this!!
recurringInfo.OptionalTrx = “S”; //S = represents an initial fee, A = Authorization
recurringInfo.OptionalTrxAmt = new PayPal.Payments.DataObjects.Currency(orderTotal, CurrencyManager.PrimaryStoreCurrency.CurrencyCode);

// Create a new Recurring Add Transaction.
RecurringAddTransaction Trans = new RecurringAddTransaction(
userInfo, payflowConnectionData, invoice, tender, recurringInfo, PayflowUtility.RequestId);

// Submit the transaction.
Response response = Trans.SubmitTransaction();

if (response.TransactionResponse != null)
{
if (response.TransactionResponse.Result == 0)
{
processPaymentResult.AuthorizationTransactionId = response.TransactionResponse.Pnref;
processPaymentResult.AuthorizationTransactionResult = response.TransactionResponse.RespMsg;

if (transactionMode == TransactMode.Authorize)
{
processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
}
else
{
processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
}
}
else
{
processPaymentResult.Error = string.Format(“{0} – {1}”, response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
processPaymentResult.FullError = string.Format(“Response Code : {0}. Response Description : {1}”, response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
}
}
else
{
processPaymentResult.Error = “Error during checkout”;
processPaymentResult.FullError = “Error during checkout”;
}

// Get the Recurring Response parameters.
RecurringResponse recurResponse = response.RecurringResponse;
if (recurResponse != null)
{

processPaymentResult.SubscriptionTransactionId = recurResponse.ProfileId;
//Console.WriteLine(“RPREF = ” + recurResponse.RPRef);
//Console.WriteLine(“PROFILEID = ” + recurResponse.ProfileId);
}

}
catch (Exception)
{
throw;
}
finally
{
NopContext.Current.SetCulture(userCulture);
}

}

Comments
Leave a Response
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  This Wordpress Theme is protected. Thanks to 1 Hour Loan