HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/debierbaron.komma.pro/app/Komma/Payments/PaymentService.php
<?php

namespace Komma\Payments;

/**
 * Short description for the file.
 *
 * @author      Tim Van Samang <timvansamang@komma.pro>
 * @copyright   (c) 2012-2015, Komma Mediadesign
 */

use Illuminate\Support\Facades\Redirect;
use Komma\Kms\Orders\Models\OrderTransactions;
use Komma\Kms\Subscriptions\Models\SubscriptionTransactionsRequest;
use Komma\Shop\ShopService;
use Komma\Subscriptions\Models\SubscriptionTransactions;
use Mollie_API_Client as Mollie;

class PaymentService
{

    /**
     * @var Mollie
     */
    private $mollie;

    /**
     * @var ShopService
     */
    private $shopService;

    /**
     * Inject the ShopService
     * initiate Mollie
     *
     * PaymentService constructor.
     * @param ShopService $shopService
     */
    public function __construct(ShopService $shopService)
    {
        $this->shopService = $shopService;

        $this->initMollie();

        //Set the locale (for date translations)
        $this->setLocale();
    }

    /**
     * Initialize the mollie class
     * And set the api_key to it
     *
     */
    public function initMollie()
    {
        //Create new Mollie class
        $this->mollie = new Mollie;
        //Try to set the api_key
        try {
            $this->mollie->setApiKey(\Config::get('mollie.api_key'));
        } catch (\Mollie_API_Exception $e) {
            //When there is an exception, abort to 404 with the message
            //\App::abort(404, "API call failed: " . htmlspecialchars($e->getMessage()) . " on field " . htmlspecialchars($e->getField()));
        }

    }


    /*----------------------------------|
    |                                   |
    |   Normal order                    |
    |                                   |
    |----------------------------------*/

    /**
     * Start a new payment
     *
     * @param $order
     * @return mixed
     */
    public function startPayment($order)
    {

        //Try to create a new payment
        try {
            $payment = $this->mollie->payments->create(array(
                "amount" => $order->price_total / 100,
                "description" => "Betaling bierbaron ordernummer " . $order->order_number,
                "redirectUrl" => \Config::get('mollie.redirectUrl'),
                'webhookUrl' => \Config::get('mollie.webhookUrl'),
                'metadata' => array(
                    'order_id' => $order->id
                )
            ));

            //Create a new order transaction (db)
            $this->newOrderTransAction($order, $payment);

            //Redirect to Mollie
            return \Redirect::to($payment->getPaymentUrl());

        } catch (\Mollie_API_Exception $e) {
            //When there is an exception, abbort to 404 with the message
            \App::abort(404, "API call failed: " . htmlspecialchars($e->getMessage()) . " on field " . htmlspecialchars($e->getField()));

        }
    }

    /**
     * Create a new order_transaction line
     *
     * @param $order
     * @param $payment
     */
    public function newOrderTransAction($order, $payment)
    {
        $orderTransaction = new OrderTransactions();
        $orderTransaction->order_id = $order->id;
        //Payment id from Mollie
        $orderTransaction->custom_identifier = $payment->id;
        //Set the status to open by default
        $orderTransaction->status = 'open';
        $orderTransaction->save();
    }

    /**
     * Handle the payment
     * Called by webhook
     *
     * @param $paymentId
     * @return mixed
     */
    public function handlePayment($paymentId)
    {
        //Check if we can get the payment from mollie
        try {
            $payment = $this->mollie->payments->get($paymentId);
        } catch (\Mollie_API_Exception $e) {
            \App::abort(404, "API call failed: " . htmlspecialchars($e->getMessage()));
        }

        //Get the order based on the payment info
        if (!$order = $this->shopService->getOrderWithPayment($payment)) \App::abort(404, 'order not found');

        $transaction = $order->transactions->first();
        //Set the status of the payment
        $this->SetStatusToTransaction($transaction, $payment);
        if ($payment->isPaid()) {
            //order is paid
            $this->shopService->updateOrder($order, 'paid');
        } elseif (!$payment->isOpen()) {
            //The payment isn't paid and isn't open anymore. We can assume it was aborted. (Mollie docs)
            $this->shopService->updateOrder($order, 'canceled');
        }
        return true;
    }


    /*----------------------------------|
    |                                   |
    |   Subscription                    |
    |                                   |
    |----------------------------------*/

    /**
     * Start a new payment for a subscription
     *
     * @param $subscription
     * @param null $transactionRequest
     * @return mixed
     */
    public function startSubscriptionPayment($subscription, $transactionRequest = null)
    {

        //Get the monthly fee from the subscription
        $amount = $subscription->monthly_fee;

        //Create the default description with current month
        $description = 'De Bierbaron, nieuw pakket';
        //$description = 'De Bierbaron pakket van ' . strftime("%B", time());

        //When there is no $transactionRequest, it is a new subscription
        if ($transactionRequest == null) {
            //Set the amount to the first_fee amount
            $amount = \Config::get('bierbaron.subscription_first_fee');
            $description = 'De Bierbaron, eerste betaling abonnement';
        }

        //Try to create a new payment
        try {
            $payment = $this->mollie->payments->create(array(
                "amount" => $amount / 100,
                "description" => $description,
                "redirectUrl" => \Config::get('mollie.subscriptionRedirectUrl'),
                'webhookUrl' => \Config::get('mollie.subscriptionWebHookUrl'),
                'metadata' => array(
                    'subscription_id' => $subscription->id,
                    'subscription_payment' => 1
                )
            ));

            //Create a new order transaction (db)
            $transaction = $this->newSubscriptionTransAction($subscription, $payment);
            //If there is a transactionRequest, set the payment to it, so it cant be used anymore
            if ($transactionRequest != null) $this->savePaymentToTransactionRequest($transactionRequest, $transaction);

            //Redirect to Mollie
            return \Redirect::to($payment->getPaymentUrl());

        } catch (\Mollie_API_Exception $e) {
            //When there is an exception, abbort to 404 with the message
            \App::abort(404, "API call failed: " . htmlspecialchars($e->getMessage()) . " on field " . htmlspecialchars($e->getField()));

        }
    }

    /**
     * Create a new SubscriptionTransaction
     *
     * @param $subscription
     * @param $payment
     * @return SubscriptionTransactions
     */
    private function newSubscriptionTransAction($subscription, $payment)
    {

        $subscriptionTransactions = new SubscriptionTransactions();
        $subscriptionTransactions->subscription_id = $subscription->id;
        //Payment id from Mollie
        $subscriptionTransactions->custom_identifier = $payment->id;
        //Set the status to open by default
        $subscriptionTransactions->status = 'open';
        $subscriptionTransactions->save();

        return $subscriptionTransactions;
    }

    /**
     * Save the transaction to the transactionRequest.
     * This makes sure a request is only payed once.
     *
     * @param $transactionRequest
     * @param $transaction
     */
    private function savePaymentToTransactionRequest($transactionRequest, $transaction)
    {
        $transactionRequest->subscription_transaction_id = $transaction->id;
        $transactionRequest->save();
    }


    /**
     * Handle the payment
     * called by webhook
     *
     * @param $paymentId
     * @return mixed
     */
    public function handleSubscriptionPayment($paymentId)
    {
        //Check if we can get the payment from mollie
        try {
            $payment = $this->mollie->payments->get($paymentId);
        } catch (\Mollie_API_Exception $e) {
            \App::abort(404, "API call failed: " . htmlspecialchars($e->getMessage()));
        }
        //Get the order based on the payment info
        if (!$subscription = $this->shopService->getSubscriptionWithPayment($payment)) \App::abort(404, 'subscription not found');

        $transaction = $subscription->transactions->first();
        //Set the status of the payment
        $this->SetStatusToTransaction($transaction, $payment);

        if ($payment->isPaid()) {
            //order is paid
            $this->shopService->updateSubscription($subscription, 'paid');
        } elseif (!$payment->isOpen()) {
            //The payment isn't paid and isn't open anymore. We can assume it was aborted. (Mollie docs)
            $this->shopService->updateSubscription($subscription, 'canceled');
        }
        return true;
    }

    /**
     * @param $field | datbase field
     * @param $value | value
     * @param string $operator
     * @return False | SubscriptionTransactionsRequest
     */
    public function getOpenSubscriptionTransactionRequest($field, $value, $operator = '=')
    {
        //Get  SubscriptionTransactionsRequests with the given parameters
        if (!$subscriptionTransactionsRequests = SubscriptionTransactionsRequest::where($field, $operator, $value)
            ->with('subscription')
            ->whereNull('subscription_transaction_id')
            ->first()
        ) return FALSE;

        return $subscriptionTransactionsRequests;
    }



    /*----------------------------------|
    |                                   |
    |   Global methods                  |
    |                                   |
    |----------------------------------*/

    /**
     * Set the status of the transaction.
     * to the status from Mollie.
     *
     * @param $transaction
     * @param $payment
     */
    public function SetStatusToTransaction($transaction, $payment)
    {
        $transaction->status = $payment->status;
        $transaction->save();

    }

    /**
     * Set the locale based on the language of Laravel
     */
    private function setLocale()
    {
        if (\App::getLocale() == 'nl') setlocale(LC_TIME, "nl_nl");

    }

}