# KDR verification

## Behavior and activation status

The optional verifier checks `StatusNumer` at the payment preview and again during final creation, before saving a payment or calling Przelewy24. Only direct group/individual lesson payments qualify. Existing payment history and reporting are unchanged; no database migration or persistent cache is used. Calls happen outside database transactions. A failed verification prevents payment creation; the customer may retry or explicitly remove the discount.

`KDR_VERIFICATION_ENABLED=false` (also the default when absent) preserves the previous 10% discount for a non-empty card number without network calls. With the flag enabled, missing credentials, transport failures and unknown/incomplete responses block the discounted payment. They never silently bypass verification. The ordinary discount-code and gift-voucher paths are unchanged.

**Local activated; test-next pending:** the current provider documentation (interface 2.35.9 and test-method instructions 1.3.0, updated 2026-06-19) changes the endpoint to `https://kdr-ws-test.empatia.gov.pl/kdr/InfoKarta`. Local live calls using the issued certificate and full TLS verification returned the expected results for all three fixtures. Local verification is enabled; test-next must remain disabled until the endpoint correction, PEM upload and remote smoke tests are complete. No direct SSH access was available. Production is unchanged. Provider email confirms SOAP 1.2/client TLS without WS-Security, XML signatures or UsernameToken, no outgoing IP registration and currently no call limits. Production requires a separate certificate.

The API verifies a card, not its ownership. It does not return holder identity. Automatic bank-transfer reconciliation is outside this integration.

## Configuration and private files

Add the following inside PHP in `application/config/config.php` on local and test-next. This file and `application/config/kdr-test/` are ignored by Git. Never commit their contents.

```php
define('KDR_API_URL', 'https://kdr-ws-test.empatia.gov.pl/kdr/InfoKarta');
define('KDR_VERIFICATION_ENABLED', false);
define('KDR_CLIENT_CERT_PATH', __DIR__ . '/kdr-test/client-chain.pem');
define('KDR_PRIVATE_KEY_PATH', __DIR__ . '/kdr-test/rollschool-test.key.pem');
define('KDR_CA_BUNDLE_PATH', __DIR__ . '/kdr-test/ca-bundle.pem');
define('KDR_PRIVATE_KEY_PASSWORD', '');
```

`KDR_API_URL` contains the complete HTTPS service address, read directly by the client. There is no environment selector, hostname map or hard-coded API address in the library. Set `https://kdr-ws-test.empatia.gov.pl/kdr/InfoKarta` on local and test-next. Missing, non-string, malformed or non-HTTPS values fail closed before network access when verification is enabled. With the flag disabled, no API configuration is required. The setting is server-owned and must never come from request input.

For production, after separate authorization and issuance of production credentials, set `KDR_API_URL` to `https://kdr-ws.empatia.gov.pl/kdr/InfoKarta` and the three file paths to the corresponding PEM files in `__DIR__ . '/kdr-production/'` (use `rollschool-production.key.pem` for the key). Keep the flag false during installation; never use test certificates or fixtures against production. No code edit is needed. This release does not activate or configure production. cURL and DOM extensions are required. Timeouts are 3 seconds to connect and 8 seconds overall; no retries or redirects. Responses are limited to 64 KiB, XML external resources are not loaded, and card numbers/credentials are not logged.

The confirmed contract: only `Wydana` qualifies. An absent `ExpiryDate` on that status means a permanent card. An empty element, explicit `xsi:nil` or duplicate expiry element is not an absent element and is rejected as unavailable. `Unieważniona`, `Anulowana` and `Upłynął termin ważności` are invalid. Unknown statuses fail closed. Date-only expiry is inclusive through the indicated calendar day in Europe/Warsaw. The parser accepts ISO `YYYY-MM-DD`, the provider's `YYYY.MM.DD` example and legacy XSD dateTime; live responses on 2026-09-28 used the legacy XSD dateTime representation. No permanent-card configuration override is needed; remove the obsolete `KDR_PERMANENT_EXPIRY_VALUE` definition if previously added.

## CSR and activation email

The private local activation package is at:
`$HOME/Sites/rollschool.localhost/application/config/kdr-test/`.

- `rollschool-test.key.pem`: private RSA 2048 key, mode 600. Do not send.
- `rollschool-test.csr`: accepted PKCS#10 request signed with SHA-256. The only email attachment; `.csr.pem` is the original identical copy.
- `rollschool-test.csr.txt`: readable public request details.
- `mail.txt`: prepared email to partnerzy.kdr@mrpips.gov.pl requesting a test certificate and activation, with questions about SOAP/security, shared use/IP restrictions, test numbers and permanent-card/date semantics.

