Skip to content

Commit 8743195

Browse files
authored
Add files via upload
1 parent 0956558 commit 8743195

File tree

2 files changed

+201
-196
lines changed

2 files changed

+201
-196
lines changed

PayPalLibrary.php

Lines changed: 60 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -1,168 +1,80 @@
11
<?php
22

3-
class PayPalLibrary {
4-
5-
6-
/*
7-
8-
Example Usage
9-
10-
require_once plugin_dir_path(__FILE__) . 'PayPalLibrary.php';
11-
$paypal = new PayPalLibrary($client_id, $secret, $currency);
12-
$description = get_the_title($post_id);
13-
$return_url = get_permalink($post_id);
14-
$cancel_url = get_permalink($post_id);
15-
return $paypal->generatePurchase($price, $description, $return_url, $cancel_url);
16-
17-
*/
18-
19-
private $client_id;
20-
private $secret;
21-
private $currency;
22-
private $webhook_id;
23-
24-
public function __construct($client_id, $secret, $currency = 'USD', $webhook_id = '') {
25-
$this->client_id = $client_id;
26-
$this->secret = $secret;
27-
$this->currency = $currency;
28-
$this->webhook_id = $webhook_id;
29-
}
30-
31-
public function generatePurchase($amount, $description, $return_url, $cancel_url) {
32-
$auth = base64_encode($this->client_id . ":" . $this->secret);
33-
34-
// Get access token
35-
$ch = curl_init();
36-
curl_setopt($ch, CURLOPT_URL, "https://api.paypal.com/v1/oauth2/token");
37-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
38-
curl_setopt($ch, CURLOPT_POST, 1);
39-
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
40-
curl_setopt($ch, CURLOPT_USERPWD, $this->client_id . ":" . $this->secret);
41-
42-
$headers = array();
43-
$headers[] = "Accept: application/json";
44-
$headers[] = "Accept-Language: en_US";
45-
$headers[] = "Authorization: Basic " . $auth;
46-
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
47-
48-
$result = curl_exec($ch);
49-
curl_close($ch);
50-
51-
if (empty($result)) {
52-
return false;
53-
}
54-
55-
$json = json_decode($result);
56-
$access_token = isset($json->access_token) ? $json->access_token : null;
57-
58-
if (!$access_token) {
59-
return false;
60-
}
61-
62-
63-
// Create payment
64-
$payment_data = array(
65-
"intent" => "sale",
66-
"redirect_urls" => array(
67-
"return_url" => $return_url,
68-
"cancel_url" => $cancel_url,
69-
),
70-
"payer" => array(
71-
"payment_method" => "paypal"
72-
),
73-
"transactions" => array(
74-
array(
75-
"amount" => array(
76-
"total" => $amount,
77-
"currency" => $this->currency
78-
),
79-
"description" => $description
80-
)
3+
require 'vendor/autoload.php';
4+
5+
use PayPal\Api\Amount;
6+
use PayPal\Api\Payer;
7+
use PayPal\Api\Payment;
8+
use PayPal\Api\PaymentExecution;
9+
use PayPal\Api\RedirectUrls;
10+
use PayPal\Api\Transaction;
11+
use PayPal\Rest\ApiContext;
12+
use PayPal\Auth\OAuthTokenCredential;
13+
use PayPal\Exception\PayPalConnectionException;
14+
15+
class PayPalPayment {
16+
private $apiContext;
17+
18+
public function __construct($clientId, $clientSecret) {
19+
$this->apiContext = new ApiContext(
20+
new OAuthTokenCredential(
21+
$clientId, // ClientID
22+
$clientSecret // ClientSecret
8123
)
8224
);
83-
84-
$ch = curl_init();
85-
curl_setopt($ch, CURLOPT_URL, "https://api.paypal.com/v1/payments/payment");
86-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
87-
curl_setopt($ch, CURLOPT_POST, 1);
88-
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
89-
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
90-
"Content-Type: application/json",
91-
"Authorization: Bearer " . $access_token
92-
));
93-
94-
$result = curl_exec($ch);
95-
curl_close($ch);
96-
97-
if (empty($result)) {
98-
return false;
99-
}
100-
101-
$json = json_decode($result);
102-
103-
foreach ($json->links as $link) {
104-
if ($link->rel == 'approval_url') {
105-
return $link->href;
106-
}
107-
}
108-
109-
return false;
110-
}
111-
11225

113-
public function verifyWebhook($event) {
114-
if (!$this->webhook_id) {
115-
return false; // No webhook ID provided
116-
}
117-
118-
$auth = base64_encode($this->client_id . ":" . $this->secret);
26+
$this->apiContext->setConfig([
27+
'mode' => 'live', // or 'sandbox'
28+
'http.ConnectionTimeOut' => 30,
29+
'log.LogEnabled' => false,
30+
'log.FileName' => '',
31+
'log.LogLevel' => 'ERROR',
32+
'cache.enabled' => true,
33+
]);
34+
}
11935

120-
$ch = curl_init();
121-
curl_setopt($ch, CURLOPT_URL, "https://api.paypal.com/v1/notifications/verify-webhook-signature");
122-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
123-
curl_setopt($ch, CURLOPT_POST, 1);
36+
public function createPayment($amount, $currency, $returnUrl, $cancelUrl) {
37+
$payer = new Payer();
38+
$payer->setPaymentMethod('paypal');
12439

125-
$headers = array();
126-
$headers[] = "Content-Type: application/json";
127-
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
40+
$amountObj = new Amount();
41+
$amountObj->setTotal($amount);
42+
$amountObj->setCurrency($currency);
12843

129-
$request_data = array(
130-
"transmission_id" => $_SERVER['HTTP_PAYPAL_TRANSMISSION_ID'],
131-
"transmission_time" => $_SERVER['HTTP_PAYPAL_TRANSMISSION_TIME'],
132-
"cert_url" => $_SERVER['HTTP_PAYPAL_CERT_URL'],
133-
"auth_algo" => $_SERVER['HTTP_PAYPAL_AUTH_ALGO'],
134-
"transmission_sig" => $_SERVER['HTTP_PAYPAL_TRANSMISSION_SIG'],
135-
"webhook_id" => $this->webhook_id,
136-
"webhook_event" => $event
137-
);
44+
$transaction = new Transaction();
45+
$transaction->setAmount($amountObj);
46+
$transaction->setDescription("Payment Description");
13847

139-
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
48+
$redirectUrls = new RedirectUrls();
49+
$redirectUrls->setReturnUrl($returnUrl)
50+
->setCancelUrl($cancelUrl);
14051

141-
$result = curl_exec($ch);
142-
curl_close($ch);
52+
$payment = new Payment();
53+
$payment->setIntent('sale')
54+
->setPayer($payer)
55+
->setTransactions([$transaction])
56+
->setRedirectUrls($redirectUrls);
14357

144-
if (empty($result)) {
145-
return false;
58+
try {
59+
$payment->create($this->apiContext);
60+
} catch (PayPalConnectionException $ex) {
61+
throw new Exception("An error occurred while creating payment: " . $ex->getMessage());
14662
}
14763

148-
$json = json_decode($result);
149-
150-
return $json->verification_status === 'SUCCESS';
64+
return $payment;
15165
}
15266

153-
public function handleWebhook(callable $callback) {
154-
// Retrieve the webhook event from the request
155-
$request_body = file_get_contents('php://input');
156-
$event = json_decode($request_body, true);
67+
public function executePayment($paymentId, $payerId) {
68+
$payment = Payment::get($paymentId, $this->apiContext);
69+
$execution = new PaymentExecution();
70+
$execution->setPayerId($payerId);
15771

158-
// Verify the webhook event
159-
if ($this->verifyWebhook($event)) {
160-
// Execute the callback function with the verified event data
161-
call_user_func($callback, $event);
72+
try {
73+
$result = $payment->execute($execution, $this->apiContext);
74+
} catch (PayPalConnectionException $ex) {
75+
throw new Exception("An error occurred while executing payment: " . $ex->getMessage());
16276
}
16377

164-
// Return a 200 response to PayPal
165-
status_header(200);
166-
exit();
78+
return $result;
16779
}
16880
}

0 commit comments

Comments
 (0)