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/ZelfVerkopen/zelfverkopen.nl/app/KommaApp/Icepay/Paybymail/PaybymailService.php
<?php


namespace App\KommaApp\Icepay\Paybymail;

use App\KommaApp\Orders\Models\Order;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\Debug\Debug;

/**
 * Class PaybymailService
 *
 * @see http://icepay.com/docs/pay-by-mail/
 * @see https://paybymail.icepay.com/
 *
 * @package App\KommaApp\Icepay\Paybymail
 */
class PaybymailService
{
    /** @var int $icepay_environment The current environment to use. Must equal one of the ENVIRONMENT environment constants */
    private $icepay_environment;

    /** @var Client $httpClientPayments */
    private $httpClientPayments;

    /** @var bool */
    const generateFakeUrl = false;

    public function __construct()
    {
        $this->icepay_environment = 'production'; //production or test
        $this->setupHTTPClients();
    }

    private function setupHTTPClients()
    {
        \Log::debug(' ');
        \Log::debug('[-------------------------------- Paybymail ----------------------------------]');

        $url = 'https://' . config('icepay.paybymail.environment_settings.' . $this->icepay_environment . '.payment_url');

        \Log::debug('Init client with this url: ' . $url);

        $this->httpClientPayments = new Client([
            'base_uri' => $url,
            'timeout'  => 10.0,
            'verify'   => false,
        ]);
    }

    /**
     * @param int $gender 0 for undefined, 1 for male, 2 for female
     * @param string $salutation Mister, mr. Ms, Dr etc.
     * @param string $customerLastName
     * @param string $customerEmail
     * @param int $amountToPay In Euros
     * @param int $orderId Own order id reference. Must be unqiue
     * @param bool $icepayMustSendMail wether or not icepay themselves must send a mail to the customer requesting payment
     * @return bool|string false on failures. link string on success. Example link: http://spbl.eu/70x9696kNK
     */
    public function createPaymentURL(
        int $gender,
        string $salutation,
        string $customerLastName,
        string $customerEmail,
        float $amountToPay,
        string $orderId,
        bool $icepayMustSendMail = false
    ) {
        if (self::generateFakeUrl) {
            return 'http://spbl.eu/fake_' . $amountToPay . '_' . str_random(6);
        }
        \Log::debug('Create payment url call received.');

        /** @var Order $order */
        $order = Order::where('order_id', '=', $orderId)->first();
        if(!$order) {
            \Log::debug('Could not get the order with order id "'.$orderId.'" to generate a payment url for.');
            return false;
        }

        $response = null;
        try {
            $username = config('icepay.paybymail.api_username');
            $password = config('icepay.paybymail.api_password');
//            $credentials = base64_encode($username.':'.$password);
//            'Authorization' => ['Basic '.$credentials]

            switch ($gender) {
                default:
                case 0:
                    $genderType = '';
                    break;
                case 1:
                    $genderType = __('icepay.mister');
                    break;
                case 2:
                    $genderType = __('icepay.misses');
                    break;
            }

            $channel = ($icepayMustSendMail) ? 'mail' : 'nosend';

            $uri = 'create/' . config('icepay.paybymail.api_entity_key');

            $queryData = [
                "MappingTemplate"   => "Standaard",
                "MailTemplate"      => "Standaard template",
                "GenderText"        => $salutation,
                "AmountText"        => "10 euro",
                "EntityDisplayName" => "Zelfverkopen",
                "Description"       => "Description",
                "Amount"            => "Amount",
                "LanguageCode"      => "nl-NL",
                "CurrencyCode"      => "euro",
                "AmountPayable"     => $amountToPay,
                "Product Name"      => "zelfverkopen.nl",
                "Estate"            => $this->zelfverkopenOrderIdToPayByMailOrderId($order),
                "Gender"            => $genderType,
                "Lastname"          => $customerLastName,
                "Name"              => "Company",
                "Phone"             => "Phone",
                "Email"             => $customerEmail,
                "Channel"           => $channel
            ];
            \Log::debug('Create payment url with query data: ['.http_build_query($queryData,'','|').']');
            \Log::debug('Basic authenticating with: '.$username.' '.$password. 'From server with address: '.(array_key_exists('LOCAL_ADDR', $_SERVER) ? $_SERVER['LOCAL_ADDR'] : '').' OR '.gethostbyname('zelfverkopen.komma.pro'));


            $response = $this->httpClientPayments->request('GET', $uri, [ //Auth gives basic authentication
                'auth'  => [$username, $password],
                'query' => $queryData
            ]);
        } catch (GuzzleException $exception) {
            $code = $exception->getCode();

            if ($code == 401) {
                \Log::debug('Paybymail call failed because it was unauthorized. ' . $exception->getMessage());

//                echo 'Request was unauthorized. Check credentials: '.$exception->getMessage();
                return false;
            }else {
                \Log::debug('Something went wrong while creating the payment url via paybymail: ');
                \Log::debug($exception->getMessage());

//                echo 'Something went wrong while creating the payment url: '.$exception->getMessage();
                return false;
            }
        }

        if ( ! $response) {
            \Log::debug('Something went wrong while creating the payment url via paybymail. Did not receive a response.');
            \Log::debug($response);
            return false;
        }

        $link = $response->getBody()->getContents(); //Example: "http://spbl.eu/70x9696kNK"
        $link = str_replace('"', '', $link);

        \Log::debug('Created payment url: '.$link);


        \Log::debug('[-------------------------------- /Paybymail ----------------------------------]');

        return $link;
    }

    public function zelfverkopenOrderIdToPayByMailOrderId(Order $order):string
    {
        $parts = explode('-', $order->order_id); //returns ['ZELF', '1234'] when zelfverkopen order id is ZELF-1234
        $orderId = $parts[1];
        if($order->payment_fail_counter > 0) $orderId .= '-'.$order->payment_fail_counter;
        return $orderId;
    }
}