Files
ms1inscription-v5/php/inc_paypal.php
2026-05-13 09:43:32 -04:00

316 lines
9.1 KiB
PHP

<?php
// Include the composer autoloader
require_once __DIR__ . '/../vendor/autoload.php';
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
/**
* Helper method for getting an APIContext for all calls
* @return PayPal\Rest\ApiContext
*/
function getApiContext() {
global $vPaypal;
$apiContext = new ApiContext(
new OAuthTokenCredential(
$vPaypal['credentials']['client_id'],
$vPaypal['credentials']['secret']
)
);
// based configuration
$apiContext->setConfig(
array(
'mode' => $vPaypal['mode'],
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => $vPaypal['log_level'],
'cache.enabled' => true,
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
)
);
return $apiContext;
}
// Wrapper methods for all PayPal integration
use PayPal\Api\PaymentExecution;
use PayPal\Api\Amount;
use PayPal\Api\CreditCard;
use PayPal\Api\Details;
use PayPal\Api\FundingInstrument;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
/* $card = new CreditCard();
$card->setType("visa")
->setNumber("4148529247832259")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setDescription('Ground Coffee 40 oz')
->setCurrency('CAD')
->setQuantity(1)
->setTax(0.3)
->setPrice(7.50);
$item2 = new Item();
$item2->setName('Granola bars')
->setDescription('Granola Bars with Peanuts')
->setCurrency('CAD')
->setQuantity(5)
->setTax(0.2)
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.5);
$amount = new Amount();
$amount->setCurrency("CAD")
->setTotal(20)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($apiContext);
} catch (Exception $ex) {
print_r(array('Create Payment Using Credit Card. If 500 Exception, try creating a new Credit Card using <a href="https://ppmts.custhelp.com/app/answers/detail/a_id/750">Step 4, on this link</a>, and using it.', 'Payment', null, $request, $ex));
exit(1);
}
print_r(array('Create Payment Using Credit Card', 'Payment', $payment->getId(), $request, $payment)); */
/**
* Détermine le type de carte de crédit
* @param string $str Numéro de la carte
* @return string
*/
function getCreditCardType($str) {
$strRetour = 'error';
$matchingPatterns = array(
'visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/',
'mastercard' => '/^5[1-5][0-9]{14}$/'
);
foreach ($matchingPatterns as $key => $pattern) {
if (preg_match($pattern, $str)) {
$strRetour = $key;
}
}
return $strRetour;
}
/**
* Fait un paiement par carte de crédit<
* @param string $type Type de la carte
* @param string $number Numéro de la carte
* @param string $expire_month Mois d'expiration
* @param string $expire_year Année d'expiration
* @param string $cvv2 Code de vérification
* @param string $first_name Prénom du titulaire
* @param string $last_name Nom de famille du titulaire
* @param string $currency Devise d'argent utilisée
* @param float $total Montant total du panier
* @param array $details Détails de la commande (montant livraison, taxes, sous-total)
* @param string $description Description globale de ce qui est acheté
* @param array $items Liste des items achetés (nom, quantité et prix)
* @param string $invoice_number Numéro de transaction
* @return array
*/
function makePaymentUsingCC($type, $number, $expire_month, $expire_year, $cvv2, $first_name, $last_name, $currency = 'CAD', $total, $details, $description, $items, $invoice_number) {
$tabRetour = array();
if (trim($type) == '')
$type = getCreditCardType($number);
$card = new CreditCard();
$card->setType($type)
->setNumber($number)
->setExpireMonth($expire_month)
->setExpireYear($expire_year)
->setCvv2($cvv2)
->setFirstName($first_name)
->setLastName($last_name);
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$tabItems = array();
foreach ($items as $tab) {
$item = new Item();
$item->setName($tab['name'])
->setCurrency($currency)
->setQuantity($tab['quantity'])
->setPrice($tab['price']);
$tabItems[] = $item;
}
$itemList = new ItemList();
$itemList->setItems($tabItems);
$details1 = new Details();
$details1->setShipping($details['shipping'])
->setTax($details['tax'])
->setSubtotal($details['subtotal']);
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($total)
->setDetails($details1);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription($description)
->setInvoiceNumber($invoice_number);
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
try {
$payment->create(getApiContext());
} catch (PayPal\Exception\PayPalConnectionException $ex) {
/* echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex); */
$tabRetour['exception'] = array('code' => $ex->getCode(), 'Message' => $ex->getMessage(), 'data' => $ex->getData());
} catch (Exception $ex) {
/*echo '<pre>';
print_r(array($request, $ex));
echo '</pre>';
exit(1); */
die($ex);
}
$tabRetour['payment'] = $payment;
$tabRetour['id'] = $payment->getId();
$tabRetour['state'] = $payment->getState();
return $tabRetour;
}
/**
* Create a payment using the buyer's paypal
* account as the funding instrument. Your app
* will have to redirect the buyer to the paypal
* website, obtain their consent to the payment
* and subsequently execute the payment using
* the execute API call.
*
* @param string $total payment amount in DDD.DD format
* @param string $currency 3 letter ISO currency code such as 'USD'
* @param string $paymentDesc A description about the payment
* @param string $returnUrl The url to which the buyer must be redirected
* to on successful completion of payment
* @param string $cancelUrl The url to which the buyer must be redirected
* to if the payment is cancelled
* @return \PayPal\Api\Payment
*/
function makePaymentUsingPayPal($total, $currency, $paymentDesc, $returnUrl, $cancelUrl) {
$payer = new Payer();
$payer->setPaymentMethod("paypal");
// Specify the payment amount.
$amount = new Amount();
$amount->setCurrency($currency);
$amount->setTotal($total);
// ###Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription($paymentDesc);
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl($returnUrl);
$redirectUrls->setCancelUrl($cancelUrl);
$payment = new Payment();
$payment->setRedirectUrls($redirectUrls);
$payment->setIntent("sale");
$payment->setPayer($payer);
$payment->setTransactions(array($transaction));
$payment->create(getApiContext());
return $payment;
}
/**
* Completes the payment once buyer approval has been
* obtained. Used only when the payment method is 'paypal'
*
* @param string $paymentId id of a previously created
* payment that has its payment method set to 'paypal'
* and has been approved by the buyer.
*
* @param string $payerId PayerId as returned by PayPal post
* buyer approval.
*/
function executePayment($paymentId, $payerId) {
$payment = getPaymentDetails($paymentId);
$paymentExecution = new PaymentExecution();
$paymentExecution->setPayerId($payerId);
$payment = $payment->execute($paymentExecution, getApiContext());
return $payment;
}
/**
* Retrieves the payment information based on PaymentID from Paypal APIs
*
* @param $paymentId
*
* @return Payment
*/
function getPaymentDetails($paymentId) {
$payment = Payment::get($paymentId, getApiContext());
return $payment;
}