The subject identifies Fundacja Rolki dla każdego, Warszawa, PL, Rollschool TEST and kontakt@rollschool.pl. The email includes NIP 9512480918. The CSR signature and matching public keys were verified locally. Do not regenerate the private key after sending the request; the returned certificate must match it. The operator sent the request; the provider has confirmed its parameters and accepted the `.csr` attachment.

## Installation on local and test-next

1. Keep the flag false. The CSR is already accepted; obtain the issued certificate, intermediate certificates, trusted CA bundle and any accompanying installation instructions. Back up the private key through the operator's secure backup process.
2. Convert issued certificates to PEM as necessary. Prepare `client-chain.pem` with the client certificate first followed by its intermediate chain. Prepare `ca-bundle.pem` with the trusted CA certificates needed to validate the API server; do not assume the client issuer chain necessarily covers the server certificate.
3. Place these two files in the local private directory above. Verify the certificate public key matches the CSR/key, its validity dates and the chain. Never overwrite the private key with a new one.
4. After code deployment, securely copy exactly `rollschool-test.key.pem`, `client-chain.pem` and `ca-bundle.pem` from the local private directory to `/home/rollschomq-rg/test-next.rollschool.pl/application/config/kdr-test/`. The directory is outside `public_html`. Set directory permissions to 700 and files to 600 for the PHP execution owner; verify readability by that owner. Do not copy the key to production. No files are deleted and no SQL migration is required.
5. Add the configuration above to `/home/rollschomq-rg/test-next.rollschool.pl/application/config/config.php`. Local Docker sees the local directory as `/var/www/sites/rollschool.localhost/application/config/kdr-test/`. The same relative config paths work in both runtimes. Check that the PHP user can read the restricted files without making them public.
6. After installing credentials, enable the flag on local for the controlled smoke test below. On failure immediately set it false and diagnose. After successful local testing, repeat on test-next. Do not initiate real payment-provider transactions: verify the site's payment gateway is in test mode first.
7. Verify `/application/config/kdr-test/rollschool-test.key.pem` is not HTTP-accessible on either host without printing/downloading its contents. The server document root must remain `public_html`.

Rollback: set the flag false; this deliberately restores the historical unverified discount. No data rollback is needed. Remove credentials only after disabling the flag if access is being retired. For renewal, keep the old working files in a restricted backup, validate a matching replacement set, disable verification during replacement, run the smoke tests, and re-enable. Restore the old unexpired set if renewal fails. Track certificate expiry operationally.

## Testing

Run offline tests in Docker:

```sh
docker compose -f "$HOME/Docker/localdev/docker-compose.yml" exec -T --workdir /var/www/sites/rollschool.localhost web-rollschool php tests/kdr_verification_test.php
docker compose -f "$HOME/Docker/localdev/docker-compose.yml" exec -T --workdir /var/www/sites/rollschool.localhost web-rollschool php tests/kdr_verification_test.php enabled
```

These cover disabled/no-network behavior, enabled transport failure/missing configuration, valid/expired/cancelled cards, permanent cards without expiry and inclusive date-only expiry, malformed/incomplete XML, wrong card numbers, unsupported status and payment-save rejection. Run the existing promo-code workflow tests too.

After certificate activation run `php scripts/check-kdr.php` in the site root (inside the PHP Docker container on local). It reads the number from stdin and prints only `valid`, `invalid` or `unavailable`. Flag false returns exit 2 without a call; valid returns 0 and other outcomes 1. Do not expose this CLI helper as a web endpoint.

The provider confirmed these test numbers by email (superseding the 2020 document):

| Number | Confirmed description | Expected result |
|---|---|---|
| 16010220004601001 | Active, permanent; Wydana without ExpiryDate | valid |
| 16010220002104001 | Active until 2042-08-07 inclusive | valid through that day |
| 16010220000901001 | Inactive since 2015-11-01 | invalid |

These fixtures were queried successfully locally on 2026-09-28 (see record below). Obtain additional cancelled and nonexistent fixtures if needed; do not use arbitrary real card numbers.

