Klarna   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
c 2
b 0
f 0
dl 0
loc 50
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getPaymentUrl() 0 26 3
1
<?php
2
3
namespace App\PaymentProvider;
4
5
use Sofort\SofortLib\Sofortueberweisung;
6
use App\Purchase;
7
use App\Exceptions\PaymentProviderException;
8
use Illuminate\Support\Facades\Log;
9
10
/**
11
 * Class to process requests to Klarna
12
 * 
13
 * Find docs @ https://github.com/sofort/sofortlib-php
14
 */
15
class Klarna
16
{
17
    /**
18
     * API-Object; initialized by constructor
19
     */
20
    protected $sofortApi;
21
22
    /**
23
     * 
24
     * @param string $configKey Configuration key for this exact project
25
     * @return void
26
     */
27
    public function __construct($configKey)
28
    {
29
        $this->sofortApi = new Sofortueberweisung($configKey);
30
    }
31
32
    /**
33
     * Generates for a given Purchase a payment request at Klarna and
34
     * returns a payment url where the customer can pay the purchase
35
     * 
36
     * @param Purchase $purchase the customer's purchase
37
     * @return string PaymentUrl to Klarna for the given purchase
38
     */
39
    public function getPaymentUrl(Purchase $purchase)
40
    {
41
        $this->sofortApi->setAmount($purchase->total());
42
        $this->sofortApi->setCurrencyCode('EUR');
43
        $this->sofortApi->setReason('#'.$purchase->id . ' Purchase');
44
        $this->sofortApi->setSuccessUrl(route('ts.payment.successful', [
45
            'purchase' => $purchase->random_id,
46
            'secret' => $purchase->payment_secret
47
        ]));
48
        $this->sofortApi->setAbortUrl(route('ts.payment.aborted', ['purchase' => $purchase->random_id]));
49
        $this->sofortApi->setTimeoutUrl(route('ts.payment.timedout', ['purchase' => $purchase->random_id]));
50
51
        $this->sofortApi->sendRequest();
52
53
        if ($this->sofortApi->isError()) {
54
            // SOFORT-API didn't accept the data
55
            foreach($this->sofortApi->getErrors() as $error) {
56
                Log::error($error);
57
            }
58
            throw new PaymentProviderException("SOFORT got errors...");
59
        }
60
        // get unique transaction-ID useful for check payment status
61
        $transactionId = $this->sofortApi->getTransactionId();
62
        Log::info('[Klarna] TransactionId for purchase #' . $purchase->id . ' is ' . $transactionId);
63
        // buyer must be redirected to $paymentUrl else payment cannot be successfully completed!
64
        return $this->sofortApi->getPaymentUrl();
65
    }
66
67
}
68