One thing that any good development company should do is strive to create reusable code. Thinking back to projects I’ve worked on in my first year here, it occurred to me that quite a few of them have involved some form of online payment processing. However, each client has used a different payment processor that has required custom programming. I began thinking how nice it would be to submit a generic payment object to a gateway with large disregard to what particular vendor the payment is being submitted to. Early on in developing this, it occurred to me that a factory pattern would be the way to go; essentially what I want is a “factory” that will figure out what type of online payment gateway I need and construct that for me.
To start things, I made a simple payment .NET gateway interface to make sure my gateway objects will do the one thing I need them to:
public interface IPaymentGateway
string SubmitPayment(Payment payment);
Essentially what I’m saying here is that no matter what type of gateway I’m using, I’ll need to submit a payment.
Next, we have a simple factory pattern to return some type of gateway:
public class PaymentGatewayFactory
public IPaymentGateway CreatePaymentGateway()
PaymentGatewayRepository paymentGatewayRepository = new PaymentGatewayRepository();
string gatewayType = paymentGatewayRepository.GetGatewayType();
return new Authnet();
return new Paypal();
return new PayflowPro();
throw new NotSupportedException(“This payment gateway is not supported.”);
Here we have a call to a PaymentGatewayRepository class (not included), which will read a config file and return a string representing what type of payment gateway the client is using. Next, a simple switch is done that will return the appropriate payment gateway class (or a custom exception if the gateway is not yet supported). Each of the gateway classes implements the IPaymentGateway interface.
The beauty of this is that once this project is built, submitting payments is a breeze. Just include the assembly in a project, reference it, and then follow these three easy steps:
- Add the necessary config keys.
<!– Authnet Keys –>
<!-- Gateway types | Possible Values: Authnet, Paypal, Payflow -->
<add key="GatewayType" value="Authnet">
<add key=”Anet_URL” value=”http://test.authorize.net/gateway/transact.dll”/>
<add key=”payment_login_key” value=”123456789″/>
<add key=”payment_tran_key” value=”987654321″/>
<add key=”payment_auth_name” value=”Example”/>
- Build the payment object.
Payment payment = new Payment();
payment.BillingFirstName = "Jeremy";
payment.BillingLastName = "Wiggins";
- Submit the payment.
IPaymentGateway gateway = new PaymentGatewayFactory().CreatePaymentGateway();
And that’s all there is to it. This will be a nice addition to a reusable component library. Once the logic has been implemented for a new payment gateway, it never has to be thought about again. Just add a few lines to a config file and submit payments in a couple of easy steps.