Skip to content

Instantly share code, notes, and snippets.

@amonger
Last active August 29, 2015 14:23
Show Gist options
  • Save amonger/5149953992329a38b1af to your computer and use it in GitHub Desktop.
Save amonger/5149953992329a38b1af to your computer and use it in GitHub Desktop.
Omnipay Paypal Express Command
<?php
namespace App\Commands;
use App\Commands\Command;
use Dotenv;
use Illuminate\Contracts\Bus\SelfHandling;
use Omnipay\PayPal\ExpressGateway;
class MakePayment extends Command implements SelfHandling
{
protected $cancelUrl;
protected $returnUrl;
protected $description;
protected $currency;
protected $items;
/**
* @param array $items
* @param string $currency
* @param string $cancelUrl
* @param string $returnUrl
*/
public function __construct(array $items, $currency, $cancelUrl, $returnUrl)
{
$this->items = $items;
$this->currency = $currency;
$this->cancelUrl = $cancelUrl;
$this->returnUrl = $returnUrl;
}
/**
* @param Dotenv $environmentVariables
* @param ExpressGateway $gateway
*/
public function handle(Dotenv $environmentVariables, ExpressGateway $gateway)
{
/** @var \Omnipay\PayPal\ExpressGateway $gateway */
$gateway->setUsername($environmentVariables->findEnvironmentVariable('PAYPAL_USERNAME'));
$gateway->setPassword($environmentVariables->findEnvironmentVariable('PAYPAL_PASSWORD'));
$gateway->setSignature($environmentVariables->findEnvironmentVariable('PAYPAL_SIGNATURE'));
if($environmentVariables->findEnvironmentVariable('PAYPAL_TEST_MODE') === "true") {
$gateway->setTestMode(true);
}
$response = $gateway->purchase($this->details())->send();
if ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
echo $response->getTransactionReference();
}
}
/**
* @param array $items
*
* @return float
*/
private function getSumTotal(array $items)
{
return array_reduce($items, function ($current, $item) {
return $current + ($item['price'] * $item['quantity']);
}, 0);
}
/**
* @return array
*/
private function details()
{
return [
'amount' => $this->getSumTotal($this->items),
'cancelUrl' => $this->cancelUrl,
'returnUrl' => $this->returnUrl,
'currency' => $this->currency,
'items' => $this->items
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment