Accepting Payments with PayPal API in PHP
Introduction to PayPal
PayPal is an American-based global online payments system supporting online money transfers, serving as an electronic alternative to traditional paper methods like checks and money orders. Launched in December 1998 as Confinity, it was renamed PayPal in 2001 and has since become one of the world's largest internet payment companies.
PayPal operates as a payment processor for online vendors, auction sites, and many other commercial users, charging a fee for these services. It allows customers to create an account on its platform, which is then connected to a user's credit card or checking account. Once identification and proof of funds have been confirmed, users can begin sending or receiving payments to and from other PayPal accounts online or through the company's app.
Why is PayPal used?
PayPal is used for various reasons:
- Security: PayPal allows users to shop and pay online without directly providing their credit card or bank account information to the vendors. This adds a layer of security to online transactions.
- Convenience: PayPal saves your financial details, meaning you don't need to enter them each time you make a transaction. You can pay by simply entering your PayPal account email and password.
- Global Acceptance: PayPal is accepted worldwide and can handle payments in multiple currencies, making it easy for international shoppers to buy from foreign websites.
- Seller Protection: PayPal offers protection to sellers by providing them with tools and technology to help prevent fraud and secure their businesses.
- Fast Transactions: Transactions via PayPal are usually quick, making it convenient for online shopping.
Here's a simple tutorial explaining each step How to Accept Payments with PayPal API in PHP
1.Setup: Define if you want to use PayPal's sandbox for testing or the live PayPal API. Also, define your PayPal client ID, client secret, and return and cancel URLs.
$enableSandbox = false;
if($enableSandbox){
define("apiUrl", 'https://api.sandbox.paypal.com');
}else{
define("apiUrl", 'https://api.paypal.com');
}
define("clientId", '');
define("clientSecret", '');
define("return_url", $url['home'].'/recharge_status?return=1');
define("cancel_url", $url['home'].'/recharge_status?cancel');
2. Access Token: Get the access token from PayPal. This token is required for authorization when making PayPal API requests.
function get_access_token(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, apiUrl."/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, clientId.":".clientSecret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$result = curl_exec($ch);
if(empty($result)) die("Error: Try with web Dev.");
else
{
$json = json_decode($result);
$accessToken = $json->access_token;
return $accessToken;
}
}
3. Payment Verification: Verify the payment by executing the payment on PayPal.
function verify_payment($paymentId=null){
$accessToken = get_access_token();
// Execute the payment
$paymentData = [
'payer_id' => "S5KCWPRG3DN34" //It's an external unique identifier of a particular PayPal account.
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, apiUrl."/v1/payments/payment/".$paymentId."/execute");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
"Authorization: Bearer $accessToken",
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
// Check for errors and output the payment status
if (isset($result->name)) {
return false;
echo "Error: " . $result->message;
} else {
return $result->state;
}
}
4. Create Payment: Create a new payment. This will setup the payment and return an approval URL, redirecting the user to this URL will allow them to approve the payment on PayPal's site.
function create_payment($amount=null ){
global $last_id;
global $dbh;
$accessToken = get_access_token();
// Create a payment
$paymentData = [
'intent' => 'sale',
'payer' => [
'payment_method' => 'paypal'
],
'transactions' => [
[
'amount' => [
'total' => $amount,
'currency' => 'USD'
],
'description' => 'Buy Divine Coins.'
]
],
'redirect_urls' => [
'return_url' => return_url,
'cancel_url' => cancel_url
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, apiUrl."/v1/payments/payment");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
"Authorization: Bearer $accessToken",
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
// Check for errors and output the approval url
if (isset($result->name)) {
echo "Error: " . $result->message;die;
} else {
$trxid = $result->id;
//insert to db
foreach ($result->links as $link) {
if ($link->rel == 'approval_url') {
$approvalUrl = $link->href;
header("Location: $approvalUrl");
}
}
}
}
Conclusion
PayPal has revolutionized the way we do online transactions. It has made online shopping safer and more convenient, allowing businesses and individuals to make easy, secure, and fast online payments globally. Whether you're an online vendor wanting to simplify the checkout process or a shopper who values security, PayPal is a great option to consider. It's crucial to remember that while PayPal offers various advantages, it's essential to understand their fee structure and ensure it aligns with your personal or business needs.