diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d38e3b79..eafaa9342 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,11 +11,15 @@ to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). * `recurring` flag on `\UnzerSDK\Resources\PaymentTypes\SepaDirectDebit` for registering a payment type for recurring (mandate-based) collection. * `getRawResponse()` on `\UnzerSDK\Resources\Keypair`, exposing the exact raw API response string from a Keypair fetch. +* `Unzer::fetchPaylaterPlans(BasePaymentType $paymentType, PaylaterPlansQuery $query)` to fetch the available plans (including the `secciUrl`) for any paylater payment type, e.g. `new PaylaterInvoice()` or `new PaylaterDirectDebit()`. The SECCI PDF locale follows the client locale set via `Unzer::setLocale()` (`Accept-Language` header). The payment type and query values are passed through to the API unchanged; invalid input is rejected by the API with an `UnzerApiException`. +* `\UnzerSDK\Resources\PaylaterPlans` and `\UnzerSDK\Resources\EmbeddedResources\Paylater\PaylaterPlansQuery` as the generalized plan result/query models. +* `minimumInstallmentFee` is now exposed on `\UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlan` via `getMinimumInstallmentFee()` (previously present in the API response but dropped by the SDK). ### Deprecated * `\UnzerSDK\Resources\PaymentTypes\PIS` (Unzer Bank Transfer / FlexiPay Direct) payment type. It is no longer supported and will be removed in a future major version. * `\UnzerSDK\Resources\PaymentTypes\Sofort` payment type. It is no longer supported and will be removed in a future major version. +* `\UnzerSDK\Resources\PaylaterInstallmentPlans` (use `\UnzerSDK\Resources\PaylaterPlans`) and `\UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery` (use `\UnzerSDK\Resources\EmbeddedResources\Paylater\PaylaterPlansQuery`). The legacy classes are left unchanged as standalone deprecated aliases with their original public signatures (no inheritance from the new generalized classes), so existing code keeps working. `Unzer::fetchPaylaterInstallmentPlans()` is unchanged. ### Removed diff --git a/src/Interfaces/PaymentServiceInterface.php b/src/Interfaces/PaymentServiceInterface.php index ad05a505e..fbd5a1ab7 100644 --- a/src/Interfaces/PaymentServiceInterface.php +++ b/src/Interfaces/PaymentServiceInterface.php @@ -15,9 +15,11 @@ use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; +use UnzerSDK\Resources\EmbeddedResources\Paylater\PaylaterPlansQuery; use UnzerSDK\Resources\InstalmentPlans; use UnzerSDK\Resources\Metadata; use UnzerSDK\Resources\PaylaterInstallmentPlans; +use UnzerSDK\Resources\PaylaterPlans; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Paypage; @@ -391,6 +393,23 @@ public function fetchInstallmentPlans( */ public function fetchPaylaterInstallmentPlans(InstallmentPlansQuery $plansRequest): PaylaterInstallmentPlans; + /** + * Returns a PaylaterPlans object containing all available plan options for the given paylater payment type + * (e.g. Paylater Installment, Paylater Invoice, Paylater Direct Debit). + * + * The payment type is passed through to the API as-is; the SDK neither validates it nor the query values. + * An unsupported payment type or invalid input is rejected by the API with an UnzerApiException. + * + * @param BasePaymentType $paymentType The paylater payment type the plans are requested for. + * @param PaylaterPlansQuery $query The query holding amount, currency, country and customer type. + * + * @return PaylaterPlans The object containing all available plans. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchPaylaterPlans(BasePaymentType $paymentType, PaylaterPlansQuery $query): PaylaterPlans; + /** * Perform an SCA transaction. * diff --git a/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php b/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php index 344a935c5..810ee52a1 100644 --- a/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php +++ b/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php @@ -19,6 +19,8 @@ class InstallmentPlan extends AbstractUnzerResource private $totalAmount; + private $minimumInstallmentFee; + private $nominalInterestRate; /** @var float $effectiveInterestRate */ @@ -87,6 +89,25 @@ public function setTotalAmount($totalAmount) return $this; } + /** + * @return mixed + */ + public function getMinimumInstallmentFee() + { + return $this->minimumInstallmentFee; + } + + /** + * @param mixed $minimumInstallmentFee + * + * @return InstallmentPlan + */ + public function setMinimumInstallmentFee($minimumInstallmentFee) + { + $this->minimumInstallmentFee = $minimumInstallmentFee; + return $this; + } + /** * @return mixed */ @@ -154,7 +175,7 @@ public function handleResponse(stdClass $response, string $method = HttpAdapterI if (isset($response->installmentRates)) { $rates = []; foreach ($response->installmentRates as $rate) { - $rates[] = new InstallmentRate($rate->date, $rate->rate); + $rates[] = new InstallmentRate($rate->date ?? null, $rate->rate ?? null); } $this->setInstallmentRates($rates); } diff --git a/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php b/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php index 7d949c45b..c34cf1664 100644 --- a/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php +++ b/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php @@ -8,6 +8,8 @@ /** * This class contains the query properties which are used to fetch paylater installment plans. * + * @deprecated since the introduction of the generalized paylater plans endpoint. Use + * {@see PaylaterPlansQuery} together with Unzer::fetchPaylaterPlans() instead. * @link https://docs.unzer.com/ * */ diff --git a/src/Resources/EmbeddedResources/Paylater/PaylaterPlansQuery.php b/src/Resources/EmbeddedResources/Paylater/PaylaterPlansQuery.php new file mode 100644 index 000000000..5ec1446bb --- /dev/null +++ b/src/Resources/EmbeddedResources/Paylater/PaylaterPlansQuery.php @@ -0,0 +1,111 @@ +amount = $amount; + $this->currency = $currency; + $this->country = $country; + $this->customerType = $customerType; + } + + /** + * @return float + */ + public function getAmount(): float + { + return $this->amount; + } + + /** + * @param float $amount + * + * @return PaylaterPlansQuery + */ + public function setAmount(float $amount): PaylaterPlansQuery + { + $this->amount = $amount; + return $this; + } + + /** + * @return string + */ + public function getCurrency(): string + { + return $this->currency; + } + + /** + * @param string $currency + * + * @return PaylaterPlansQuery + */ + public function setCurrency(string $currency): PaylaterPlansQuery + { + $this->currency = $currency; + return $this; + } + + /** + * @return string + */ + public function getCountry(): string + { + return $this->country; + } + + /** + * @param string $country + * + * @return PaylaterPlansQuery + */ + public function setCountry(string $country): PaylaterPlansQuery + { + $this->country = $country; + return $this; + } + + /** + * @return string + */ + public function getCustomerType(): string + { + return $this->customerType; + } + + /** + * @param string $customerType + * + * @return PaylaterPlansQuery + */ + public function setCustomerType(string $customerType): PaylaterPlansQuery + { + $this->customerType = $customerType; + return $this; + } +} diff --git a/src/Resources/PaylaterInstallmentPlans.php b/src/Resources/PaylaterInstallmentPlans.php index 4e132d2a7..6f559f8f7 100644 --- a/src/Resources/PaylaterInstallmentPlans.php +++ b/src/Resources/PaylaterInstallmentPlans.php @@ -13,6 +13,8 @@ * Please use Unzer methods to fetch the list of instalment plans * (e.g. Unzer::fetchInstallmentPlans(...)). * + * @deprecated since the introduction of the generalized paylater plans endpoint. Use + * {@see PaylaterPlans} together with Unzer::fetchPaylaterPlans() instead. * @link https://docs.unzer.com/ * */ diff --git a/src/Resources/PaylaterPlans.php b/src/Resources/PaylaterPlans.php new file mode 100644 index 000000000..927937b71 --- /dev/null +++ b/src/Resources/PaylaterPlans.php @@ -0,0 +1,205 @@ +amount; + } + + /** + * @param float $amount + * + * @return PaylaterPlans + */ + public function setAmount(float $amount): PaylaterPlans + { + $this->amount = $amount; + return $this; + } + + /** + * @return string + */ + public function getCurrency(): ?string + { + return $this->currency; + } + + /** + * @param string $currency + * + * @return PaylaterPlans + */ + public function setCurrency(string $currency): PaylaterPlans + { + $this->currency = $currency; + return $this; + } + + /** + * @return string + */ + public function getCountry(): ?string + { + return $this->country; + } + + /** + * @param string $country + * + * @return PaylaterPlans + */ + public function setCountry(string $country): PaylaterPlans + { + $this->country = $country; + return $this; + } + + /** + * @return string + */ + public function getCustomerType(): ?string + { + return $this->customerType; + } + + /** + * @param string $customerType + * + * @return PaylaterPlans + */ + public function setCustomerType(string $customerType): PaylaterPlans + { + $this->customerType = $customerType; + return $this; + } + + /** + * @return InstallmentPlan[] + */ + public function getPlans(): array + { + return $this->plans; + } + + /** + * @param stdClass[] $plans + * + * @return PaylaterPlans + */ + protected function setPlans(array $plans): PaylaterPlans + { + $this->plans = $plans; + return $this; + } + + /** + * {@inheritDoc} + */ + public function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string + { + return 'plans' . $this->getQueryString(); + } + + /** + * Returns the query string for this resource. + * + * @return string + */ + protected function getQueryString(): string + { + return '?' . http_build_query($this->getQueryArray()); + } + + /** + * Returns the parameter array containing the values for the query string. + * + * @return array + */ + protected function getQueryArray(): array + { + $parameters = []; + if ($this->queryParameter === null) { + return $parameters; + } + + return $this->getQueryParameter()->expose(); + } + + /** + * @return PaylaterPlansQuery + */ + public function getQueryParameter(): PaylaterPlansQuery + { + return $this->queryParameter; + } + + /** + * @param PaylaterPlansQuery $queryParameter + * + * @return PaylaterPlans + */ + public function setQueryParameter(PaylaterPlansQuery $queryParameter): PaylaterPlans + { + $this->queryParameter = $queryParameter; + return $this; + } + + /** + * {@inheritDoc} + */ + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void + { + parent::handleResponse($response, $method); + + if (isset($response->plans)) { + $plans = []; + foreach ($response->plans as $plan) { + $instalment = new InstallmentPlan(); + $instalment->handleResponse($plan); + $plans[] = $instalment; + } + $this->setPlans($plans); + } + } +} diff --git a/src/Services/PaymentService.php b/src/Services/PaymentService.php index a8a11b2af..78eb3c543 100755 --- a/src/Services/PaymentService.php +++ b/src/Services/PaymentService.php @@ -11,9 +11,11 @@ use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; +use UnzerSDK\Resources\EmbeddedResources\Paylater\PaylaterPlansQuery; use UnzerSDK\Resources\InstalmentPlans; use UnzerSDK\Resources\Metadata; use UnzerSDK\Resources\PaylaterInstallmentPlans; +use UnzerSDK\Resources\PaylaterPlans; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\InstallmentSecured; @@ -350,6 +352,18 @@ public function fetchPaylaterInstallmentPlans( return $this->unzer->getResourceService()->fetchResource($plans); } + /** + * {@inheritDoc} + */ + public function fetchPaylaterPlans(BasePaymentType $paymentType, PaylaterPlansQuery $query): PaylaterPlans + { + // Route via an identity-free copy so an already-identified payment type still resolves to + // types//plans instead of types//plans. The caller's instance stays untouched. + $plansParent = (clone $paymentType)->setId(null)->setParentResource($this->unzer); + $plans = (new PaylaterPlans())->setQueryParameter($query)->setParentResource($plansParent); + return $this->unzer->getResourceService()->fetchResource($plans); + } + /** * Creates the PayPage for the requested transaction method. * diff --git a/src/Unzer.php b/src/Unzer.php index f616b68d3..b7c783785 100644 --- a/src/Unzer.php +++ b/src/Unzer.php @@ -20,10 +20,12 @@ use UnzerSDK\Resources\Config; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; +use UnzerSDK\Resources\EmbeddedResources\Paylater\PaylaterPlansQuery; use UnzerSDK\Resources\InstalmentPlans; use UnzerSDK\Resources\Keypair; use UnzerSDK\Resources\Metadata; use UnzerSDK\Resources\PaylaterInstallmentPlans; +use UnzerSDK\Resources\PaylaterPlans; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Paypage; @@ -1186,6 +1188,14 @@ public function fetchPaylaterInstallmentPlans(InstallmentPlansQuery $plansReques return $this->getPaymentService()->fetchPaylaterInstallmentPlans($plansRequest); } + /** + * {@inheritDoc} + */ + public function fetchPaylaterPlans(BasePaymentType $paymentType, PaylaterPlansQuery $query): PaylaterPlans + { + return $this->getPaymentService()->fetchPaylaterPlans($paymentType, $query); + } + /** * {@inheritDoc} * diff --git a/test/Fixtures/jsonData/paylaterPlansResponse.json b/test/Fixtures/jsonData/paylaterPlansResponse.json index 15f99b5f3..d586eefdc 100644 --- a/test/Fixtures/jsonData/paylaterPlansResponse.json +++ b/test/Fixtures/jsonData/paylaterPlansResponse.json @@ -8,7 +8,7 @@ "totalAmount": "101.31", "nominalInterestRate": 9.95, "effectiveInterestRate": 10.43, - "minimumInstallmentFee": "0.00", + "minimumInstallmentFee": "2.50", "secciUrl": "https://test-payment.paylater.unzer.com/payolution-payment/infoport/creditagreementdraft/Tx-xyz?duration=3", "installmentRates": [ { diff --git a/test/Fixtures/jsonData/paylaterPlansResponseEmpty.json b/test/Fixtures/jsonData/paylaterPlansResponseEmpty.json new file mode 100644 index 000000000..2e9bdb0a1 --- /dev/null +++ b/test/Fixtures/jsonData/paylaterPlansResponseEmpty.json @@ -0,0 +1,10 @@ +{ + "id": "Tx-empty", + "amount": "99.99", + "currency": "EUR", + "plans": [], + "isSuccess": true, + "isPending": false, + "isResumed": false, + "isError": false +} diff --git a/test/Fixtures/jsonData/paylaterPlansResponseNoRates.json b/test/Fixtures/jsonData/paylaterPlansResponseNoRates.json new file mode 100644 index 000000000..93f934872 --- /dev/null +++ b/test/Fixtures/jsonData/paylaterPlansResponseNoRates.json @@ -0,0 +1,27 @@ +{ + "id": "Tx-norates", + "amount": "99.99", + "currency": "EUR", + "plans": [ + { + "numberOfRates": 3, + "totalAmount": "101.31", + "nominalInterestRate": 9.95, + "effectiveInterestRate": 10.43, + "minimumInstallmentFee": "0.00", + "secciUrl": "https://test-payment.paylater.unzer.com/payolution-payment/infoport/creditagreementdraft/Tx-norates?duration=3" + }, + { + "numberOfRates": 6, + "totalAmount": "102.60", + "nominalInterestRate": 9.95, + "effectiveInterestRate": 10.53, + "minimumInstallmentFee": "0.00", + "secciUrl": "https://test-payment.paylater.unzer.com/payolution-payment/infoport/creditagreementdraft/Tx-norates?duration=6" + } + ], + "isSuccess": true, + "isPending": false, + "isResumed": false, + "isError": false +} diff --git a/test/integration/PaymentTypes/PaylaterPlansTest.php b/test/integration/PaymentTypes/PaylaterPlansTest.php new file mode 100644 index 000000000..ea9b9d25a --- /dev/null +++ b/test/integration/PaymentTypes/PaylaterPlansTest.php @@ -0,0 +1,113 @@ +unzer->fetchPaylaterPlans($paymentType, $query); + + $this->assertTrue($plans->isSuccess()); + $this->assertGreaterThan(0, count($plans->getPlans())); + foreach ($plans->getPlans() as $plan) { + $this->assertNotEmpty($plan->getSecciUrl()); + } + } + + /** + * Permissive design: an unsupported payment type is passed through and rejected by PAPI. + * + * @test + */ + public function unsupportedPaymentTypeIsRejectedByApi(): void + { + $query = new PaylaterPlansQuery(99.99, 'EUR', 'DE'); + $unsupportedType = new SepaDirectDebit('DE89370400440532013000'); + + // Example observed sandbox behaviour (illustrative only, not asserted - codes/messages may change): + // code API.720.100.001, merchantMessage "The given payment method plans is not found.", + // customerMessage "Invalid payment method. Please contact us for more information." + try { + $this->unzer->fetchPaylaterPlans($unsupportedType, $query); + $this->fail('Expected ' . UnzerApiException::class . ' was not thrown.'); + } catch (UnzerApiException $e) { + $this->assertNotEmpty($e->getMerchantMessage()); + } + } + + /** + * Invalid input is delegated to PAPI and surfaced as an UnzerApiException. + * + * @test + * + * @dataProvider invalidQueryDataProvider + */ + public function invalidInputThrowsUnzerApiException(float $amount, string $currency, string $country): void + { + $query = new PaylaterPlansQuery($amount, $currency, $country); + + try { + $this->unzer->fetchPaylaterPlans(new PaylaterInvoice(), $query); + $this->fail('Expected ' . UnzerApiException::class . ' was not thrown.'); + } catch (UnzerApiException $e) { + $this->assertNotEmpty($e->getMerchantMessage()); + } + } + + // + + public function supportedPaylaterTypeDataProvider(): array + { + return [ + 'invoice' => [new PaylaterInvoice()], + 'directDebit' => [new PaylaterDirectDebit('DE89370400440532013000', 'Peter Mustermann')], + ]; + } + + public function invalidQueryDataProvider(): array + { + return [ + // amount=0 is NOT included: the live API accepts it (HTTP 200 with a degenerate plan). + 'negative amount' => [-99.99, 'EUR', 'DE'], + 'invalid currency' => [99.99, 'XXX', 'DE'], + 'invalid country' => [99.99, 'EUR', 'ZZ'], + ]; + } + + // +} diff --git a/test/unit/Resources/PaylaterInstallmentPlansTest.php b/test/unit/Resources/PaylaterInstallmentPlansTest.php index 607189c56..634dfd5e5 100644 --- a/test/unit/Resources/PaylaterInstallmentPlansTest.php +++ b/test/unit/Resources/PaylaterInstallmentPlansTest.php @@ -11,6 +11,7 @@ namespace UnzerSDK\test\unit\Resources; +use ReflectionMethod; use UnzerSDK\Constants\CustomerTypes; use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentRate; @@ -21,6 +22,50 @@ class PaylaterInstallmentPlansTest extends BasePaymentTest { + /** + * These deprecated classes are standalone aliases and must keep their original public + * signatures (no inheritance from the generalized PaylaterPlans/PaylaterPlansQuery). + * + * @test + * + * @dataProvider legacySignatureDataProvider + * + * @param class-string $class + */ + public function legacyPublicSignaturesAreUnchanged(string $class, string $method, ?string $expectedParamType, string $expectedReturnType): void + { + $reflection = new ReflectionMethod($class, $method); + + $returnType = $reflection->getReturnType(); + $this->assertNotNull($returnType); + $this->assertEquals($expectedReturnType, $returnType->getName()); + + if ($expectedParamType !== null) { + $params = $reflection->getParameters(); + $this->assertNotEmpty($params); + $this->assertEquals($expectedParamType, $params[0]->getType()->getName()); + } + } + + /** + * Verify the legacy fluent setters keep returning their own type for chaining. + * + * @test + */ + public function legacyFluentSettersReturnOwnType(): void + { + $query = (new InstallmentPlansQuery(100, 'EUR', 'DE')) + ->setAmount(1.0) + ->setCurrency('USD') + ->setCountry('CH') + ->setCustomerType(CustomerTypes::B2B); + $this->assertInstanceOf(InstallmentPlansQuery::class, $query); + + $plans = (new PaylaterInstallmentPlans())->setQueryParameter($query); + $this->assertInstanceOf(PaylaterInstallmentPlans::class, $plans); + $this->assertInstanceOf(InstallmentPlansQuery::class, $plans->getQueryParameter()); + } + /** * Verify getters and setters. * @@ -108,6 +153,7 @@ protected function comparePlans(array $expected, array $actual): void foreach ($expected as $index => $plan) { $this->assertEquals($plan->totalAmount ?? null, $actual[$index]->getTotalAmount()); + $this->assertEquals($plan->minimumInstallmentFee ?? null, $actual[$index]->getMinimumInstallmentFee()); $this->assertEquals($plan->nominalInterestRate ?? null, $actual[$index]->getNominalInterestRate()); $this->assertEquals($plan->effectiveInterestRate ?? null, $actual[$index]->getEffectiveInterestRate()); $this->compareRates($plan->installmentRates ?? null, $actual[$index]->getInstallmentRates()); @@ -144,5 +190,29 @@ public function verifyQueryStringDP(): array [100, 'CHF', 'CHE', 'B2C'], ]; } + + /** + * Pins the original (pre-generalization) public signatures of the deprecated legacy classes. + * + * @return array + */ + public function legacySignatureDataProvider(): array + { + $query = InstallmentPlansQuery::class; + $plans = PaylaterInstallmentPlans::class; + + return [ + 'query setAmount' => [$query, 'setAmount', 'float', $query], + 'query setCurrency' => [$query, 'setCurrency', 'string', $query], + 'query setCountry' => [$query, 'setCountry', 'string', $query], + 'query setCustomerType' => [$query, 'setCustomerType', 'string', $query], + 'plans setAmount' => [$plans, 'setAmount', 'float', $plans], + 'plans setCurrency' => [$plans, 'setCurrency', 'string', $plans], + 'plans setCountry' => [$plans, 'setCountry', 'string', $plans], + 'plans setCustomerType' => [$plans, 'setCustomerType', 'string', $plans], + 'plans getQueryParameter' => [$plans, 'getQueryParameter', null, $query], + 'plans setQueryParameter' => [$plans, 'setQueryParameter', $query, $plans], + ]; + } // } diff --git a/test/unit/Resources/PaylaterPlansTest.php b/test/unit/Resources/PaylaterPlansTest.php new file mode 100644 index 000000000..5748ed122 --- /dev/null +++ b/test/unit/Resources/PaylaterPlansTest.php @@ -0,0 +1,219 @@ +assertNull($plans->getAmount()); + $this->assertNull($plans->getCurrency()); + $this->assertNull($plans->getCountry()); + $this->assertNull($plans->getCustomerType()); + + $plans->setAmount(2.345) + ->setCurrency('USD') + ->setCountry('DE') + ->setCustomerType(CustomerTypes::B2C); + + $this->assertEquals(2.345, $plans->getAmount()); + $this->assertEquals('USD', $plans->getCurrency()); + $this->assertEquals('DE', $plans->getCountry()); + $this->assertEquals(CustomerTypes::B2C, $plans->getCustomerType()); + } + + /** + * Verify the query string is assembled from the query parameter. + * + * @test + * + * @dataProvider queryStringDataProvider + */ + public function resourcePathContainsQueryString(float $amount, string $currency, string $country, string $customerType): void + { + $query = new PaylaterPlansQuery($amount, $currency, $country, $customerType); + $plans = (new PaylaterPlans())->setQueryParameter($query); + $this->assertEquals("plans?amount={$amount}&country={$country}¤cy={$currency}&customerType={$customerType}", $plans->getResourcePath()); + } + + /** + * The default customer type is B2C when none is provided. + * + * @test + */ + public function defaultCustomerTypeIsB2c(): void + { + $query = new PaylaterPlansQuery(100, 'EUR', 'DE'); + $this->assertEquals(CustomerTypes::B2C, $query->getCustomerType()); + } + + /** + * Verify the Json response gets mapped properly for the supported paylater types. + * + * @test + * + * @dataProvider responseFixtureDataProvider + */ + public function jsonResponseIsHandledProperly(string $fixture): void + { + $plans = new PaylaterPlans(); + $jsonResponse = json_decode(JsonProvider::getJsonFromFile($fixture)); + $plans->handleResponse($jsonResponse); + + $this->assertEquals($jsonResponse->id, $plans->getId()); + $this->assertEquals($jsonResponse->amount, $plans->getAmount()); + $this->assertEquals($jsonResponse->currency, $plans->getCurrency()); + $this->assertCount(count($jsonResponse->plans), $plans->getPlans()); + + $this->comparePlans($jsonResponse->plans, $plans->getPlans()); + } + + /** + * Plans without installmentRates map cleanly (null rates), no error. + * + * @test + */ + public function planWithoutInstallmentRatesMapsCleanly(): void + { + $plans = new PaylaterPlans(); + $plans->handleResponse(json_decode(JsonProvider::getJsonFromFile('paylaterPlansResponseNoRates.json'))); + + $this->assertNotEmpty($plans->getPlans()); + foreach ($plans->getPlans() as $plan) { + $this->assertNotNull($plan->getSecciUrl()); + $this->assertNull($plan->getInstallmentRates()); + } + } + + /** + * An empty plans array maps to an empty list. + * + * @test + */ + public function emptyPlansArrayMapsToEmptyList(): void + { + $plans = new PaylaterPlans(); + $plans->handleResponse(json_decode(JsonProvider::getJsonFromFile('paylaterPlansResponseEmpty.json'))); + + $this->assertIsArray($plans->getPlans()); + $this->assertEmpty($plans->getPlans()); + } + + /** + * The minimumInstallmentFee sent by the API is exposed on each plan. + * + * @test + */ + public function minimumInstallmentFeeIsMapped(): void + { + $plans = new PaylaterPlans(); + $plans->handleResponse(json_decode(JsonProvider::getJsonFromFile('paylaterPlansResponse.json'))); + + $this->assertEquals('2.50', $plans->getPlans()[0]->getMinimumInstallmentFee()); + } + + /** + * An installment rate without a date (as returned by the amount=0 edge case) maps without a warning. + * + * @test + */ + public function installmentRateWithoutDateMapsWithoutWarning(): void + { + $response = json_decode(json_encode([ + 'id' => 'Tx-zero', + 'amount' => '0.00', + 'currency' => 'EUR', + 'plans' => [[ + 'numberOfRates' => 1, + 'totalAmount' => '0.00', + 'secciUrl' => 'https://example.test/secci', + 'installmentRates' => [['rate' => '0.00']], + ]], + ])); + + $plans = new PaylaterPlans(); + $plans->handleResponse($response); + + $rate = $plans->getPlans()[0]->getInstallmentRates()[0]; + $this->assertNull($rate->getDate()); + $this->assertEquals('0.00', $rate->getRate()); + } + + // + + /** + * @param object[] $expected + * @param InstallmentPlan[] $actual + */ + private function comparePlans(array $expected, array $actual): void + { + foreach ($expected as $index => $plan) { + $this->assertEquals($plan->totalAmount ?? null, $actual[$index]->getTotalAmount()); + $this->assertEquals($plan->minimumInstallmentFee ?? null, $actual[$index]->getMinimumInstallmentFee()); + $this->assertEquals($plan->nominalInterestRate ?? null, $actual[$index]->getNominalInterestRate()); + $this->assertEquals($plan->effectiveInterestRate ?? null, $actual[$index]->getEffectiveInterestRate()); + $this->assertNotNull($actual[$index]->getSecciUrl()); + $this->assertEquals($plan->secciUrl, $actual[$index]->getSecciUrl()); + $this->compareRates($plan->installmentRates ?? [], $actual[$index]->getInstallmentRates() ?? []); + } + } + + /** + * @param object[] $expected + * @param InstallmentRate[] $actual + */ + private function compareRates(array $expected, array $actual): void + { + foreach ($expected as $index => $rate) { + $this->assertEquals($rate->date, $actual[$index]->getDate()); + $this->assertEquals($rate->rate, $actual[$index]->getRate()); + } + } + + // + + // + + public function queryStringDataProvider(): array + { + return [ + [100, 'EUR', 'DE', 'B2C'], + [100, 'EUR', 'GB', 'B2B'], + [100, 'CHF', 'CHE', 'B2C'], + ]; + } + + public function responseFixtureDataProvider(): array + { + return [ + 'invoice' => ['paylaterPlansResponse.json'], + 'directDebit' => ['paylaterPlansResponseNoRates.json'], + ]; + } + + // +} diff --git a/test/unit/Services/PaymentServiceTest.php b/test/unit/Services/PaymentServiceTest.php index ea3441cc9..816e96bec 100755 --- a/test/unit/Services/PaymentServiceTest.php +++ b/test/unit/Services/PaymentServiceTest.php @@ -19,10 +19,18 @@ use UnzerSDK\Interfaces\ResourceServiceInterface; use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\Customer; +use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; +use UnzerSDK\Resources\EmbeddedResources\Paylater\PaylaterPlansQuery; use UnzerSDK\Resources\InstalmentPlans; use UnzerSDK\Resources\Metadata; +use UnzerSDK\Resources\PaylaterInstallmentPlans; +use UnzerSDK\Resources\PaylaterPlans; use UnzerSDK\Resources\Payment; +use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\InstallmentSecured; +use UnzerSDK\Resources\PaymentTypes\PaylaterDirectDebit; +use UnzerSDK\Resources\PaymentTypes\PaylaterInstallment; +use UnzerSDK\Resources\PaymentTypes\PaylaterInvoice; use UnzerSDK\Resources\PaymentTypes\Paypage; use UnzerSDK\Resources\PaymentTypes\Paypal; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; @@ -34,9 +42,11 @@ use UnzerSDK\Resources\TransactionTypes\Sca; use UnzerSDK\Resources\TransactionTypes\Shipment; use UnzerSDK\Services\CancelService; +use UnzerSDK\Services\HttpService; use UnzerSDK\Services\PaymentService; use UnzerSDK\Services\ResourceService; use UnzerSDK\test\BasePaymentTest; +use UnzerSDK\test\Fixtures\JsonProvider; use PHPUnit\Framework\MockObject\MockObject; use function in_array; @@ -643,6 +653,164 @@ public function fetchInstalmentPlansWillCallFetchOnResourceService(): void // + // + + /** + * Verify fetchPaylaterPlans builds the resource path and query for the given payment type, + * both for fresh types and for already-identified ones (which must still route by type name). + * + * @test + * + * @dataProvider paylaterPlansTypeDataProvider + */ + public function fetchPaylaterPlansResolvesResourcePathPerType(BasePaymentType $paymentType, string $segment): void + { + $unzer = new Unzer('s-priv-1234'); + /** @var MockObject|ResourceService $resourceSrvMock */ + $resourceSrvMock = $this->getMockBuilder(ResourceService::class)->setConstructorArgs(['unzer' => $unzer])->setMethods(['fetchResource'])->getMock(); + $unzer->setResourceService($resourceSrvMock); + + // Pre-set an id to emulate a previously created/fetched payment type. + $paymentType->setId('s-pit-identified'); + $query = new PaylaterPlansQuery(99.99, 'EUR', 'DE', 'B2B'); + + $resourceSrvMock->expects($this->once())->method('fetchResource') + ->with($this->callback(static function ($param) use ($paymentType, $segment, $query) { + return $param instanceof PaylaterPlans && + // Routing uses an identity-free copy, not the caller's instance. + $param->getParentResource() !== $paymentType && + $param->getParentResource() instanceof BasePaymentType && + $param->getQueryParameter() === $query && + $param->getUri() === "/types/{$segment}/plans?amount=99.99&country=DE¤cy=EUR&customerType=B2B"; + }))->willReturn(new PaylaterPlans()); + + $result = $unzer->getPaymentService()->fetchPaylaterPlans($paymentType, $query); + $this->assertInstanceOf(PaylaterPlans::class, $result); + // The caller's payment type must stay untouched (id preserved). + $this->assertEquals('s-pit-identified', $paymentType->getId()); + } + + /** + * Verify the default customer type B2C is applied to the query. + * + * @test + */ + public function fetchPaylaterPlansAppliesDefaultCustomerType(): void + { + $unzer = new Unzer('s-priv-1234'); + /** @var MockObject|ResourceService $resourceSrvMock */ + $resourceSrvMock = $this->getMockBuilder(ResourceService::class)->setConstructorArgs(['unzer' => $unzer])->setMethods(['fetchResource'])->getMock(); + $unzer->setResourceService($resourceSrvMock); + + $query = new PaylaterPlansQuery(10.0, 'EUR', 'DE'); + + $resourceSrvMock->expects($this->once())->method('fetchResource') + ->with($this->callback(static function ($param) { + $query = $param->getQueryParameter(); + return $param instanceof PaylaterPlans && + $query->getAmount() === 10.0 && + $query->getCurrency() === 'EUR' && + $query->getCountry() === 'DE' && + $query->getCustomerType() === 'B2C' && + $param->getUri() === '/types/paylater-invoice/plans?amount=10&country=DE¤cy=EUR&customerType=B2C'; + }))->willReturn(new PaylaterPlans()); + + $unzer->getPaymentService()->fetchPaylaterPlans(new PaylaterInvoice(), $query); + } + + /** + * Verify the deprecated fetchPaylaterInstallmentPlans still targets the installment endpoint and return type. + * + * @test + */ + public function fetchPaylaterInstallmentPlansRemainsBackwardCompatible(): void + { + $unzer = new Unzer('s-priv-1234'); + /** @var MockObject|ResourceService $resourceSrvMock */ + $resourceSrvMock = $this->getMockBuilder(ResourceService::class)->setConstructorArgs(['unzer' => $unzer])->setMethods(['fetchResource'])->getMock(); + $unzer->setResourceService($resourceSrvMock); + + $query = new InstallmentPlansQuery(99.99, 'EUR', 'DE'); + + $resourceSrvMock->expects($this->once())->method('fetchResource') + ->with($this->callback(static function ($param) { + return $param instanceof PaylaterInstallmentPlans && + $param->getParentResource() instanceof PaylaterInstallment && + $param->getUri() === '/types/paylater-installment/plans?amount=99.99&country=DE¤cy=EUR&customerType=B2C'; + }))->willReturn(new PaylaterInstallmentPlans()); + + $result = $unzer->getPaymentService()->fetchPaylaterInstallmentPlans($query); + $this->assertInstanceOf(PaylaterInstallmentPlans::class, $result); + } + + /** + * End-to-end: the generic fetchPaylaterPlans() hits types/paylater-/plans and maps the + * response (incl. a non-null secciUrl per plan) for all three plan-supporting payment types. + * + * @test + * + * @dataProvider paylaterPlansTypeDataProvider + */ + public function fetchPaylaterPlansFetchesAndMapsPlansPerType(BasePaymentType $paymentType, string $segment): void + { + $unzer = new Unzer('s-priv-1234'); + $unzer->setHttpService($this->stubPlansHttpService("types/{$segment}/plans")); + + $query = new PaylaterPlansQuery(99.99, 'EUR', 'DE'); + $plans = $unzer->fetchPaylaterPlans($paymentType, $query); + + $this->assertInstanceOf(PaylaterPlans::class, $plans); + $this->assertNotEmpty($plans->getPlans()); + foreach ($plans->getPlans() as $plan) { + $this->assertNotNull($plan->getSecciUrl()); + } + } + + /** + * End-to-end regression: the legacy fetchPaylaterInstallmentPlans() still hits + * types/paylater-installment/plans and maps to a PaylaterInstallmentPlans with secciUrl. + * + * @test + */ + public function fetchPaylaterInstallmentPlansFetchesAndMapsPlansEndToEnd(): void + { + $unzer = new Unzer('s-priv-1234'); + $unzer->setHttpService($this->stubPlansHttpService('types/paylater-installment/plans')); + + $plans = $unzer->fetchPaylaterInstallmentPlans(new InstallmentPlansQuery(99.99, 'EUR', 'DE')); + + $this->assertInstanceOf(PaylaterInstallmentPlans::class, $plans); + $this->assertNotEmpty($plans->getPlans()); + foreach ($plans->getPlans() as $plan) { + $this->assertNotNull($plan->getSecciUrl()); + } + } + + // + + // + + /** + * Builds an HttpService stub that asserts the plans endpoint URL and returns the shared plans fixture. + * + * @param string $expectedUriPart The expected types/paylater-/plans path fragment. + * + * @return MockObject|HttpService + */ + private function stubPlansHttpService(string $expectedUriPart): HttpService + { + $httpServiceMock = $this->getMockBuilder(HttpService::class) + ->disableOriginalConstructor()->onlyMethods(['send'])->getMock(); + $httpServiceMock->expects($this->once())->method('send') + ->with($this->callback(static function ($uri) use ($expectedUriPart) { + return is_string($uri) && str_contains($uri, $expectedUriPart); + })) + ->willReturn(JsonProvider::getJsonFromFile('paylaterPlansResponse.json')); + return $httpServiceMock; + } + + // + // /** @@ -657,6 +825,18 @@ public function card3dsDataProvider(): array ]; } + /** + * @return array + */ + public function paylaterPlansTypeDataProvider(): array + { + return [ + 'installment' => [new PaylaterInstallment(), 'paylater-installment'], + 'invoice' => [new PaylaterInvoice(), 'paylater-invoice'], + 'directDebit' => [new PaylaterDirectDebit(), 'paylater-direct-debit'], + ]; + } + /** * @return array */