Online payment using Paypal API

This tip explains about the Direct Payment API i.e how we can do online payment using Direct Payment API.

n order to implement online payment for any website, we can use the PayPal platform.PayPal’s platform accept both credit cards and PayPal account directly on the website.

For the online payment, PayPal provides two API-based solutions: Direct Payment and Express Checkout.

This tip explains about the Direct Payment API i.e how we can do online payment using Direct Payment API.

In case of Direct Payment API,
the customer need not require to have a PayPal account for payment, rather they can pay directly using the credit cards. We just need to display the user a page with text fields, where the user will enter his credit card info and the amount to pay and of course a submit button. In our case let’s name the page as “Payment.aspx” and the button as “btnPayment”.

After entering the details of credit card info and the amount to pay, when the user click on Submit button, the payment information is sent to PayPal using the PayPal DoDirectPayment API operation. PayPal processes the payment information and the amount sumitted by the user get transferred to the seller’s paypal account. All these API operation get executed in the background and when these are getting excuted, the customer is still in the same payment page.

Steps to implement the Online payment using Direct Payment PayPal API:

Processs – 1: Creating PayPal sandbox account

We first need a PayPal sandbox account in the PayPal Sandbox site https://developer.paypal.com/. Once we have completed the sign up and verification process, we should be able to log into our sandbox account.

Processs – 2: Create Test Accounts

After logged in, in the sandbox “Home” page we have a section called “Test Accounts”. Here we need to create one “Seller” and one “Buyer” test account. In the Test Account section, click on “create a preconfigured account” link.

Create a seller account :

Select Website Payments Pro (Use to represent yourself as a merchant using Pro) for the Account type, enter email and password, enter some amount, check “Add bank account” and Click on create account. Once done, generate the API credentials from this account and use it for testing. Lets say, the API credentials generated as below, these credentials will be get used while doing online payment using DoDirectPaypalAPI.

Username = seller_1304145158_biz_api1.gmail.com Password = 1304145176 Signature = AFcWxV21C7fd0v3bYYYRCpSSRl31A4leuYGgGdsuOs6VQyE-12KXdLQt

Create a buyer account:

Same procedure will be followed as that of seller, only the account type should be “Buyer”. After creation the details generated for buyer. Let’s say in our case the details is as below:

Credit Card: Visa 4060180243825030 Exp Date: 4/2016 Bank Account: Checking (Confirmed) Routing Number: 325272063 Bank Account Number: 790406253446848 Balance: 9000.00 USD

Processs – 3: Implementation at the Application level

After all the above set up, now the time is for Application level implementation.

Step-1: Add a web reference to the project.Enter the web service URL as “https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl” and add the service. A new web refernce named as “com.paypal.sandbox.www” will be found inside the WebReference folder.

Step – 2: Add a appsetting key in the web.config file in order to switch between developmnet environment and production environment.


Step – 3: Write code for the Pay button (btnPayment) click event.

Add namespace:-

using PaypalWebApplication.com.paypal.sandbox.www;
Class level variable declaration:-

private string _PaypalUrl;
private UserIdPasswordType _credential;

Here we will collect the following information from the customer which is to be used in the DoDirectPayment operation:

Amount of the transaction, Credit card type, Credit card number, Credit card expiration date, Credit card CVV value, Cardholder first and last name, Cardholder billing address.

Required Fields for the API opeartion are:
Method, IPAddress, CreditCardType, CreditCardNumber, FirstName, LastName, Street1, City, State, CountryCode, Zip, Amt.

With the absence of values for these required fields, the paypal transaction will get failed.

The exection of DoDirectPayment API operation results a response type of DoDirectPaymentResponseType, which will contain the info like Ack code (Success, SuccessWithWarning, or Failure), Amount of the transaction, PayPal transaction ID, Error codes and messages etc.

we can also use DoDirectPaymentResponseType further to obtain various data about the transaction made like PaymentStatus,paymenterrors,TransactionID etc

The information collected here is hardcoded, we can replace it with the value of the corresponding text fields present in the Payment.aspx page. For the credit card info, we are using the details generated for the buyer account .Below is the code for the button click event.

protected void btnPayment_Click(object sender, EventArgs e)
{

//Initialize the paypal inteface ,i.e set the url and the credentials
InitializePaypalInterface();

DoDirectPaymentRequestDetailsType dPRequestDetailsType = new DoDirectPaymentRequestDetailsType();
DoDirectPaymentResponseType dpResponseType = new DoDirectPaymentResponseType();
try

{

//Set The Payer Address Type Info

AddressType addressInfo = new AddressType();
addressInfo.Street1 = "123 Main";
addressInfo.Street2 = "Apt 23";
addressInfo.CityName = "Hill Side";
addressInfo.StateOrProvince = "FL";
addressInfo.PostalCode = "32550";
addressInfo.Country = CountryCodeType.US;

//Set The Payer Name Type Info

PersonNameType payerNameInfo = new PersonNameType();
payerNameInfo.FirstName = "xxx";
payerNameInfo.LastName = "yyy";

//Set Payer Info Details

PayerInfoType payerInformation = new PayerInfoType();
payerInformation.Address = addressInfo;
payerInformation.PayerName = payerNameInfo;

//Set Credit Card details info

CreditCardDetailsType creditCardDetailsInfo = new CreditCardDetailsType();
creditCardDetailsInfo.CreditCardType = CreditCardTypeType.Visa;
creditCardDetailsInfo.CreditCardNumber = "4060180243825030";
creditCardDetailsInfo.ExpMonth = 04;
creditCardDetailsInfo.ExpYear = 2016;
creditCardDetailsInfo.CVV2 = "030";
creditCardDetailsInfo.ExpMonthSpecified = true;
creditCardDetailsInfo.ExpYearSpecified = true;
creditCardDetailsInfo.CardOwner = payerInformation;

//Set amount type info

BasicAmountType amountType = new BasicAmountType();
amountType.Value = "1000";
amountType.currencyID = CurrencyCodeType.USD;

//Set payment details info

PaymentDetailsType payDetailType = new PaymentDetailsType();
payDetailType.OrderTotal = amountType;

//Set the details of DoDirectPaymentRequestDetailsType

dPRequestDetailsType.PaymentDetails = payDetailType;
dPRequestDetailsType.CreditCard = creditCardDetailsInfo;
dPRequestDetailsType.IPAddress = "192.168.10.182"; //get the ipaddress of the machine and Set IP
dPRequestDetailsType.ReturnFMFDetails = true;
dPRequestDetailsType.PaymentAction = PaymentActionCodeType.Sale; //Set Transaction Type

//Set Request
DoDirectPaymentRequestType requestType = new DoDirectPaymentRequestType();

//Set Payment Detail

requestType.DoDirectPaymentRequestDetails = dPRequestDetailsType;
requestType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CountrySpecified = true;

//Set the version

DoDirectPaymentReq req = new DoDirectPaymentReq();
req.DoDirectPaymentRequest = requestType;
req.DoDirectPaymentRequest.Version = "2.0";
dpResponseType.PaymentStatusSpecified = true;

// This needs to be instantiated every time
PayPalAPIAASoapBinding paypalAPIService = GeneratePaypalAPIAAService();

//Do direct payment, API operation which allows you to process a credit card transaction. 
dpResponseType = paypalAPIService.DoDirectPayment(req);

//Check if payment has been made successfully

if (dpResponseType.Ack.ToString() == "Success")
{
//Display the success message
}
else
{
//Display the error message
}

}
catch (Exception ex)
{
}
}

// Create PayPalAPISoapBinding object and set the merchant credential and url propety
public PayPalAPIAASoapBinding GeneratePaypalAPIAAService()
{

PayPalAPIAASoapBinding paypalAPIAAService = new PayPalAPIAASoapBinding();
paypalAPIAAService.RequesterCredentials = new CustomSecurityHeaderType();
paypalAPIAAService.RequesterCredentials.Credentials = _credential;
paypalAPIAAService.Url = _PaypalUrl;
return paypalAPIAAService;

}

// Generate paypal interface

public void InitializePaypalInterface()
{

PayPalAPISoapBinding PPInterface = new PayPalAPISoapBinding();
UserIdPasswordType cred = new UserIdPasswordType();
string url = string.Empty;

// Initialize the PayPal interface 
PPInterface.RequesterCredentials = new CustomSecurityHeaderType();
// Read Web.config to determine if we are using a Paypal for Production environment or for Sandbox Environment
if (WebConfigurationManager.AppSettings["PaypalEnvironment"].ToLower() == "production")
{
// credentials for Production
url = "https://api-3t.paypal.com/2.0/"; 
cred.Username = "your username";
cred.Password = "your password";
cred.Signature = "your signature";
}
else
{
// Sandbox, credential for testing , here we are using the API Credential generated for the seller account
url = "https://api.sandbox.paypal.com/2.0/"; 
cred.Username = "seller_1304145158_biz_api1.gmail.com";
cred.Password = "1304145176";
cred.Signature = "AFcWxV21C7fd0v3bYYYRCpSSRl31A4leuYGgGdsuOs6VQyE-12KXdLQt";

}
_credential = cred;
_PaypalUrl = url;

}

After the execution if we go to the test account page and click the “view details” link of seller/business account, then we can found the amount sumitted by the customer (here hardcoded to $1000.00) has been added to the seller’s account.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!