Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webhooks #73

Open
wants to merge 17 commits into
base: master-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 8 additions & 4 deletions Controller/BaseController.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ public function __construct(
\Magento\Customer\Model\Session $customerSession,
\Magento\Checkout\Model\Session $checkoutSession,
\Razorpay\Magento\Model\Config $config
) {
)
{
parent::__construct($context);
$this->customerSession = $customerSession;
$this->checkoutSession = $checkoutSession;
Expand All @@ -68,7 +69,8 @@ public function __construct(
protected function initCheckout()
{
$quote = $this->getQuote();
if (!$quote->hasItems() || $quote->getHasError()) {
if (!$quote->hasItems() || $quote->getHasError())
{
$this->getResponse()->setStatusHeader(403, '1.1', 'Forbidden');
throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t initialize checkout.'));
}
Expand All @@ -81,7 +83,8 @@ protected function initCheckout()
*/
protected function getQuote()
{
if (!$this->quote) {
if (!$this->quote)
{
$this->quote = $this->checkoutSession->getQuote();
}
return $this->quote;
Expand All @@ -92,7 +95,8 @@ protected function getQuote()
*/
protected function getCheckout()
{
if (!$this->checkout) {
if (!$this->checkout)
{
$this->checkout = $this->checkoutFactory->create(
[
'params' => [
Expand Down
21 changes: 11 additions & 10 deletions Controller/Payment/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public function __construct(
\Razorpay\Magento\Model\CheckoutFactory $checkoutFactory,
\Razorpay\Magento\Model\Config $config,
\Magento\Catalog\Model\Session $catalogSession
) {
)
{
parent::__construct(
$context,
$customerSession,
Expand All @@ -42,21 +43,21 @@ public function execute()
{
$amount = (int) (round($this->getQuote()->getBaseGrandTotal(), 2) * 100);

$receipt_id = $this->getQuote()->getId();
$receiptId = $this->getQuote()->getId();

$code = 400;

try
{
$order = $this->rzp->order->create([
'amount' => $amount,
'receipt' => $receipt_id,
'currency' => $this->_currency,
'payment_capture' => 1 // auto-capture
'amount' => $amount,
'receipt' => $receiptId,
'currency' => $this->_currency,
'payment_capture' => 1
]);

$responseContent = [
'message' => 'Unable to create your order. Please contact support.',
'message' => 'Unable to create your order. Please contact support.',
'parameters' => []
];

Expand All @@ -65,7 +66,7 @@ public function execute()
$responseContent = [
'success' => true,
'rzp_order' => $order->id,
'order_id' => $receipt_id,
'order_id' => $receiptId,
'amount' => $order->amount,
'quote_currency' => $this->getQuote()->getQuoteCurrencyCode(),
'quote_amount' => round($this->getQuote()->getGrandTotal(), 2)
Expand All @@ -79,14 +80,14 @@ public function execute()
catch(\Razorpay\Api\Errors\Error $e)
{
$responseContent = [
'message' => $e->getMessage(),
'message' => $e->getMessage(),
'parameters' => []
];
}
catch(\Exception $e)
{
$responseContent = [
'message' => $e->getMessage(),
'message' => $e->getMessage(),
'parameters' => []
];
}
Expand Down
235 changes: 235 additions & 0 deletions Controller/Payment/Webhook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
<?php

namespace Razorpay\Magento\Controller\Payment;

use Razorpay\Api\Api;
use Razorpay\Api\Errors;
use Razorpay\Magento\Model\Config;
use Razorpay\Magento\Model\PaymentMethod;

class Webhook extends \Razorpay\Magento\Controller\BaseController
{
/**
* @var \Magento\Checkout\Model\Session
*/
protected $checkoutSession;

/**
* @var \Magento\Quote\Model\QuoteRepository
*/
protected $quoteRepository;

/**
* @var \Magento\Sales\Api\Data\OrderInterface
*/
protected $order;

protected $api;

protected $logger;

protected $quoteManagement;

protected $objectManagement;

protected $storeManager;

protected $customerRepository;

const STATUS_APPROVED = 'APPROVED';

/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Razorpay\Model\CheckoutFactory $checkoutFactory
* @param \Razorpay\Magento\Model\Config $config
* @param \Magento\Catalog\Model\Session $catalogSession
* @param \Magento\Quote\Model\QuoteRepository $quoteRepository,
* @param \Magento\Sales\Api\Data\OrderInterface $order
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Checkout\Model\Session $checkoutSession,
\Razorpay\Magento\Model\CheckoutFactory $checkoutFactory,
\Razorpay\Magento\Model\Config $config,
\Magento\Catalog\Model\Session $catalogSession,
\Magento\Quote\Model\QuoteRepository $quoteRepository,
\Magento\Sales\Api\Data\OrderInterface $order,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\Magento\Store\Model\StoreManagerInterface $storeManagement,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Psr\Log\LoggerInterface $logger
)
{
parent::__construct(
$context,
$customerSession,
$checkoutSession,
$config
);

$keyId = $this->config->getConfigData(Config::KEY_PUBLIC_KEY);
$keySecret = $this->config->getConfigData(Config::KEY_PRIVATE_KEY);

$this->api = new Api($keyId, $keySecret);
$this->order = $order;
$this->logger = $logger;

$this->objectManagement = \Magento\Framework\App\ObjectManager::getInstance();
$this->quoteManagement = $quoteManagement;
$this->checkoutFactory = $checkoutFactory;
$this->catalogSession = $catalogSession;
$this->quoteRepository = $quoteRepository;
$this->storeManagement = $storeManagement;
$this->customerRepository = $customerRepository;
}

/**
* Processes the incoming webhook
*/
public function execute()
{
$post = $this->getPostData();

if (json_last_error() !== 0)
{
return;
}

if (($this->config->isWebhookEnabled() === true) &&
(empty($post['event']) === false))
{
if (isset($_SERVER['HTTP_X_RAZORPAY_SIGNATURE']) === true)
{
$webhookSecret = $this->config->getWebhookSecret();

//
// To accept webhooks, the merchant must configure
// it on the magento backend by setting the secret
//
if (empty($webhookSecret) === true)
{
return;
}

try
{
$this->api->utility->verifyWebhookSignature(json_encode($post),
$_SERVER['HTTP_X_RAZORPAY_SIGNATURE'],
$webhookSecret);
}
catch (Errors\SignatureVerificationError $e)
{
$this->logger->warning(
$e->getMessage(),
[
'data' => $post,
'event' => 'razorpay.wc.signature.verify_failed'
]);

return;
}

switch ($post['event'])
{
case 'payment.authorized':
return $this->paymentAuthorized($post);

default:
return;
}
}
}
}

/**
* Payment Authorized webhook
*
* @param array $post
*/
protected function paymentAuthorized(array $post)
{
$quoteId = $post['payload']['payment']['entity']['notes']['merchant_order_id'];
$amount = $post['payload']['payment']['entity']['amount'] / 100;
$paymentId = $post['payload']['payment']['entity']['id'];

$quote = $this->getQuoteObject($post, $quoteId);

$order = $this->quoteManagement->submit($quote);

$payment = $order->getPayment();

$this->logger->warning('Debug Log --------------------- 1');

if (empty($payment->getLastTransId()) === false)
{
return;
}

$this->logger->warning('Debug Log --------------------- 2');

$payment->setAmountPaid($amount)
->setLastTransId($paymentId)
->setTransactionId($paymentId)
->setIsTransactionClosed(true)
->setShouldCloseParentTransaction(true);

$payment->save();

$this->logger->warning('Debug Log --------------------- 3');
}

protected function getQuoteObject($post, $quoteId)
{
$email = $post['payload']['payment']['entity']['email'];

$quote = $this->quoteRepository->get($quoteId);

$firstName = $quote->getBillingAddress()['customer_firstname'] ?? 'null';
$lastName = $quote->getBillingAddress()['customer_lastname'] ?? 'null';

$quote->getPayment()->setMethod(PaymentMethod::METHOD_CODE);

$store = $this->storeManagement->getStore();

$websiteId = $store->getWebsiteId();

$customer = $this->objectManagement->create('Magento\Customer\Model\Customer');
$customer->setWebsiteId($websiteId);

$customer = $customer->loadByEmail($email);

if (empty($customer->getEntityId()) === true)
{
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($firstName)
->setLastname($lastName)
->setEmail($email);

$customer->save();
}

$customer = $this->customerRepository->getById($customer->getEntityId());

$quote->assignCustomer($customer);

$quote->setStore($store);

$quote->save();

return $quote;
}

/**
* @return Webhook post data as an array
*/
protected function getPostData() : array
{
$request = file_get_contents('php://input');

return json_decode($request, true);
}
}