Manual acceptance on both environments: apply a valid test card to a group lesson and an individual lesson, verify 10%, then create a test payment. Repeat with invalid card, unavailable endpoint/credentials and changed submitted number; no rejected attempt may create a payment or contact Przelewy24. Check preserved form input, the explicit remove-discount action, normal codes/vouchers, excluded balance/pass payments, flag off, and a permanent card after provider confirmation. Record actual test date, environment and result here without credentials or real card numbers. Until these tests pass, leave the flag false.

## Local verification record — 2026-09-23

PHP syntax checks passed for all changed PHP files and the local configuration. Offline KDR tests passed with verification enabled and disabled; the existing promo-code workflow tests passed. The CLI helper exits 2 with the flag disabled and does not call the API. An HTTP HEAD request to the private-key URL returned 404 on local; the configured document root is public_html. CSR signature and public-key matching passed; the key is mode 600 and the package is ignored by Git. No live KDR or test-next acceptance test has been performed: an issued certificate and live verification are still required. The provider contract was subsequently confirmed by email as described above.

## Provider-contract verification — 2026-09-25

Updated the parser and offline fixtures to the provider's email: issued cards without ExpiryDate are permanent, date-only validity includes the full calendar day, and Upłynął termin ważności is invalid. Both flag-mode tests, the promo-code workflow regression and PHP syntax checks passed. The release is intended for test-next with verification disabled; it does not include credentials or live KDR activation.

## Certificate installation and resolved TLS blocker — 2026-09-28

The provider archive contains the issued client certificate, Test_SubCA_SC intermediate and Test_RootCA root in DER format. They were converted to PEM in the ignored private directory. The leaf public key matches the existing private key and the client chain verifies successfully. Client validity: 2026-09-28 06:28:52 UTC to 2028-09-28 06:28:52 UTC.

Local `client-chain.pem` contains the leaf followed by the intermediate. `ca-bundle.pem` contains the local PHP container's system CA bundle (`/etc/ssl/certs/ca-certificates.crt`) plus the supplied Test_RootCA. The CA files supplied for the client certificate alone do not cover the API server's public Certum chain. All three runtime files are mode 600 and readable by the local WWW process; the private directory remains Git-ignored.

Three documented fixture calls from local PHP failed during TLS, before SOAP responses could be obtained. The test endpoint resolved to 217.153.230.189 and, with SNI `kdr-ws-test.mpips.gov.pl`, presented a certificate with CN `*.empatia.gov.pl` and SAN `*.empatia.gov.pl`, `empatia.gov.pl`. After assembling the complete trust bundle, OpenSSL reports verify error 62 (hostname mismatch); cURL reports error 60 (no matching alternative subject name). This was not a card-status result. The corrected endpoint in the new documentation resolved this historical blocker, as recorded below.

The package is ready locally for uploading the three runtime PEM files to test-next. No files have been installed there: direct SSH authentication was rejected. The user may upload them using SFTP/FTPS to the documented directory, retaining restrictive permissions and keeping the flag false. The ignored directory includes `UPLOAD-test-next.txt` with precise instructions and `mail-tls.txt` with a draft for the provider. No message has been sent. Local checks subsequently passed; repeat all three fixtures on test-next before enabling its payment feature.

## TLS blocker resolved and local activation — 2026-09-28

Newly supplied documentation explicitly identifies the Empatia endpoint, with the domain change dated 2026-06-19. The previous hostname mismatch was caused by using the obsolete mpips.gov.pl address, not by the issued client certificate. Earlier blocker notes above are historical and the draft TLS complaint must not be sent.

After correcting the client endpoint, local PHP calls with full peer and hostname verification returned valid for 16010220004601001, valid for 16010220002104001, and invalid for 16010220000901001. Local KDR_VERIFICATION_ENABLED was then set true. The client uses automatic cURL handle cleanup to avoid PHP 8.5 curl_close deprecation output. Test-next still requires deploying this endpoint correction, uploading the PEM files and repeating smoke tests before activation; no remote configuration or credentials were changed. No payment or enrollment records were created during these API checks.

## URL configuration

The URL is independent of the feature flag and certificate paths. Replace the obsolete KDR_API_ENVIRONMENT definition with KDR_API_URL in any previously configured environment; no compatibility mapping remains. Before enabling test-next, set the test URL shown above and install the three PEM files. Run tests/kdr_configuration_test.php separately with arguments test, production, custom, invalid, non-string and without an argument; these tests never call any API. The custom URL case ensures the library uses the supplied address without environment-based routing. The CLI check prints the configured endpoint before reading a card number.
