Warning: chmod(): Operation not permitted in /var/www/hopeinstoughton_www/wp-content/plugins/simple-universal-google-analytics/main.php on line 8 [0] in function chmod in /var/www/hopeinstoughton_www/wp-content/plugins/simple-universal-google-analytics/main.php on line 8 [1] in function include_once in /var/www/hopeinstoughton_www/wp-settings.php on line 560 [2] in function require_once in /var/www/hopeinstoughton_www/wp-config.php on line 85 [3] in function require_once in /var/www/hopeinstoughton_www/wp-load.php on line 50 [4] in function require_once in /var/www/hopeinstoughton_www/wp-blog-header.php on line 13 [5] in function require in /var/www/hopeinstoughton_www/index.php on line 17
| Server IP : 94.177.8.99 / Your IP : 216.73.217.165 Web Server : Apache/2.4.58 (Ubuntu) System : Linux aries 6.8.0-134-generic #134-Ubuntu SMP PREEMPT_DYNAMIC Fri Jun 26 18:43:11 UTC 2026 x86_64 User : www-data ( 33) PHP Version : 8.1.34 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/theyoungdesigners_com/modules/storePaypal/model/ |
Upload File : |
<?php
// NEED TO WORK OUT WHAT TO DO WITH COMBINED DIGITAL/PHYSICAL GOODS ORDER
// PayPalCheckoutSdk
spl_autoload_register(function ($class_name) {
$elements = explode('\\', $class_name);
$base = array_shift($elements);
if ($base == 'PayPalCheckoutSdk') {
$filename = __DIR__ . '/' . join('/', $elements) . '.php';
require_once $filename;
} elseif ($base == 'PayPalHttp') {
$filename = __DIR__ . '/PayPalHttp/' . join('/', $elements) . '.php';
require_once $filename;
}
});
use \PayPalCheckoutSdk\Core\PayPalHttpClient;
use \PayPalCheckoutSdk\Core\SandboxEnvironment;
use \PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use \PayPalCheckoutSdk\Orders\OrdersGetRequest;
use \PayPalCheckoutSdk\Orders\OrdersPatchRequest;
use \PayPalCheckoutSdk\Orders\OrdersAuthorizeRequest;
use \PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use \PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
class Paypal_model extends Database_Model {
// https://developer.paypal.com/sdk/js/reference/
// sandbox credit card: 4012000077777777
private $currency = 'USD';
private $clientid;
private $secret;
private $paypalid;
private $DATA;
private $orderdata;
public function Currency() {
if (func_num_args()) {
$this->currency = func_get_arg(0);
return $this;
}
return $this->currency;
}
public function ClientId() {
if (func_num_args()) {
$this->clientid = func_get_arg(0);
return $this;
}
return $this->clientid;
}
public function Secret() {
if (func_num_args()) {
$this->secret = func_get_arg(0);
return $this;
}
return $this->secret;
}
public function PaypalId() { // Paypal's order number
if (func_num_args()) {
$this->paypalid = func_get_arg(0);
$this->_loadPaypal();
return $this;
}
return $this->paypalid;
}
public function OrderData($orderdata) {
$this->orderdata = $orderdata;
return $this;
}
public function OrderId() { // our internal order number
return (int) $this->DATA->sp_orderid;
}
public function createOrder() {
$items = [];
$order_data = $this->orderdata;
foreach($order_data['items'] as $item) {
$product = [
'name' => !empty($item['sp_model']) ? $item['sp_model'] : $item['sp_sku'], // name cannot be empty
'quantity' => '' . intval($item['quantity']),
'description' => $item['desc'],
'sku' => $item['sp_sku'],
'category' => $item['physical'] ? 'PHYSICAL_GOODS' : 'DIGITAL_GOODS',
'unit_amount' => [
'currency_code' => $this->currency,
'value' => (float) $item['price']['full'],
],
];
// add UPC, but only if it is valid
$upc = $item['physical'] ? $item['sp_upc'] : '';
$upc = Product_model::checkUPC($upc);
if ($upc) {
$product['upc'] = $upc;
}
$items[] = $product;
}
// https://developer.paypal.com/docs/api/orders/v2/#orders_create
$order = [
'custom_id' => $order_data['order_id'],
'description' => 'Order ' . $order_data['order_id'],
'amount' => [
'currency_code' => $this->currency,
'value' => (float) $order_data['subtotal'],
'breakdown' => [
'item_total' => [
'currency_code' => $this->currency,
'value' => (float) $order_data['subtotal'],
],
],
],
'items' => $items,
];
$client = new SandboxEnvironment($this->clientid, $this->secret);
$http = new PayPalHttpClient($client);
$payload = [
'intent' => 'AUTHORIZE',
'purchase_units' => [ $order ],
];
$request_id = Misc::uuid4();
$request = new OrdersCreateRequest();
$request->headers['prefer'] = 'return=representation';
$request->headers['PayPal-Request-Id'] = $request_id;
$request->body = $payload;
try {
$response = $http->execute($request);
} catch (\Exception $e) {
$message = $e->getMessage();
$body = json_decode($message, TRUE);
header('Content-type: text/plain');
echo "Exception [1]\n";
var_dump($payload);
var_dump($body);
exit;
}
$paypal_id = $response->result->id;
// Save the date
$this->TableName('store_paypal')
->InsertOrUpdate([
'order_id' => $paypal_id,
],[
'sp_orderid' => $order_data['order_id'],
'sp_timestamp' => time(),
'request_id' => $request_id, // only valid for 6 hours
]);
$data = [
'id' => $paypal_id,
];
header('Content-type: application/json');
die(json_encode($data, JSON_UNESCAPED_SLASHES));
// onShippingAddressChange and onShippingOptionsChange
}
private function _loadPaypal() {
$this->DATA = $this->Query('select * from `store_paypal`')
->Where('order_id=%s', $this->paypalid)
->First();
}
protected function _getPaypalOrder($http, $paypal_id) {
if (empty($paypal_id)) {
header('Content-type: text/plain');
echo "Exception [2]\n";
die('Paypal Identifier is missing');
}
$request = new OrdersGetRequest($paypal_id);
try {
$response = $http->execute($request);
} catch (\PayPalHttp\HttpException $e) {
$status = $e->statusCode;
$message = $e->getMessage();
header('Content-type: text/plain');
die("Exception [2]: Status code: $status - $paypal_id\n");
} catch (\Exception $e) {
$message = $e->getMessage();
$body = json_decode($message, TRUE);
header('Content-type: text/plain');
echo "Exception [2]\n";
var_dump($body);
exit;
}
return $response->result;
}
private function objectToArray($o) {
$a = [];
foreach ($o as $k => $v)
$a[$k] = (is_array($v) || is_object($v)) ? $this->objectToArray($v): $v;
return $a;
}
public function fetchPaypalOrder() {
$client = new SandboxEnvironment($this->clientid, $this->secret);
$http = new PayPalHttpClient($client);
$orderDetails = $this->_getPaypalOrder($http, $this->PaypalId());
return $orderDetails;
}
// https://developer.paypal.com/docs/checkout/standard/customize/shipping-options/
public function UpdateShipping($amount) {
$client = new SandboxEnvironment($this->clientid, $this->secret);
$http = new PayPalHttpClient($client);
$orderDetails = $this->_getPaypalOrder($http, $this->PaypalId());
// get order total
$total = 0;
foreach($orderDetails->purchase_units[0]->items as $item) {
$total += $item->unit_amount->value * $item->quantity;
}
$total = sprintf('%0.2f', $total);
$amount = sprintf('%0.2f', $amount);
// add shipping cost
$value = $this->objectToArray($orderDetails->purchase_units[0]->amount);
$value['breakdown']['shipping'] = [
'currency_code' => $this->currency,
'value' => $amount,
];
$value['value'] = sprintf('%0.2f', $total + $amount);
// update paypal record
// this will also update pricing on the paypal popup
$request = new OrdersPatchRequest($this->PaypalId());
$request->body = [
[
'op' => 'replace',
'path' => "/purchase_units/@reference_id=='default'/amount",
'value' => $value,
],
];
try {
$response = $http->execute($request);
} catch (\Exception $e) {
$message = $e->getMessage();
$body = json_decode($message, TRUE);
header('Content-type: text/plain');
echo "Exception [3]\n";
var_dump($body);
exit;
}
return TRUE;
}
private function loadUser_paypal($payer, $isVerified) {
// if a non-verified email adddress is used, we change it slightly
$email_address = $payer->email_address;
if (!$isVerified) $email_address = '#' . $email_address;
$param = new \StdClass;
$param->name_first = $payer->name->given_name;
$param->name_last = $payer->name->surname;
$param->email = $email_address;
$hash = md5($payer->payer_id);
$row = $this->Query('select us_user_id,level,email,verified from `users_source` inner join `users` on us_user_id=user_id')
->Where('us_source=%s', 'paypal')
->Where('us_hash=%s', $hash)
->First();
if (!$row->empty()) {
$this->TableName('users_source') // update email and status
->InsertOrUpdate([
'us_source' => 'paypal',
'us_hash' => $hash,
], [
'us_identifier' => $payer->payer_id,
'email' => $email_address,
'verified' => $isVerified ? 1 : 0,
'email_hash' => md5($email_address),
'name_first' => $payer->name->given_name,
'name_last' => $payer->name->surname,
]);
$param->user_id = (int) $row->us_user_id;
$param->level = (int) $row->level;
return $param;
}
$row = $this->Query('select * from `users`')
->Where('primary_email=%s', $email_address)
->First();
if ($row->empty()) {
// create a user
$row = $this->TableName('users')
->Autoinc('user_id')
->InsertOrUpdate([
'user_id' => NULL
],[
'parent_id' => 0,
'level' => 1,
'name_first' => $payer->name->given_name,
'name_last' => $payer->name->surname,
'primary_email' => $email_address,
'created' => time(),
]);
$user_id = $row->user_id;
$param->level = 1;
} else {
$user_id = (int) $row->user_id;
$param->level = (int) $row->level;
}
// add source record
$this->TableName('users_source') // update email and status
->InsertOrUpdate([
'us_source' => 'paypal',
'us_hash' => $hash,
], [
'us_identifier' => $payer->payer_id,
'email' => $email_address,
'verified' => $isVerified ? 1 : 0,
'email_hash' => md5($email_address),
'us_user_id' => $user_id,
'name_first' => $payer->name->given_name,
'name_last' => $payer->name->surname,
]);
$param->user_id = $user_id;
return $param;
}
public function HoldOrder() {
$client = new SandboxEnvironment($this->clientid, $this->secret);
$http = new PayPalHttpClient($client);
$orderDetails = $this->_getPaypalOrder($http, $this->PaypalId());
if ($orderDetails->status != 'APPROVED') return;
// production or sandbox?
$data = [];
$isSandbox = FALSE;
foreach($orderDetails->links as $link) {
if (strpos($link->href, 'sandbox') !== FALSE) {
$isSandbox = TRUE;
}
if ($link->rel == 'authorize') {
$data['sp_link_authorize'] = json_encode($link, JSON_UNESCAPED_SLASHES);
} elseif ($link->rel == 'update') {
$data['sp_link_update'] = json_encode($link, JSON_UNESCAPED_SLASHES);
}
}
// update store_paypal record
$account_status = $orderDetails->payment_source->paypal->account_status;
$data['sp_accountstatus'] = $account_status;
$data['sp_state'] = 'authorized';
$data['sp_transaction'] = $orderDetails->id;
$this->TableName('store_paypal')
->InsertOrUpdate([ 'order_id' => $this->paypalid ], $data);
$param = $this->loadUser_paypal($orderDetails->payer, $account_status == 'VERIFIED' );
hook_execute('login', 0, $param); // login in
session_write_close();
// add delivery address, if missing, update order details (user_id, name, email)
$shipping = $orderDetails->purchase_units[0]->shipping;
$param->address = [
'name' => $shipping->name->full_name,
'del_a' => $shipping->address->address_line_1,
'town' => $shipping->address->admin_area_2,
'state' => $shipping->address->admin_area_1,
'zip' => $shipping->address->postal_code,
'country' => $shipping->address->country_code,
];
// update order delivery and postcode (assume freight charge is still correct)
$param->order_id = $this->OrderId();
$param->status = 'paypal';
$param->test = $isSandbox ? 1 : 0;
hook_execute('order.update', $param);
}
public function fromOrderId($order_id) {
$row = $this->Query('select order_id from `store_paypal`')
// ->Where('sp_state=%s', 'authorized')
->Where('sp_orderid=%d', $order_id)
->First();
return $row->order_id;
}
// not needed - order is already authorized
public function Authorize($http) {
$request = new OrdersAuthorizeRequest($this->paypalid);
try {
$response = $http->execute($request);
} catch (\Exception $e) {
$message = $e->getMessage();
$body = json_decode($message, TRUE);
header('Content-type: text/plain');
echo "Exception [8]\n";
var_dump($body);
exit;
}
var_dump($response->result);
error_log(json_encode($response->result, JSON_UNESCAPED_SLASHES));
}
public function Capture($http) {
// now authorize
$request = new OrdersCaptureRequest($this->paypalid);
try {
$response = $http->execute($request);
} catch (\Exception $e) {
$message = $e->getMessage();
$body = json_decode($message, TRUE);
header('Content-type: text/plain');
echo "Exception [9] :- /{$this->paypalid}/\n";
var_dump($body);
exit;
}
var_dump($response->result);
error_log(json_encode($response->result, JSON_UNESCAPED_SLASHES));
}
// https://developer.paypal.com/docs/multiparty/checkout/standard/integrate/
// https://developer.paypal.com/docs/multiparty/checkout/standard/customize/auth-capture/
// we are at a point where we are going to send out the order
public function finalizeOrder() {
$client = new SandboxEnvironment($this->clientid, $this->secret);
$http = new PayPalHttpClient($client);
$orderDetails = $this->_getPaypalOrder($http, $this->PaypalId());
// When you are ready to capture the funds you authorized, call /v2/payments/authorizations/{authorization_id}/capture. You can retrieve the
// authorization_id from the purchase_units/payments/authorizations/id field of the response from the previous step to authorize an order or
// from a show order details call.
// $this->Authorize($http); // the order is already authorized
$this->Capture($http);
// transaction must be approved first
die('Breakpoint');
header('Content-type: text/plain');
var_dump($orderDetails);
exit;
// change order status to 'paid'
$param = new StdClass;
$param->order_id = $this->OrderId();
$param->status = 'paid';
// hook_execute('order.update', $param);
}
// https://developer.paypal.com/docs/api/payments/v2/#authorizations_capture
//
public function ProcessPayment($params) {
$client = new SandboxEnvironment($this->clientid, $this->secret);
$http = new PayPalHttpClient($client);
$paypal_id = $this->fromOrderId($params->order_id);
$request = new AuthorizationsCaptureRequest($paypal_id); // authorization id
$request->body = [
"amount" => [
"value" => sprintf('%0.2f', $params->amount),
"currency_code" => "USD",
],
"invoice_id" => $params->order_id,
"final_capture" => !$params->partial,
// "note_to_payer" => "If the ordered color is not available, we will substitute with a different color free of charge.",
// "soft_descriptor" => "Bob's Custom Sweaters"
];
var_dump($request->body);
try {
$response = $http->execute($request);
} catch (\Exception $e) {
$message = $e->getMessage();
$body = json_decode($message, TRUE);
header('Content-type: text/plain');
echo "Exception [7]\n";
var_dump($body);
exit;
}
//
}
// add tracking to order
}