Skip to content

Commit d2be6e9

Browse files
committed
Merge branch '1.x-develop' into 1.x
2 parents fb501d2 + 0b6213c commit d2be6e9

File tree

3 files changed

+683
-6
lines changed

3 files changed

+683
-6
lines changed

Libraries/VaahPayPal.md

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
# VaahPayPal
2+
> Small Laravel Helpers
3+
4+
### Installation
5+
6+
VaahPaypal provides to you a simple way to integrate Paypal in your Laravel application.
7+
8+
### Dependencies
9+
- [PayPal-PHP-SDK](https://github.com/paypal/PayPal-PHP-SDK)
10+
11+
### Installation
12+
13+
```shell script
14+
composer require paypal/rest-api-sdk-php
15+
```
16+
### Add env variables:
17+
18+
`PayPal live` and `PayPal sandbox` are two different environments for using the PayPal API. The live environment is the real PayPal network that processes actual payments, while the sandbox environment is a simulated test environment that allows developers to test their integration with the PayPal API without using real money.
19+
```env
20+
## For PayPal Sandbox
21+
PAYPAL_MODE=sandbox
22+
PAYPAL_SANDBOX_CLIENT_ID=xxxxxxxxxxxxxxx
23+
PAYPAL_SANDBOX_CLIENT_SECRET=xxxxxxxxxxxxx
24+
## For PayPal Live
25+
PAYPAL_MODE=live
26+
PAYPAL_LIVE_CLIENT_ID=xxxxxxxxxxxxxxx
27+
PAYPAL_LIVE_CLIENT_SECRET=xxxxxxxxxxxxx
28+
```
29+
To obtain your PayPal sandbox client ID and client secret, you will need to complete the following steps:
30+
31+
1. Visit the [PayPal Developer](https://developer.paypal.com/home) website and sign in to your account.
32+
2. Click on the `Sandbox > Accounts` option in the top menu.
33+
3. In the `Business` section, click on the `Create` button to create a
34+
new sandbox business account.
35+
4. Enter the required information to create your account and click `Create Account`.
36+
5. Once your account has been created, click on the `Profile` link next
37+
to the account.
38+
6. On the next page, you will see your `sandbox client ID` and
39+
`client secret`. Make sure to save these values, as you will need them to
40+
authenticate your app with PayPal in the sandbox environment.
41+
42+
### Initialize VaahPaypal
43+
```php
44+
//Initialize the VaahPaypal
45+
$vaahPaypal = new VaahPayPal(
46+
$client_id,
47+
$client_secret,
48+
$return_url,
49+
$cancel_url,
50+
$mode
51+
);
52+
```
53+
| Name | Description | Required | Default |
54+
|--|--|--|--|
55+
| client_id | PayPal Live/Sandbox client id| Yes
56+
| client_secret| PayPal Live/Sandbox client_secret| Yes
57+
| return_ url| redirect the user to after they have completed a payment.| No | /api/vaah/paypal/execute
58+
| cancel_url | redirect the user to after they have canceled a payment. | No| /api/vaah/paypal/cancel|
59+
| mode | environments for managing payments | No | sandbox
60+
61+
### Methods
62+
- Paypal Create Order
63+
64+
|Name| Required | Type |
65+
|--|--|--|
66+
| name | yes | String |
67+
| quantity| yes | String
68+
| amount| yes | String
69+
| description| yes | String
70+
| currency | yes | String |
71+
|shipping | No | Integer
72+
|tax| No | Integer
73+
```php
74+
$vaahPaypal->pay([
75+
'name' => 'Name',
76+
'amount' => 100,
77+
'currency' => 'USD',
78+
'description' => 'Description',
79+
'quantity' => 1,
80+
]);
81+
```
82+
83+
**Success response**
84+
```php
85+
[
86+
'status' => 'success';
87+
'approval_url' = 'approval url';
88+
'payment_id' = 'xxxxx';
89+
'token' = 'EC-xxxxxxxx';
90+
];
91+
```
92+
**Error Response**
93+
```php
94+
[
95+
'status' => 'failed';
96+
'errors' = 'errors';
97+
];
98+
```
99+
- Execute Order
100+
101+
|Name| Required
102+
|--|--|
103+
| payment_id | yes |
104+
| payer_id | yes |
105+
```php
106+
$payment_id = 'xxxx';
107+
$payer_id = 'xxxx';
108+
$vaahPaypal->executePayment($payment_id, $payer_id);
109+
```
110+
111+
**Success response**
112+
```php
113+
[
114+
'status' => 'success';
115+
'data' => 'data'; //array
116+
];
117+
```
118+
**Error response**
119+
```php
120+
[
121+
'status' => 'failed';
122+
'errors' = 'errors';
123+
];
124+
```
125+
Reference url: https://developer.paypal.com/api/rest/

Libraries/VaahPayPal.php

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
<?php
2+
namespace WebReinvent\VaahExtend\Libraries;
3+
4+
use PayPal\Api\OpenIdUserinfo;
5+
6+
7+
use Illuminate\Http\Request;
8+
use PayPal\Api\Agreement;
9+
use PayPal\Api\Amount;
10+
use PayPal\Api\Item;
11+
use PayPal\Api\ItemList;
12+
use PayPal\Api\MerchantPreferences;
13+
use PayPal\Api\Patch;
14+
use PayPal\Api\PatchRequest;
15+
use PayPal\Api\Payer;
16+
use PayPal\Api\Payment;
17+
use PayPal\Api\PaymentDefinition;
18+
use PayPal\Api\PaymentExecution;
19+
use PayPal\Api\Plan;
20+
use PayPal\Api\RedirectUrls;
21+
use PayPal\Api\ShippingAddress;
22+
use PayPal\Api\Transaction;
23+
use PayPal\Auth\OAuthTokenCredential;
24+
use PayPal\Common\PayPalModel;
25+
use PayPal\Rest\ApiContext;
26+
27+
class VaahPayPal{
28+
29+
private $mode;
30+
private $client_id;
31+
private $client_secret;
32+
private $return_url;
33+
private $cancel_url;
34+
35+
public function __construct(
36+
$client_id,
37+
$client_secret,
38+
$return_url = '/api/vaah/paypal/execute',
39+
$cancel_url = '/api/vaah/paypal/cancel',
40+
$mode = 'sandbox'
41+
)
42+
{
43+
$this->mode = $mode;
44+
$this->client_id = $client_id;
45+
$this->client_secret = $client_secret;
46+
$this->return_url = $return_url;
47+
$this->cancel_url = $cancel_url;
48+
}
49+
50+
//----------------------------------------------------------
51+
public function pay($inputs){
52+
$rules = [
53+
'name' => 'required',
54+
'amount' => 'required',
55+
'currency' => 'required',
56+
'description' => 'required',
57+
'quantity' => 'required',
58+
];
59+
$validator = \Validator::make($inputs, $rules);
60+
if ($validator->fails()) {
61+
$errors = $validator->errors();
62+
$response['status'] = 'failed';
63+
$response['errors'] = $errors;
64+
return $response;
65+
}
66+
$payer = new \PayPal\Api\Payer();
67+
$payer->setPaymentMethod("paypal");
68+
//set item info
69+
$item = new \PayPal\Api\Item();
70+
$item->setName($inputs['name'])
71+
->setDescription($inputs['description'])
72+
->setCurrency($inputs['currency'])
73+
->setPrice($inputs['amount'])
74+
->setQuantity($inputs['quantity']);
75+
//set item list
76+
$itemList = new \PayPal\Api\ItemList();
77+
$itemList->setItems(array($item));
78+
//details
79+
$details = new \PayPal\Api\Details();
80+
$shipping = $inputs['shipping'] ?? 0;
81+
$tax = $inputs['tax'] ?? 0;
82+
83+
$subtotal = ($inputs['amount'] * $inputs['quantity']) + $shipping + $tax;
84+
$details->setShipping($shipping)
85+
->setTax($tax)
86+
->setSubtotal($subtotal);
87+
88+
//set amount
89+
$amount = new \PayPal\Api\Amount();
90+
$total = $inputs['amount'] * $item->getQuantity();
91+
$amount->setCurrency($inputs['currency'])
92+
->setTotal($total)
93+
->setDetails($details);
94+
95+
//set transaction
96+
$transaction = new \PayPal\Api\Transaction();
97+
$transaction->setAmount($amount)->setItemList($itemList)
98+
->setDescription($inputs['description'])
99+
->setInvoiceNumber(uniqid());
100+
//set redirect urls
101+
$redirectUrls = new \PayPal\Api\RedirectUrls();
102+
$redirectUrls->setReturnUrl($this->return_url)
103+
->setCancelUrl($this->cancel_url);
104+
//set payment
105+
$payment = new \PayPal\Api\Payment();
106+
$payment->setIntent("sale")
107+
->setPayer($payer)
108+
->setRedirectUrls($redirectUrls)
109+
->setTransactions(array($transaction));
110+
111+
//create payment with valid api context
112+
try {
113+
$resp = $payment->create($this->getApiContext());
114+
$approvalUrl = $resp->getApprovalLink(); //approval url
115+
$response = [];
116+
$response['status'] = 'success';
117+
$response['data']['approval_url'] = $approvalUrl;
118+
$response['data']['payment_id'] = $resp->getId();
119+
$response['data']['token'] = $resp->getToken();
120+
return $response;
121+
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
122+
$response = [];
123+
$response['status'] = 'failed';
124+
$response['errors'] = $ex->getData();
125+
return $response;
126+
} catch (\Exception $ex) {
127+
$response = [];
128+
$response['status'] = 'failed';
129+
$response['errors'] = $ex->getMessage();
130+
return $response;
131+
}
132+
}
133+
//----------------------------------------------------------
134+
public function getUserInfo(){
135+
//getting user details
136+
try {
137+
$token = $this->getApiContext()->getCredential()->getAccessToken($this->getApiContext()); //get access token
138+
$user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $this->getApiContext());
139+
$response = [];
140+
$response['status'] = 'success';
141+
$response['data'] = $user->toArray();
142+
return $response;
143+
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
144+
$response = [];
145+
$response['status'] = 'failed';
146+
$response['errors'] = $ex->getData();
147+
return $response;
148+
} catch (\Exception $ex) {
149+
$response = [];
150+
$response['status'] = 'failed';
151+
$response['errors'] = $ex->getMessage();
152+
return $response;
153+
}
154+
}
155+
//----------------------------------------------------------
156+
public function executePayment($paymentId, $payerId)
157+
{
158+
try {
159+
$payment = \PayPal\Api\Payment::get($paymentId, $this->getApiContext());
160+
$execution = new \PayPal\Api\PaymentExecution();
161+
$execution->setPayerId($payerId);
162+
$result = $payment->execute($execution, $this->getApiContext());
163+
$response = [];
164+
$response['status'] = 'success';
165+
$response['data'] = $result->toArray();
166+
return $response;
167+
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
168+
$response = [];
169+
$response['status'] = 'failed';
170+
$response['errors'] = $ex->getData();
171+
return $response;
172+
} catch (\Exception $ex) {
173+
$response = [];
174+
$response['status'] = 'failed';
175+
$response['errors'] = $ex->getMessage();
176+
return $response;
177+
}
178+
}
179+
//----------------------------------------------------------
180+
private function getApiContext() {
181+
// #### SDK configuration
182+
// Register the sdk_config.ini file in current directory
183+
// as the configuration source.
184+
/*
185+
if(!defined("PP_CONFIG_PATH")) {
186+
define("PP_CONFIG_PATH", __DIR__);
187+
}
188+
*/
189+
// ### Api context
190+
// Use an ApiContext object to authenticate
191+
// API calls. The clientId and clientSecret for the
192+
// OAuthTokenCredential class can be retrieved from
193+
// developer.paypal.com
194+
$apiContext = new ApiContext(
195+
new OAuthTokenCredential(
196+
$this->client_id,
197+
$this->client_secret
198+
),
199+
200+
);
201+
// Comment this line out and uncomment the PP_CONFIG_PATH
202+
// 'define' block if you want to use static file
203+
// based configuration
204+
$apiContext->setConfig(
205+
array(
206+
'mode' => $this->mode,
207+
'log.LogEnabled' => true,
208+
'log.FileName' => '../PayPal.log',
209+
'log.LogLevel' => 'DEBUG',
210+
// PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
211+
'cache.enabled' => true,
212+
//'cache.FileName' => '/PaypalCache' // for determining paypal cache directory
213+
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
214+
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
215+
//'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
216+
)
217+
);
218+
// Partner Attribution Id
219+
// Use this header if you are a PayPal partner. Specify a unique BN Code to receive revenue attribution.
220+
// To learn more or to request a BN Code, contact your Partner Manager or visit the PayPal Partner Portal
221+
// $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', '123123123');
222+
return $apiContext;
223+
}
224+
//----------------------------------------------------
225+
}

0 commit comments

Comments
 (0)