diff --git a/.gitattributes b/.gitattributes index 26d083c..624c649 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,11 @@ +/.github/ export-ignore /Build/ export-ignore +/Tests/ export-ignore +/.editorconfig export-ignore /.gitattributes export-ignore /.gitlab-ci.yml export-ignore -/.travis.yml export-ignore \ No newline at end of file +/codeception.dist.yml export-ignore +/crowdin.yml export-ignore +/Makefile export-ignore +/rector.php export-ignore +/shell.nix export-ignore diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..91b84b7 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,81 @@ +# Contributing + +When contributing to this repository, please first discuss the change you wish to make via issue, +email, or any other method with the owners of this repository before making a change. + +## Getting Started + +* Make sure you have a [GitHub account](https://github.com/signup/free) +* Submit a ticket for your [issue](https://github.com/extcode/cart/issues), assuming one does not already exist. + * Clearly describe the issue including steps to reproduce when it is a bug. +* Fork the repository on GitHub + +## Making Changes + +* Create a topic branch from where you want to base your work. + * This is usually the master branch. + * Only target release branches if you are certain your fix must be on that + branch. + * To quickly create a topic branch based on master; `git checkout -b + fix/master/my_contribution master`. Please avoid working directly on the + `master` branch. +* Make commits of logical units. +* Use `./php-cs-fixer fix --config-file Build/.php_cs` to make sure the code is formatted correctly. +* Make sure your commit messages are in the proper format. Use either `[TASK]`, `[FEATURE]`, `[BUGFIX]` or `[DOC]` + +```` + [TASK] Make the example in CONTRIBUTING imperative and concrete + + The first line is a real life imperative statement. + The body describes the behavior without the patch, + why this is a problem, and how the patch fixes the problem when applied. + + Resolves: #123 +```` + +* Make sure you have added the necessary tests for your changes. +* Run _all_ the tests to assure nothing else was accidentally broken. However travis will do that for you as well. + +## Making Trivial Changes + +For changes of a trivial nature, it is not always necessary to create a new issue. + +## Additional resources + +* [Rendered documentation](https://docs.typo3.org/typo3cms/extensions/cart/) +* [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) + + +## Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of fostering an open and +welcoming community, we pledge to respect all people who contribute through reporting issues, +posting feature requests, updating documentation, submitting pull requests or patches, and other +activities. + +We are committed to making participation in this project a harassment-free experience for everyone, +regardless of level of experience, gender, gender identity and expression, sexual orientation, +disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic addresses, without explicit + permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, +code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By +adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently +applying these principles to every aspect of managing this project. Project maintainers who do not +follow or enforce the Code of Conduct may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), +version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..ffb6d99 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: extcode +custom: ["https://paypal.me/extcart"] diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..b03dc81 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,6 @@ + diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md new file mode 100644 index 0000000..fde55a8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -0,0 +1,26 @@ +--- +name: Bug Report +about: If something isn't working as expected. + +--- + +## Bug Report + +**Current Behavior** +A clear and concise description of the behavior. + +**Expected behavior/output** +A clear and concise description of what you expected to happen. + +**Environment** +- TYPO3 version(s): [e.g. 13.4.2] +- cart version: [e.g. 10.0.0] +- cart_paypal version: [e.g. 6.0.0] +- Is your TYPO3 installation set up with Composer (Composer Mode): [yes, no] +- OS: [e.g. OSX 10.13.4, Windows 10] + +**Possible Solution** + + +**Additional context** +Add any other context about the problem here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/Feature_request.md b/.github/ISSUE_TEMPLATE/Feature_request.md new file mode 100644 index 0000000..619ba21 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Feature_request.md @@ -0,0 +1,19 @@ +--- +name: Feature Request +about: I have a suggestion! + +--- + +## Feature Request + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I have an issue when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. Add any considered drawbacks. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Teachability, Documentation, Adoption, Migration Strategy** +If you can, explain how users will be able to use this and possibly amend the documentation. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/Support_question.md b/.github/ISSUE_TEMPLATE/Support_question.md new file mode 100644 index 0000000..38a60c1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Support_question.md @@ -0,0 +1,5 @@ +--- +name: Support Question +about: If you have a question, please check out our [Slack Channel](https://typo3.slack.com/messages/ext-cart/)! + +--- \ No newline at end of file diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..c5886ad --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,188 @@ +name: CI +on: + - pull_request +jobs: + check-composer: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Validate composer.json + run: composer validate + + php-linting: + runs-on: ubuntu-latest + strategy: + matrix: + php-version: + - 8.2 + - 8.3 + - 8.4 + - 8.5 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php-version }}" + tools: composer:v2 + + - name: PHP lint + run: Build/Scripts/lint-php.sh + + typos-linting: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install typos + run: pipx install typos + + - name: Typos lint + run: Build/Scripts/lint-typos.sh + + typoscript-linting: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.2" + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: TypoScript lint + run: Build/Scripts/lint-typoscript.sh + + xml-linting: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install xmllint + run: sudo apt-get update && sudo apt-get install -y libxml2-utils + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.2" + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: XML lint + run: Build/Scripts/lint-xml.sh + + yaml-linting: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install yamllint + run: pipx install yamllint + + - name: YAML lint + run: Build/Scripts/lint-yaml.sh + + documentation-rendering: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Documentation without warnings + run: | + mkdir -p Documentation-GENERATED-temp \ + && docker run --rm --pull always -v $(pwd):/project \ + ghcr.io/typo3-documentation/render-guides:latest --config=Documentation --no-progress --fail-on-log + + coding-guideline: + runs-on: ubuntu-latest + needs: + - php-linting + steps: + - uses: actions/checkout@v4 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.2" + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Coding Guideline + run: Build/Scripts/cgl.sh + + code-quality: + runs-on: ubuntu-latest + needs: + - php-linting + strategy: + matrix: + include: + - php-version: '8.2' + typo3-version: '^13.4' + - php-version: '8.3' + typo3-version: '^13.4' + - php-version: '8.4' + typo3-version: '^13.4' + - php-version: '8.5' + typo3-version: '^13.4' + steps: + - uses: actions/checkout@v4 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php-version }}" + tools: composer:v2 + + - name: Install dependencies with expected TYPO3 version + run: |- + composer require --no-interaction --prefer-dist --no-progress "typo3/cms-core:${{ matrix.typo3-version }}" "typo3/cms-extbase:${{ matrix.typo3-version }}" "typo3/cms-frontend:${{ matrix.typo3-version }}" + + - name: Code Quality (by PHPStan) + run: Build/Scripts/phpstan.sh + + tests-unit-and-functional: + runs-on: ubuntu-latest + needs: + - coding-guideline + - code-quality + strategy: + matrix: + php-version: + - 8.2 + - 8.3 + - 8.4 + - 8.5 + steps: + - uses: actions/checkout@v4 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php-version }}" + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Run unit tests + run: Build/Scripts/phpunit.sh unit + + - name: Run functional tests + run: Build/Scripts/phpunit.sh functional diff --git a/.gitignore b/.gitignore index bbf6d53..78ffaec 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,16 @@ -.build +.Build composer.lock -.php_cs.cache -.phplint.cache +.php-cs-fixer.cache +Build/.phpunit.cache + +Documentation/_make +Documentation-GENERATED-temp/ .DS_Store .idea + +var/ + +phpunit.coverage.xml +phpunit.report.xml \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml deleted file mode 100644 index 2ad9923..0000000 --- a/.gitlab-ci.yml +++ /dev/null @@ -1,142 +0,0 @@ -cache: - key: "$CI_JOB_STAGE-$CI_COMMIT_REF_NAME" - paths: - - .composer/ - - .php_cs.cache - -variables: - COMPOSER_CACHE_DIR: ".composer" - -before_script: - - apk add git --update - -stages: - - lint - - documentation - - analysis - -lint:cgl: - image: composer:2.0 - stage: lint - before_script: - - composer config platform.php 7.4 - - composer remove typo3/cms-core --no-update - - composer install --no-progress --no-ansi --no-interaction - script: - - .build/bin/php-cs-fixer fix --config=Build/.php-cs-fixer.dist.php -v --dry-run --using-cache=no --path-mode=intersection ./ - -lint:typoscriptcgl: - stage: lint - image: composer:2.0 - script: - - composer config platform.php 7.4 - - composer remove typo3/cms-core --no-update - - composer install --no-progress --no-ansi --no-interaction - - .build/bin/typoscript-lint -c tslint.yaml - -lint:yaml: - stage: lint - image: python:alpine3.7 - before_script: - - pip install yamllint==1.10.0 - script: - - yamllint -c Build/yamllint.yaml Configuration/ Resources/ - -lint:php72: - stage: lint - image: php:7.2-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -lint:php73: - stage: lint - image: php:7.3-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -lint:php74: - stage: lint - image: php:7.4-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -lint:php80: - stage: lint - image: php:8.0-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -lint:php81: - stage: lint - image: php:8.1-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -lint:php82: - stage: lint - image: php:8.2-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -lint:php83: - stage: lint - image: php:8.3-alpine - script: - - find . -name \*.php -exec php -l "{}" \; - -phpstan:analyse: - image: composer:2 - stage: lint - before_script: - - composer config platform.php 7.4 - - composer install --no-progress --no-ansi --no-interaction - script: - - .build/bin/phpstan analyse -c Build/phpstan.neon - -documentation: - stage: documentation - image: - name: t3docs/render-documentation:v2.4.0 - entrypoint: [""] - before_script: - - cp -a ${CI_PROJECT_DIR}/. /PROJECT - - mkdir -p ${CI_PROJECT_DIR}/Documentation-GENERATED-temp - script: - - cd /ALL/venv - - /ALL/Menu/mainmenu.sh makehtml-no-cache -c resultdir ${CI_PROJECT_DIR}/Documentation-GENERATED-temp - artifacts: - paths: - - ${CI_PROJECT_DIR}/Documentation-GENERATED-temp/Result/project/0.0.0 - expire_in: 1 day - when: always - -sonarqube: - stage: analysis - image: ciricihq/gitlab-sonar-scanner - variables: - SONAR_URL: "https://sonar.extco.de" - SONAR_PROJECT_NAME: "$CI_PROJECT_NAME" - SONAR_TOKEN: "$SONAR_TOKEN" - SONAR_PROJECT_VERSION: "$CI_JOB_ID" - SONAR_ANALYSIS_MODE: "issues" - SONAR_SOURCES: "./Classes" - SONAR_GITLAB_PROJECT_ID: "$CI_PROJECT_ID" - script: - - echo "sonar.projectKey=cart_paypal-6.x" > sonar-project.properties - - gitlab-sonar-scanner -Dsonar.php.coverage.reportPath=phpunit.coverage.xml -Dsonar.php.tests.reportPath=phpunit.report.xml - allow_failure: true - -sonarqube-reports: - stage: analysis - image: ciricihq/gitlab-sonar-scanner - variables: - SONAR_URL: "https://sonar.extco.de" - SONAR_PROJECT_NAME: "$CI_PROJECT_NAME" - SONAR_TOKEN: "$SONAR_TOKEN" - SONAR_PROJECT_VERSION: "$CI_JOB_ID" - SONAR_ANALYSIS_MODE: "publish" - SONAR_SOURCES: "./Classes" - SONAR_TESTS: "./Tests" - script: - - echo "sonar.projectKey=cart_paypal-6.x" > sonar-project.properties - - gitlab-sonar-scanner -Dsonar.php.coverage.reportPath=phpunit.coverage.xml -Dsonar.php.tests.reportPath=phpunit.report.xml diff --git a/Build/.php-cs-fixer.dist.php b/Build/.php-cs-fixer.dist.php index 3ef07ec..e04f9fa 100644 --- a/Build/.php-cs-fixer.dist.php +++ b/Build/.php-cs-fixer.dist.php @@ -1,52 +1,64 @@ in(__DIR__ . '/../') - ->exclude('.build') - ->exclude('Documentation') - ->exclude('Resources') - ->notName('ext_emconf.php') - ->notName('ext_localconf.php') - ->notName('ext_tables.php'); - -$config = new PhpCsFixer\Config(); -$config +return (new \PhpCsFixer\Config()) + ->setFinder( + (new PhpCsFixer\Finder()) + ->ignoreVCSIgnored(true) + ->in(__DIR__ . '/../') + ) ->setRiskyAllowed(true) ->setRules([ - '@PSR2' => true, - 'no_leading_import_slash' => true, - 'no_trailing_comma_in_singleline_array' => true, - 'no_singleline_whitespace_before_semicolons' => true, - 'no_unused_imports' => true, + '@DoctrineAnnotation' => true, + '@PER-CS' => true, + 'array_syntax' => ['syntax' => 'short'], + 'cast_spaces' => ['space' => 'none'], 'concat_space' => ['spacing' => 'one'], - 'no_whitespace_in_blank_line' => true, - 'ordered_imports' => true, - 'single_quote' => true, + 'declare_equal_normalize' => ['space' => 'none'], + 'declare_parentheses' => true, + 'declare_strict_types' => true, + 'dir_constant' => true, + 'function_to_constant' => ['functions' => ['get_called_class', 'get_class', 'get_class_this', 'php_sapi_name', 'phpversion', 'pi']], + 'modernize_strpos' => true, + 'modernize_types_casting' => true, + 'native_function_casing' => true, + 'no_alias_functions' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_phpdoc' => true, 'no_empty_statement' => true, 'no_extra_blank_lines' => true, - 'phpdoc_no_package' => true, - 'phpdoc_scalar' => true, - 'no_blank_lines_after_phpdoc' => true, - 'array_syntax' => ['syntax' => 'short'], - 'whitespace_after_comma_in_array' => true, - 'function_typehint_space' => true, - 'single_line_comment_style' => true, - 'no_alias_functions' => true, - 'lowercase_cast' => true, 'no_leading_namespace_whitespace' => true, - 'native_function_casing' => true, - 'self_accessor' => true, + 'no_null_property_initialization' => true, 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_superfluous_elseif' => true, + 'no_trailing_comma_in_singleline' => true, 'no_unneeded_control_parentheses' => true, + 'no_unused_imports' => true, + 'no_useless_else' => true, + 'no_useless_nullsafe_operator' => true, + 'ordered_imports' => ['imports_order' => ['class', 'function', 'const'], 'sort_algorithm' => 'alpha'], + 'php_unit_construct' => ['assertions' => ['assertEquals', 'assertSame', 'assertNotEquals', 'assertNotSame']], + 'php_unit_mock_short_will_return' => true, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'phpdoc_no_access' => true, 'phpdoc_no_empty_return' => true, - 'phpdoc_trim' => true - ]) - ->setUsingCache(false) - ->setFinder($finder); - -return $config; + 'phpdoc_no_package' => true, + 'phpdoc_scalar' => true, + 'phpdoc_trim' => true, + 'phpdoc_types' => true, + 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], + 'return_type_declaration' => ['space_before' => 'none'], + 'single_quote' => true, + 'single_space_around_construct' => true, + 'single_line_comment_style' => ['comment_types' => ['hash']], + 'trailing_comma_in_multiline' => ['elements' => ['arrays']], + 'type_declaration_spaces' => true, + 'whitespace_after_comma_in_array' => ['ensure_single_space' => true], + 'yoda_style' => ['equal' => false, 'identical' => false, 'less_and_greater' => false], + ]); diff --git a/Build/Scripts/cgl.sh b/Build/Scripts/cgl.sh new file mode 100755 index 0000000..460cd7e --- /dev/null +++ b/Build/Scripts/cgl.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# +# Checks the coding guidelines with php-cs-fixer. +# +# Usage: +# Build/Scripts/cgl.sh check only, fails on violations +# Build/Scripts/cgl.sh --fix fix the violations in place + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary php-cs-fixer + +FIXER_ARGS=(--config=Build/.php-cs-fixer.dist.php --using-cache=no) +if [ "${1:-}" = "--fix" ]; then + shift +else + FIXER_ARGS+=(-v --dry-run --diff) +fi + +runPhp "${BIN_DIR}/php-cs-fixer" fix "${FIXER_ARGS[@]}" "$@" diff --git a/Build/Scripts/common.sh b/Build/Scripts/common.sh new file mode 100644 index 0000000..9220642 --- /dev/null +++ b/Build/Scripts/common.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# +# Shared setup for all scripts in Build/Scripts. +# +# This file is sourced, not executed. It changes to the project root, so every +# script behaves the same no matter from where it has been called, and it +# provides the defaults all scripts rely on. +# +# Environment variables used as overrides: +# PHP_BIN php binary to use, defaults to "php" +# PHP_MEMORY_LIMIT memory_limit for all php calls, defaults to "-1" + +set -euo pipefail + +PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +readonly PROJECT_ROOT +cd "${PROJECT_ROOT}" + +PHP_BIN="${PHP_BIN:-php}" +PHP_MEMORY_LIMIT="${PHP_MEMORY_LIMIT:--1}" +BIN_DIR="${PROJECT_ROOT}/.Build/bin" +readonly PHP_BIN PHP_MEMORY_LIMIT BIN_DIR + +# Runs php with the configured memory limit, independent of the php.ini in use. +runPhp() { + "${PHP_BIN}" -d memory_limit="${PHP_MEMORY_LIMIT}" "$@" +} + +# Fails with a readable message if composer install has not been run yet. +requireBinary() { + if [ ! -f "${BIN_DIR}/$1" ]; then + echo "Missing ${BIN_DIR}/$1, please run \"composer install\" first." >&2 + exit 1 + fi +} diff --git a/Build/Scripts/coverage.sh b/Build/Scripts/coverage.sh new file mode 100755 index 0000000..21e6452 --- /dev/null +++ b/Build/Scripts/coverage.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# +# Runs all phpunit tests and measures the code coverage of Classes/. +# +# Usage: +# Build/Scripts/coverage.sh [additional phpunit arguments] +# +# Every testsuite defined in Build/phpunit.xml.dist runs in its own phpunit +# process, like in phpunit.sh, the functional bootstrap leaks global state +# into the unit tests. The coverage of all suites is merged with phpcov, the +# summary is printed and the html report is written to +# .Build/coverage/index.html. +# +# Requirements: +# - php with xdebug or pcov +# +# Environment variables used as overrides: +# typo3DatabaseDriver database driver to test against, defaults to "pdo_sqlite" + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary phpunit +requireBinary phpcov + +if ! runPhp -r 'exit(extension_loaded("xdebug") || extension_loaded("pcov") ? 0 : 1);'; then + echo "Missing coverage driver, please enable xdebug or pcov." >&2 + exit 1 +fi + +export typo3DatabaseDriver="${typo3DatabaseDriver:-pdo_sqlite}" +export XDEBUG_MODE=coverage + +COVERAGE_PATH="${PROJECT_ROOT}/.Build/coverage" +COVERAGE_DATA_PATH="${COVERAGE_PATH}/data" +rm -rf "${COVERAGE_PATH}" +mkdir -p "${COVERAGE_DATA_PATH}" + +mapfile -t SUITES < <(runPhp "${BIN_DIR}/phpunit" -c Build/phpunit.xml.dist --list-suites \ + | sed -n 's/^ - \(.*\) ([0-9]\{1,\} tests\{0,1\})$/\1/p') + +if [ ${#SUITES[@]} -eq 0 ]; then + echo "No testsuites found in Build/phpunit.xml.dist." >&2 + exit 1 +fi + +STATUS=0 +for suite in "${SUITES[@]}"; do + echo "Running testsuite \"${suite}\" ..." + runPhp "${BIN_DIR}/phpunit" \ + -c Build/phpunit.xml.dist \ + --testsuite "${suite}" \ + --coverage-php "${COVERAGE_DATA_PATH}/${suite}.cov" \ + "$@" || STATUS=$? +done + +runPhp "${BIN_DIR}/phpcov" merge \ + --text php://stdout \ + --html "${COVERAGE_PATH}" \ + "${COVERAGE_DATA_PATH}" + +echo "HTML report: ${COVERAGE_PATH}/index.html" + +exit "${STATUS}" diff --git a/Build/Scripts/lint-php.sh b/Build/Scripts/lint-php.sh new file mode 100755 index 0000000..1b86352 --- /dev/null +++ b/Build/Scripts/lint-php.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# +# Lints all php files of the extension for syntax errors. +# +# Usage: +# Build/Scripts/lint-php.sh + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +find ./*.php Classes Configuration Tests -name '*.php' -print0 \ + | xargs -0 -n 1 -P 4 "${PHP_BIN}" -l diff --git a/Build/Scripts/lint-typos.sh b/Build/Scripts/lint-typos.sh new file mode 100755 index 0000000..5a9c881 --- /dev/null +++ b/Build/Scripts/lint-typos.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# +# Checks the spelling of all files of the extension with typos, using +# Build/typos.toml. Files ignored by .gitignore are skipped. +# +# typos is not installed via composer. It is provided by shell.nix, in CI it +# is installed via pipx. +# +# Usage: +# Build/Scripts/lint-typos.sh report typos +# Build/Scripts/lint-typos.sh --fix fix unambiguous typos in place + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +if ! command -v typos > /dev/null; then + echo "Missing typos, please install it first, e.g. \"pipx install typos\"." >&2 + exit 1 +fi + +if [ "${1:-}" = "--fix" ]; then + typos --config Build/typos.toml --write-changes +else + typos --config Build/typos.toml +fi diff --git a/Build/Scripts/lint-typoscript.sh b/Build/Scripts/lint-typoscript.sh new file mode 100755 index 0000000..d564292 --- /dev/null +++ b/Build/Scripts/lint-typoscript.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# +# Lints all TypoScript and TSconfig files of the extension with +# helmich/typo3-typoscript-lint, using Build/typoscriptlint.yaml. +# Warnings fail the lint as well. +# +# Usage: +# Build/Scripts/lint-typoscript.sh + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary typoscript-lint + +paths=() +for path in Configuration Tests ext_typoscript_setup.typoscript; do + if [ -e "${path}" ]; then + paths+=("${path}") + fi +done + +runPhp "${BIN_DIR}/typoscript-lint" --config Build/typoscriptlint.yaml --fail-on-warnings "${paths[@]}" diff --git a/Build/Scripts/lint-xml.sh b/Build/Scripts/lint-xml.sh new file mode 100755 index 0000000..06b4e08 --- /dev/null +++ b/Build/Scripts/lint-xml.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# +# Validates the xml files of the extension against their schemas: +# - XLIFF files in Resources/Private/Language against XLIFF 1.2 strict +# (Build/xliff-core-1.2-strict.xsd, imports Build/xml.xsd) +# - Build/phpunit.xml.dist against the schema of the installed PHPUnit +# +# xmllint is not installed via composer. It is provided by shell.nix, in CI it +# is installed via apt (libxml2-utils). +# +# Usage: +# Build/Scripts/lint-xml.sh + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +if ! command -v xmllint > /dev/null; then + echo "Missing xmllint, please install it first, e.g. the package libxml2-utils." >&2 + exit 1 +fi +requireBinary phpunit + +if [ -d Resources/Private/Language ]; then + find Resources/Private/Language -name '*.xlf' -print0 \ + | xargs -0 -r xmllint --schema Build/xliff-core-1.2-strict.xsd --noout +fi + +xmllint --schema .Build/vendor/phpunit/phpunit/phpunit.xsd --noout Build/phpunit.xml.dist diff --git a/Build/Scripts/lint-yaml.sh b/Build/Scripts/lint-yaml.sh new file mode 100755 index 0000000..1eaf223 --- /dev/null +++ b/Build/Scripts/lint-yaml.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# +# Lints all yaml files of the extension with yamllint, using +# Build/yamllint.yaml. Files ignored by .gitignore are skipped. +# +# yamllint is not installed via composer. It is provided by shell.nix, in CI it +# is installed via pipx. +# +# Usage: +# Build/Scripts/lint-yaml.sh + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +if ! command -v yamllint > /dev/null; then + echo "Missing yamllint, please install it first, e.g. \"pipx install yamllint\"." >&2 + exit 1 +fi + +yamllint --config-file Build/yamllint.yaml . diff --git a/Build/Scripts/phpstan.sh b/Build/Scripts/phpstan.sh new file mode 100755 index 0000000..6f06604 --- /dev/null +++ b/Build/Scripts/phpstan.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# +# Runs the static code analysis with phpstan. +# +# Usage: +# Build/Scripts/phpstan.sh [additional phpstan arguments] + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary phpstan + +runPhp "${BIN_DIR}/phpstan" analyse -c Build/phpstan.neon "$@" diff --git a/Build/Scripts/phpunit.sh b/Build/Scripts/phpunit.sh new file mode 100755 index 0000000..2636b97 --- /dev/null +++ b/Build/Scripts/phpunit.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# +# Runs the phpunit tests. +# +# Usage: +# Build/Scripts/phpunit.sh [testsuite] [additional phpunit arguments] +# +# Without a testsuite every suite defined in Build/phpunit.xml.dist is run, +# each one in its own phpunit process. They cannot share a process, the +# functional bootstrap leaks global state into the unit tests. The first +# argument is taken as the testsuite name unless it starts with a dash. +# +# Environment variables used as overrides: +# typo3DatabaseDriver database driver to test against, defaults to "pdo_sqlite" + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary phpunit + +export typo3DatabaseDriver="${typo3DatabaseDriver:-pdo_sqlite}" + +runSuite() { + local suite="$1" + shift + + runPhp "${BIN_DIR}/phpunit" \ + -c Build/phpunit.xml.dist \ + --testsuite "${suite}" \ + --display-warnings \ + --display-deprecations \ + --display-errors \ + --display-notices \ + "$@" +} + +if [ $# -gt 0 ] && [ -n "$1" ] && [ "${1:0:1}" != "-" ]; then + TESTSUITE="$1" + shift + runSuite "${TESTSUITE}" "$@" + exit $? +fi + +mapfile -t SUITES < <(runPhp "${BIN_DIR}/phpunit" -c Build/phpunit.xml.dist --list-suites \ + | sed -n 's/^ - \(.*\) ([0-9]\{1,\} tests\{0,1\})$/\1/p') + +if [ ${#SUITES[@]} -eq 0 ]; then + echo "No testsuites found in Build/phpunit.xml.dist." >&2 + exit 1 +fi + +STATUS=0 +for suite in "${SUITES[@]}"; do + echo "Running testsuite \"${suite}\" ..." + runSuite "${suite}" "$@" || STATUS=$? +done + +exit "${STATUS}" diff --git a/Build/phplint.yaml b/Build/phplint.yaml deleted file mode 100644 index c077586..0000000 --- a/Build/phplint.yaml +++ /dev/null @@ -1,7 +0,0 @@ -path: ./../ -jobs: 10 -cache: .phplint.cache -extensions: - - php -exclude: - - .build \ No newline at end of file diff --git a/Build/phpstan.neon b/Build/phpstan.neon index ee2d0f1..ebdfc36 100644 --- a/Build/phpstan.neon +++ b/Build/phpstan.neon @@ -1,7 +1,7 @@ parameters: - level: 0 + level: 4 paths: - ../Classes - ../Configuration - - ../ext_emconf.php - - ../ext_localconf.php \ No newline at end of file + - ../Tests + - ../ext_localconf.php diff --git a/Build/phpunit.xml.dist b/Build/phpunit.xml.dist new file mode 100644 index 0000000..37fceac --- /dev/null +++ b/Build/phpunit.xml.dist @@ -0,0 +1,33 @@ + + + + + + ../Tests/Functional/ + + + ../Tests/Unit/ + + + + + ../Classes/ + + + diff --git a/Build/typos.toml b/Build/typos.toml new file mode 100644 index 0000000..211d5ba --- /dev/null +++ b/Build/typos.toml @@ -0,0 +1,6 @@ +[files] +extend-exclude = [ + # Vendored schemas, kept as published. + "Build/xliff-core-1.2-strict.xsd", + "Build/xml.xsd", +] diff --git a/Build/typoscriptlint.yaml b/Build/typoscriptlint.yaml index 12405ea..6b7e404 100644 --- a/Build/typoscriptlint.yaml +++ b/Build/typoscriptlint.yaml @@ -3,17 +3,18 @@ sniffs: parameters: useSpaces: true indentPerLevel: 4 - indentConditions: false + indentConditions: true - class: DeadCode - class: OperatorWhitespace + # Values like validator names or paths are repeated on purpose. Moving them + # to constants would add them to the public configuration of the extension. - class: RepeatingRValue - parameters: - allowedRightValues: - - "TYPO3\\CMS\\Frontend\\DataProcessing\\DatabaseQueryProcessor" + disabled: true - class: DuplicateAssignment - class: EmptySection - class: NestingConsistency parameters: commonPathPrefixThreshold: 1 filePatterns: - - "*.typoscript" \ No newline at end of file + - "*.typoscript" + - "*.tsconfig" diff --git a/Build/xliff-core-1.2-strict.xsd b/Build/xliff-core-1.2-strict.xsd new file mode 100644 index 0000000..b9b2392 --- /dev/null +++ b/Build/xliff-core-1.2-strict.xsd @@ -0,0 +1,2223 @@ + + + + + + + + + + + + + + + Values for the attribute 'context-type'. + + + + + Indicates a database content. + + + + + Indicates the content of an element within an XML document. + + + + + Indicates the name of an element within an XML document. + + + + + Indicates the line number from the sourcefile (see context-type="sourcefile") where the <source> is found. + + + + + Indicates a the number of parameters contained within the <source>. + + + + + Indicates notes pertaining to the parameters in the <source>. + + + + + Indicates the content of a record within a database. + + + + + Indicates the name of a record within a database. + + + + + Indicates the original source file in the case that multiple files are merged to form the original file from which the XLIFF file is created. This differs from the original <file> attribute in that this sourcefile is one of many that make up that file. + + + + + + + Values for the attribute 'count-type'. + + + + + Indicates the count units are items that are used X times in a certain context; example: this is a reusable text unit which is used 42 times in other texts. + + + + + Indicates the count units are translation units existing already in the same document. + + + + + Indicates a total count. + + + + + + + Values for the attribute 'ctype' when used other elements than <ph> or <x>. + + + + + Indicates a run of bolded text. + + + + + Indicates a run of text in italics. + + + + + Indicates a run of underlined text. + + + + + Indicates a run of hyper-text. + + + + + + + Values for the attribute 'ctype' when used with <ph> or <x>. + + + + + Indicates a inline image. + + + + + Indicates a page break. + + + + + Indicates a line break. + + + + + + + + + + + + Values for the attribute 'datatype'. + + + + + Indicates Active Server Page data. + + + + + Indicates C source file data. + + + + + Indicates Channel Definition Format (CDF) data. + + + + + Indicates ColdFusion data. + + + + + Indicates C++ source file data. + + + + + Indicates C-Sharp data. + + + + + Indicates strings from C, ASM, and driver files data. + + + + + Indicates comma-separated values data. + + + + + Indicates database data. + + + + + Indicates portions of document that follows data and contains metadata. + + + + + Indicates portions of document that precedes data and contains metadata. + + + + + Indicates data from standard UI file operations dialogs (e.g., Open, Save, Save As, Export, Import). + + + + + Indicates standard user input screen data. + + + + + Indicates HyperText Markup Language (HTML) data - document instance. + + + + + Indicates content within an HTML document’s <body> element. + + + + + Indicates Windows INI file data. + + + + + Indicates Interleaf data. + + + + + Indicates Java source file data (extension '.java'). + + + + + Indicates Java property resource bundle data. + + + + + Indicates Java list resource bundle data. + + + + + Indicates JavaScript source file data. + + + + + Indicates JScript source file data. + + + + + Indicates information relating to formatting. + + + + + Indicates LISP source file data. + + + + + Indicates information relating to margin formats. + + + + + Indicates a file containing menu. + + + + + Indicates numerically identified string table. + + + + + Indicates Maker Interchange Format (MIF) data. + + + + + Indicates that the datatype attribute value is a MIME Type value and is defined in the mime-type attribute. + + + + + Indicates GNU Machine Object data. + + + + + Indicates Message Librarian strings created by Novell's Message Librarian Tool. + + + + + Indicates information to be displayed at the bottom of each page of a document. + + + + + Indicates information to be displayed at the top of each page of a document. + + + + + Indicates a list of property values (e.g., settings within INI files or preferences dialog). + + + + + Indicates Pascal source file data. + + + + + Indicates Hypertext Preprocessor data. + + + + + Indicates plain text file (no formatting other than, possibly, wrapping). + + + + + Indicates GNU Portable Object file. + + + + + Indicates dynamically generated user defined document. e.g. Oracle Report, Crystal Report, etc. + + + + + Indicates Windows .NET binary resources. + + + + + Indicates Windows .NET Resources. + + + + + Indicates Rich Text Format (RTF) data. + + + + + Indicates Standard Generalized Markup Language (SGML) data - document instance. + + + + + Indicates Standard Generalized Markup Language (SGML) data - Document Type Definition (DTD). + + + + + Indicates Scalable Vector Graphic (SVG) data. + + + + + Indicates VisualBasic Script source file. + + + + + Indicates warning message. + + + + + Indicates Windows (Win32) resources (i.e. resources extracted from an RC script, a message file, or a compiled file). + + + + + Indicates Extensible HyperText Markup Language (XHTML) data - document instance. + + + + + Indicates Extensible Markup Language (XML) data - document instance. + + + + + Indicates Extensible Markup Language (XML) data - Document Type Definition (DTD). + + + + + Indicates Extensible Stylesheet Language (XSL) data. + + + + + Indicates XUL elements. + + + + + + + Values for the attribute 'mtype'. + + + + + Indicates the marked text is an abbreviation. + + + + + ISO-12620 2.1.8: A term resulting from the omission of any part of the full term while designating the same concept. + + + + + ISO-12620 2.1.8.1: An abbreviated form of a simple term resulting from the omission of some of its letters (e.g. 'adj.' for 'adjective'). + + + + + ISO-12620 2.1.8.4: An abbreviated form of a term made up of letters from the full form of a multiword term strung together into a sequence pronounced only syllabically (e.g. 'radar' for 'radio detecting and ranging'). + + + + + ISO-12620: A proper-name term, such as the name of an agency or other proper entity. + + + + + ISO-12620 2.1.18.1: A recurrent word combination characterized by cohesion in that the components of the collocation must co-occur within an utterance or series of utterances, even though they do not necessarily have to maintain immediate proximity to one another. + + + + + ISO-12620 2.1.5: A synonym for an international scientific term that is used in general discourse in a given language. + + + + + Indicates the marked text is a date and/or time. + + + + + ISO-12620 2.1.15: An expression used to represent a concept based on a statement that two mathematical expressions are, for instance, equal as identified by the equal sign (=), or assigned to one another by a similar sign. + + + + + ISO-12620 2.1.7: The complete representation of a term for which there is an abbreviated form. + + + + + ISO-12620 2.1.14: Figures, symbols or the like used to express a concept briefly, such as a mathematical or chemical formula. + + + + + ISO-12620 2.1.1: The concept designation that has been chosen to head a terminological record. + + + + + ISO-12620 2.1.8.3: An abbreviated form of a term consisting of some of the initial letters of the words making up a multiword term or the term elements making up a compound term when these letters are pronounced individually (e.g. 'BSE' for 'bovine spongiform encephalopathy'). + + + + + ISO-12620 2.1.4: A term that is part of an international scientific nomenclature as adopted by an appropriate scientific body. + + + + + ISO-12620 2.1.6: A term that has the same or nearly identical orthographic or phonemic form in many languages. + + + + + ISO-12620 2.1.16: An expression used to represent a concept based on mathematical or logical relations, such as statements of inequality, set relationships, Boolean operations, and the like. + + + + + ISO-12620 2.1.17: A unit to track object. + + + + + Indicates the marked text is a name. + + + + + ISO-12620 2.1.3: A term that represents the same or a very similar concept as another term in the same language, but for which interchangeability is limited to some contexts and inapplicable in others. + + + + + ISO-12620 2.1.17.2: A unique alphanumeric designation assigned to an object in a manufacturing system. + + + + + Indicates the marked text is a phrase. + + + + + ISO-12620 2.1.18: Any group of two or more words that form a unit, the meaning of which frequently cannot be deduced based on the combined sense of the words making up the phrase. + + + + + Indicates the marked text should not be translated. + + + + + ISO-12620 2.1.12: A form of a term resulting from an operation whereby non-Latin writing systems are converted to the Latin alphabet. + + + + + Indicates that the marked text represents a segment. + + + + + ISO-12620 2.1.18.2: A fixed, lexicalized phrase. + + + + + ISO-12620 2.1.8.2: A variant of a multiword term that includes fewer words than the full form of the term (e.g. 'Group of Twenty-four' for 'Intergovernmental Group of Twenty-four on International Monetary Affairs'). + + + + + ISO-12620 2.1.17.1: Stock keeping unit, an inventory item identified by a unique alphanumeric designation assigned to an object in an inventory control system. + + + + + ISO-12620 2.1.19: A fixed chunk of recurring text. + + + + + ISO-12620 2.1.13: A designation of a concept by letters, numerals, pictograms or any combination thereof. + + + + + ISO-12620 2.1.2: Any term that represents the same or a very similar concept as the main entry term in a term entry. + + + + + ISO-12620 2.1.18.3: Phraseological unit in a language that expresses the same semantic content as another phrase in that same language. + + + + + Indicates the marked text is a term. + + + + + ISO-12620 2.1.11: A form of a term resulting from an operation whereby the characters of one writing system are represented by characters from another writing system, taking into account the pronunciation of the characters converted. + + + + + ISO-12620 2.1.10: A form of a term resulting from an operation whereby the characters of an alphabetic writing system are represented by characters from another alphabetic writing system. + + + + + ISO-12620 2.1.8.5: An abbreviated form of a term resulting from the omission of one or more term elements or syllables (e.g. 'flu' for 'influenza'). + + + + + ISO-12620 2.1.9: One of the alternate forms of a term. + + + + + + + Values for the attribute 'restype'. + + + + + Indicates a Windows RC AUTO3STATE control. + + + + + Indicates a Windows RC AUTOCHECKBOX control. + + + + + Indicates a Windows RC AUTORADIOBUTTON control. + + + + + Indicates a Windows RC BEDIT control. + + + + + Indicates a bitmap, for example a BITMAP resource in Windows. + + + + + Indicates a button object, for example a BUTTON control Windows. + + + + + Indicates a caption, such as the caption of a dialog box. + + + + + Indicates the cell in a table, for example the content of the <td> element in HTML. + + + + + Indicates check box object, for example a CHECKBOX control in Windows. + + + + + Indicates a menu item with an associated checkbox. + + + + + Indicates a list box, but with a check-box for each item. + + + + + Indicates a color selection dialog. + + + + + Indicates a combination of edit box and listbox object, for example a COMBOBOX control in Windows. + + + + + Indicates an initialization entry of an extended combobox DLGINIT resource block. (code 0x1234). + + + + + Indicates an initialization entry of a combobox DLGINIT resource block (code 0x0403). + + + + + Indicates a UI base class element that cannot be represented by any other element. + + + + + Indicates a context menu. + + + + + Indicates a Windows RC CTEXT control. + + + + + Indicates a cursor, for example a CURSOR resource in Windows. + + + + + Indicates a date/time picker. + + + + + Indicates a Windows RC DEFPUSHBUTTON control. + + + + + Indicates a dialog box. + + + + + Indicates a Windows RC DLGINIT resource block. + + + + + Indicates an edit box object, for example an EDIT control in Windows. + + + + + Indicates a filename. + + + + + Indicates a file dialog. + + + + + Indicates a footnote. + + + + + Indicates a font name. + + + + + Indicates a footer. + + + + + Indicates a frame object. + + + + + Indicates a XUL grid element. + + + + + Indicates a groupbox object, for example a GROUPBOX control in Windows. + + + + + Indicates a header item. + + + + + Indicates a heading, such has the content of <h1>, <h2>, etc. in HTML. + + + + + Indicates a Windows RC HEDIT control. + + + + + Indicates a horizontal scrollbar. + + + + + Indicates an icon, for example an ICON resource in Windows. + + + + + Indicates a Windows RC IEDIT control. + + + + + Indicates keyword list, such as the content of the Keywords meta-data in HTML, or a K footnote in WinHelp RTF. + + + + + Indicates a label object. + + + + + Indicates a label that is also a HTML link (not necessarily a URL). + + + + + Indicates a list (a group of list-items, for example an <ol> or <ul> element in HTML). + + + + + Indicates a listbox object, for example an LISTBOX control in Windows. + + + + + Indicates an list item (an entry in a list). + + + + + Indicates a Windows RC LTEXT control. + + + + + Indicates a menu (a group of menu-items). + + + + + Indicates a toolbar containing one or more tope level menus. + + + + + Indicates a menu item (an entry in a menu). + + + + + Indicates a XUL menuseparator element. + + + + + Indicates a message, for example an entry in a MESSAGETABLE resource in Windows. + + + + + Indicates a calendar control. + + + + + Indicates an edit box beside a spin control. + + + + + Indicates a catch all for rectangular areas. + + + + + Indicates a standalone menu not necessarily associated with a menubar. + + + + + Indicates a pushbox object, for example a PUSHBOX control in Windows. + + + + + Indicates a Windows RC PUSHBUTTON control. + + + + + Indicates a radio button object. + + + + + Indicates a menuitem with associated radio button. + + + + + Indicates raw data resources for an application. + + + + + Indicates a row in a table. + + + + + Indicates a Windows RC RTEXT control. + + + + + Indicates a user navigable container used to show a portion of a document. + + + + + Indicates a generic divider object (e.g. menu group separator). + + + + + Windows accelerators, shortcuts in resource or property files. + + + + + Indicates a UI control to indicate process activity but not progress. + + + + + Indicates a splitter bar. + + + + + Indicates a Windows RC STATE3 control. + + + + + Indicates a window for providing feedback to the users, like 'read-only', etc. + + + + + Indicates a string, for example an entry in a STRINGTABLE resource in Windows. + + + + + Indicates a layers of controls with a tab to select layers. + + + + + Indicates a display and edits regular two-dimensional tables of cells. + + + + + Indicates a XUL textbox element. + + + + + Indicates a UI button that can be toggled to on or off state. + + + + + Indicates an array of controls, usually buttons. + + + + + Indicates a pop up tool tip text. + + + + + Indicates a bar with a pointer indicating a position within a certain range. + + + + + Indicates a control that displays a set of hierarchical data. + + + + + Indicates a URI (URN or URL). + + + + + Indicates a Windows RC USERBUTTON control. + + + + + Indicates a user-defined control like CONTROL control in Windows. + + + + + Indicates the text of a variable. + + + + + Indicates version information about a resource like VERSIONINFO in Windows. + + + + + Indicates a vertical scrollbar. + + + + + Indicates a graphical window. + + + + + + + Values for the attribute 'size-unit'. + + + + + Indicates a size in 8-bit bytes. + + + + + Indicates a size in Unicode characters. + + + + + Indicates a size in columns. Used for HTML text area. + + + + + Indicates a size in centimeters. + + + + + Indicates a size in dialog units, as defined in Windows resources. + + + + + Indicates a size in 'font-size' units (as defined in CSS). + + + + + Indicates a size in 'x-height' units (as defined in CSS). + + + + + Indicates a size in glyphs. A glyph is considered to be one or more combined Unicode characters that represent a single displayable text character. Sometimes referred to as a 'grapheme cluster' + + + + + Indicates a size in inches. + + + + + Indicates a size in millimeters. + + + + + Indicates a size in percentage. + + + + + Indicates a size in pixels. + + + + + Indicates a size in point. + + + + + Indicates a size in rows. Used for HTML text area. + + + + + + + Values for the attribute 'state'. + + + + + Indicates the terminating state. + + + + + Indicates only non-textual information needs adaptation. + + + + + Indicates both text and non-textual information needs adaptation. + + + + + Indicates only non-textual information needs review. + + + + + Indicates both text and non-textual information needs review. + + + + + Indicates that only the text of the item needs to be reviewed. + + + + + Indicates that the item needs to be translated. + + + + + Indicates that the item is new. For example, translation units that were not in a previous version of the document. + + + + + Indicates that changes are reviewed and approved. + + + + + Indicates that the item has been translated. + + + + + + + Values for the attribute 'state-qualifier'. + + + + + Indicates an exact match. An exact match occurs when a source text of a segment is exactly the same as the source text of a segment that was translated previously. + + + + + Indicates a fuzzy match. A fuzzy match occurs when a source text of a segment is very similar to the source text of a segment that was translated previously (e.g. when the difference is casing, a few changed words, white-space discripancy, etc.). + + + + + Indicates a match based on matching IDs (in addition to matching text). + + + + + Indicates a translation derived from a glossary. + + + + + Indicates a translation derived from existing translation. + + + + + Indicates a translation derived from machine translation. + + + + + Indicates a translation derived from a translation repository. + + + + + Indicates a translation derived from a translation memory. + + + + + Indicates the translation is suggested by machine translation. + + + + + Indicates that the item has been rejected because of incorrect grammar. + + + + + Indicates that the item has been rejected because it is incorrect. + + + + + Indicates that the item has been rejected because it is too long or too short. + + + + + Indicates that the item has been rejected because of incorrect spelling. + + + + + Indicates the translation is suggested by translation memory. + + + + + + + Values for the attribute 'unit'. + + + + + Refers to words. + + + + + Refers to pages. + + + + + Refers to <trans-unit> elements. + + + + + Refers to <bin-unit> elements. + + + + + Refers to glyphs. + + + + + Refers to <trans-unit> and/or <bin-unit> elements. + + + + + Refers to the occurrences of instances defined by the count-type value. + + + + + Refers to characters. + + + + + Refers to lines. + + + + + Refers to sentences. + + + + + Refers to paragraphs. + + + + + Refers to segments. + + + + + Refers to placeables (inline elements). + + + + + + + Values for the attribute 'priority'. + + + + + Highest priority. + + + + + High priority. + + + + + High priority, but not as important as 2. + + + + + High priority, but not as important as 3. + + + + + Medium priority, but more important than 6. + + + + + Medium priority, but less important than 5. + + + + + Low priority, but more important than 8. + + + + + Low priority, but more important than 9. + + + + + Low priority. + + + + + Lowest priority. + + + + + + + + + This value indicates that all properties can be reformatted. This value must be used alone. + + + + + This value indicates that no properties should be reformatted. This value must be used alone. + + + + + + + + + + + + + This value indicates that all information in the coord attribute can be modified. + + + + + This value indicates that the x information in the coord attribute can be modified. + + + + + This value indicates that the y information in the coord attribute can be modified. + + + + + This value indicates that the cx information in the coord attribute can be modified. + + + + + This value indicates that the cy information in the coord attribute can be modified. + + + + + This value indicates that all the information in the font attribute can be modified. + + + + + This value indicates that the name information in the font attribute can be modified. + + + + + This value indicates that the size information in the font attribute can be modified. + + + + + This value indicates that the weight information in the font attribute can be modified. + + + + + This value indicates that the information in the css-style attribute can be modified. + + + + + This value indicates that the information in the style attribute can be modified. + + + + + This value indicates that the information in the exstyle attribute can be modified. + + + + + + + + + + + + + Indicates that the context is informational in nature, specifying for example, how a term should be translated. Thus, should be displayed to anyone editing the XLIFF document. + + + + + Indicates that the context-group is used to specify where the term was found in the translatable source. Thus, it is not displayed. + + + + + Indicates that the context information should be used during translation memory lookups. Thus, it is not displayed. + + + + + + + + + Represents a translation proposal from a translation memory or other resource. + + + + + Represents a previous version of the target element. + + + + + Represents a rejected version of the target element. + + + + + Represents a translation to be used for reference purposes only, for example from a related product or a different language. + + + + + Represents a proposed translation that was used for the translation of the trans-unit, possibly modified. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Values for the attribute 'coord'. + + + + + + + + Version values: 1.0 and 1.1 are allowed for backward compatibility. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Build/xml.xsd b/Build/xml.xsd new file mode 100644 index 0000000..aea7d0d --- /dev/null +++ b/Build/xml.xsd @@ -0,0 +1,287 @@ + + + + + + +
+

About the XML namespace

+ +
+

+ This schema document describes the XML namespace, in a form + suitable for import by other schema documents. +

+

+ See + http://www.w3.org/XML/1998/namespace.html and + + http://www.w3.org/TR/REC-xml for information + about this namespace. +

+

+ Note that local names in this namespace are intended to be + defined only by the World Wide Web Consortium or its subgroups. + The names currently defined in this namespace are listed below. + They should not be used with conflicting semantics by any Working + Group, specification, or document instance. +

+

+ See further below in this document for more information about how to refer to this schema document from your own + XSD schema documents and about the + namespace-versioning policy governing this schema document. +

+
+
+
+
+ + + + +
+ +

lang (as an attribute name)

+

+ denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification.

+ +
+
+

Notes

+

+ Attempting to install the relevant ISO 2- and 3-letter + codes as the enumerated possible values is probably never + going to be a realistic possibility. +

+

+ See BCP 47 at + http://www.rfc-editor.org/rfc/bcp/bcp47.txt + and the IANA language subtag registry at + + http://www.iana.org/assignments/language-subtag-registry + for further information. +

+

+ The union allows for the 'un-declaration' of xml:lang with + the empty string. +

+
+
+
+ + + + + + + + + +
+ + + + +
+ +

space (as an attribute name)

+

+ denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification.

+ +
+
+
+ + + + + + +
+ + + +
+ +

base (as an attribute name)

+

+ denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification.

+ +

+ See http://www.w3.org/TR/xmlbase/ + for information about this attribute. +

+
+
+
+
+ + + + +
+ +

id (as an attribute name)

+

+ denotes an attribute whose value + should be interpreted as if declared to be of type ID. + This name is reserved by virtue of its definition in the + xml:id specification.

+ +

+ See http://www.w3.org/TR/xml-id/ + for information about this attribute. +

+
+
+
+
+ + + + + + + + + + +
+ +

Father (in any context at all)

+ +
+

+ denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: +

+
+

+ In appreciation for his vision, leadership and + dedication the W3C XML Plenary on this 10th day of + February, 2000, reserves for Jon Bosak in perpetuity + the XML name "xml:Father". +

+
+
+
+
+
+ + + +
+

About this schema document

+ +
+

+ This schema defines attributes and an attribute group suitable + for use by schemas wishing to allow xml:base, + xml:lang, xml:space or + xml:id attributes on elements they define. +

+

+ To enable this, such a schema must import this schema for + the XML namespace, e.g. as follows: +

+
+          <schema . . .>
+           . . .
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2001/xml.xsd"/>
+     
+

+ or +

+
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
+     
+

+ Subsequently, qualified reference to any of the attributes or the + group defined below will have the desired effect, e.g. +

+
+          <type . . .>
+           . . .
+           <attributeGroup ref="xml:specialAttrs"/>
+     
+

+ will define a type which will schema-validate an instance element + with any of those attributes. +

+
+
+
+
+ + + +
+

Versioning policy for this schema document

+
+

+ In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + + http://www.w3.org/2009/01/xml.xsd. +

+

+ At the date of issue it can also be found at + + http://www.w3.org/2001/xml.xsd. +

+

+ The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML + Schema itself, or with the XML namespace itself. In other words, + if the XML Schema or XML namespaces change, the version of this + document at + http://www.w3.org/2001/xml.xsd + + will change accordingly; the version at + + http://www.w3.org/2009/01/xml.xsd + + will not change. +

+

+ Previous dated (and unchanging) versions of this schema + document are at: +

+ +
+
+
+
+ +
+ diff --git a/Build/yamllint.yaml b/Build/yamllint.yaml index 5b0f71b..b8875c1 100644 --- a/Build/yamllint.yaml +++ b/Build/yamllint.yaml @@ -1,5 +1,7 @@ extends: default +ignore-from-file: .gitignore + rules: line-length: disable document-start: disable @@ -20,4 +22,6 @@ rules: forbid-in-block-mappings: true forbid-in-flow-mappings: true indentation: - spaces: 2 \ No newline at end of file + spaces: 2 + truthy: + check-keys: false diff --git a/Classes/Api/ApiException.php b/Classes/Api/ApiException.php new file mode 100644 index 0000000..eaa8c86 --- /dev/null +++ b/Classes/Api/ApiException.php @@ -0,0 +1,82 @@ +statusCode; + } + + /** + * The error name, e.g. UNPROCESSABLE_ENTITY. + */ + public function getName(): string + { + return $this->name; + } + + /** + * The issue of the first error detail, e.g. ORDER_ALREADY_CAPTURED. + */ + public function getIssue(): string + { + return $this->issue; + } + + /** + * The id PayPal support needs to find the request. + */ + public function getDebugId(): string + { + return $this->debugId; + } +} diff --git a/Classes/Api/PayPalClient.php b/Classes/Api/PayPalClient.php new file mode 100644 index 0000000..1c291a0 --- /dev/null +++ b/Classes/Api/PayPalClient.php @@ -0,0 +1,262 @@ +getCredential('clientId'); + } + + /** + * Uses the sandbox unless it is disabled explicitly. + */ + public function isSandbox(): bool + { + $credentials = $this->getCredentials(); + + if (!array_key_exists('sandbox', $credentials)) { + return true; + } + + return filter_var($credentials['sandbox'], FILTER_VALIDATE_BOOL); + } + + public function getSdkUrl(): string + { + return $this->isSandbox() ? self::SDK_SANDBOX : self::SDK_LIVE; + } + + /** + * @throws ApiException + */ + public function createOrder(array $order): array + { + return $this->send( + 'POST', + '/v2/checkout/orders', + $this->encode($order), + [ + 'PayPal-Request-Id' => 'create-' . bin2hex(random_bytes(16)), + 'Prefer' => 'return=representation', + ] + ); + } + + /** + * Captures the approved order. The request id depends on the order only, + * so PayPal treats a repeated capture of the same order as one request. + * + * @throws ApiException + */ + public function captureOrder(string $orderId): array + { + return $this->send( + 'POST', + '/v2/checkout/orders/' . rawurlencode($orderId) . '/capture', + $this->encode(new stdClass()), + [ + 'PayPal-Request-Id' => 'capture-' . $orderId, + 'Prefer' => 'return=representation', + ] + ); + } + + /** + * @throws ApiException + */ + public function getOrder(string $orderId): array + { + return $this->send('GET', '/v2/checkout/orders/' . rawurlencode($orderId)); + } + + /** + * Lets PayPal verify the signature of a received webhook. + * + * The received body is passed on unchanged, decoding and encoding it again + * could change it and let the verification fail. + * + * @throws ApiException + */ + public function verifyWebhookSignature(ServerRequestInterface $request, string $body): bool + { + $webhookId = $this->getCredential('webhookId'); + if ($webhookId === '') { + return false; + } + + $verification = [ + 'auth_algo' => $request->getHeaderLine('PayPal-Auth-Algo'), + 'cert_url' => $request->getHeaderLine('PayPal-Cert-Url'), + 'transmission_id' => $request->getHeaderLine('PayPal-Transmission-Id'), + 'transmission_sig' => $request->getHeaderLine('PayPal-Transmission-Sig'), + 'transmission_time' => $request->getHeaderLine('PayPal-Transmission-Time'), + 'webhook_id' => $webhookId, + ]; + if (in_array('', $verification, true)) { + return false; + } + + try { + json_decode($body, false, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return false; + } + + $payload = substr($this->encode($verification), 0, -1) . ',"webhook_event":' . $body . '}'; + + $response = $this->send('POST', '/v1/notifications/verify-webhook-signature', $payload); + + return ($response['verification_status'] ?? '') === 'SUCCESS'; + } + + /** + * @throws ApiException + */ + private function send(string $method, string $path, ?string $body = null, array $headers = []): array + { + $headers['Authorization'] = 'Bearer ' . $this->getAccessToken(); + $headers['Accept'] = 'application/json'; + + $options = [ + 'headers' => $headers, + 'http_errors' => false, + 'timeout' => self::TIMEOUT, + ]; + if ($body !== null) { + $options['headers']['Content-Type'] = 'application/json'; + $options['body'] = $body; + } + + return $this->request($method, $path, $options); + } + + /** + * @throws ApiException + */ + private function getAccessToken(): string + { + if ($this->accessToken !== null) { + return $this->accessToken; + } + + $clientId = $this->getCredential('clientId'); + $clientSecret = $this->getCredential('clientSecret'); + if ($clientId === '' || $clientSecret === '') { + throw new ApiException('The credentials of PayPal (clientId, clientSecret) are not configured.', 1795600002); + } + + $response = $this->request('POST', '/v1/oauth2/token', [ + 'auth' => [$clientId, $clientSecret], + 'form_params' => [ + 'grant_type' => 'client_credentials', + ], + 'headers' => [ + 'Accept' => 'application/json', + ], + 'http_errors' => false, + 'timeout' => self::TIMEOUT, + ]); + + $accessToken = (string)($response['access_token'] ?? ''); + if ($accessToken === '') { + throw new ApiException('PayPal did not return an access token.', 1795600003); + } + + return $this->accessToken = $accessToken; + } + + /** + * @throws ApiException + */ + private function request(string $method, string $path, array $options): array + { + try { + $response = $this->requestFactory->request($this->getApiUrl() . $path, $method, $options); + } catch (GuzzleException $exception) { + throw new ApiException( + 'PayPal could not be reached: ' . $exception->getMessage(), + 1795600004, + previous: $exception + ); + } + + $data = json_decode((string)$response->getBody(), true); + if (!is_array($data)) { + $data = []; + } + + if ($response->getStatusCode() >= 400) { + throw ApiException::fromResponse($response->getStatusCode(), $data); + } + + return $data; + } + + private function encode(array|stdClass $data): string + { + return json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } + + private function getApiUrl(): string + { + return $this->isSandbox() ? self::API_SANDBOX : self::API_LIVE; + } + + private function getCredential(string $name): string + { + $value = $this->getCredentials()[$name] ?? ''; + + return is_scalar($value) ? trim((string)$value) : ''; + } + + private function getCredentials(): array + { + return $this->credentials ??= $this->credentialLoaderRegistry->getCredentials(); + } +} diff --git a/Classes/Checkout/Cart/CartRecordFinder.php b/Classes/Checkout/Cart/CartRecordFinder.php new file mode 100644 index 0000000..0bab0ac --- /dev/null +++ b/Classes/Checkout/Cart/CartRecordFinder.php @@ -0,0 +1,105 @@ +findByHash('sHash', $hash); + } + + /** + * The failure hash identifies the order for the cancellation only. + */ + public function findByFHash(string $hash): ?Cart + { + return $this->findByHash('fHash', $hash); + } + + private function findByHash(string $property, string $hash): ?Cart + { + if ($hash === '') { + return null; + } + + $query = $this->cartRepository->createQuery(); + $query->getQuerySettings()->setRespectStoragePage(false); + $query->matching($query->equals($property, $hash)); + + $cart = $query->execute()->getFirst(); + + return $cart instanceof Cart ? $cart : null; + } + + public function findByPayPalOrderId(string $payPalOrderId): ?Cart + { + if ($payPalOrderId === '') { + return null; + } + + $query = $this->paymentRepository->createQuery(); + $query->getQuerySettings()->setRespectStoragePage(false); + $query->matching( + $query->logicalAnd( + $query->in('provider', PaymentProvider::values()), + $query->equals('transactions.txnId', $payPalOrderId) + ) + ); + + $payment = $query->execute()->getFirst(); + if (!$payment instanceof Payment) { + return null; + } + + $orderItem = $payment->getItem(); + if (!$orderItem instanceof Item) { + return null; + } + + return $this->findByOrderItem($orderItem); + } + + private function findByOrderItem(Item $orderItem): ?Cart + { + $query = $this->cartRepository->createQuery(); + $query->getQuerySettings()->setRespectStoragePage(false); + $query->matching($query->equals('orderItem', $orderItem)); + + $cart = $query->execute()->getFirst(); + + return $cart instanceof Cart ? $cart : null; + } +} diff --git a/Classes/Checkout/Cart/CartRestorer.php b/Classes/Checkout/Cart/CartRestorer.php new file mode 100644 index 0000000..d6596a4 --- /dev/null +++ b/Classes/Checkout/Cart/CartRestorer.php @@ -0,0 +1,41 @@ +getCart(); + if ($cart === null) { + return; + } + + // a new order gets new numbers + $cart->resetOrderNumber(); + $cart->resetInvoiceNumber(); + $this->sessionHandler->writeCart((string)$this->settings->getCartPid(), $cart); + } +} diff --git a/Classes/Checkout/CheckoutException.php b/Classes/Checkout/CheckoutException.php new file mode 100644 index 0000000..4035863 --- /dev/null +++ b/Classes/Checkout/CheckoutException.php @@ -0,0 +1,31 @@ + $returnUrl, + 'cancel_url' => $cancelUrl, + 'user_action' => 'PAY_NOW', + 'shipping_preference' => $this->settings->getShippingPreference(), + ]; + if ($this->settings->getBrandName() !== '') { + $experienceContext['brand_name'] = mb_substr($this->settings->getBrandName(), 0, self::MAX_LENGTH); + } + if ($this->settings->getLocale() !== '') { + $experienceContext['locale'] = $this->settings->getLocale(); + } + + return [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ + $this->buildPurchaseUnit($orderItem), + ], + 'payment_source' => [ + 'paypal' => [ + 'experience_context' => $experienceContext, + ], + ], + ]; + } + + /** + * The order for the card button of the JavaScript SDK. The customer enters + * the card in an overlay of PayPal, the order has no payment source. + */ + public function buildForCard(Item $orderItem): array + { + return [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ + $this->buildPurchaseUnit($orderItem), + ], + ]; + } + + public static function formatAmount(float $amount, string $currencyCode): string + { + $decimals = in_array(strtoupper($currencyCode), self::CURRENCIES_WITHOUT_DECIMALS, true) ? 0 : 2; + + return number_format(round($amount, $decimals), $decimals, '.', ''); + } + + private function buildPurchaseUnit(Item $orderItem): array + { + $currencyCode = strtoupper($orderItem->getCurrencyCode()); + + $purchaseUnit = [ + 'custom_id' => (string)$orderItem->getUid(), + 'amount' => [ + 'currency_code' => $currencyCode, + 'value' => self::formatAmount($orderItem->getTotalGross(), $currencyCode), + ], + ]; + + $orderNumber = (string)$orderItem->getOrderNumber(); + if ($orderNumber !== '') { + $purchaseUnit['invoice_id'] = mb_substr($orderNumber, 0, self::MAX_LENGTH); + } + + return $purchaseUnit; + } +} diff --git a/Classes/Checkout/Payment/PayPalOrder.php b/Classes/Checkout/Payment/PayPalOrder.php new file mode 100644 index 0000000..e847ebe --- /dev/null +++ b/Classes/Checkout/Payment/PayPalOrder.php @@ -0,0 +1,26 @@ +getOrderItem(); + if (!$orderItem instanceof Item) { + throw new CheckoutException('The stored cart has no order.', CheckoutException::NO_ORDER); + } + + $payment = $orderItem->getPayment(); + $provider = PaymentProvider::tryFrom((string)$payment?->getProvider()); + if (!$payment instanceof Payment || !$provider instanceof PaymentProvider) { + throw new CheckoutException('The order is not paid with PayPal.', CheckoutException::NOT_PAYPAL); + } + + return new self($cartRecord, $orderItem, $payment, $provider); + } + + public function getCartRecord(): Cart + { + return $this->cartRecord; + } + + /** + * The success hash of the stored cart, the customer pays the order with it. + */ + public function getSHash(): string + { + return $this->cartRecord->getSHash(); + } + + /** + * The failure hash of the stored cart, the customer cancels the payment + * with it. + */ + public function getFHash(): string + { + return $this->cartRecord->getFHash(); + } + + public function getOrderItem(): Item + { + return $this->orderItem; + } + + public function getPayment(): Payment + { + return $this->payment; + } + + public function getStatus(): string + { + return $this->payment->getStatus(); + } + + public function isPaid(): bool + { + return $this->payment->isPaid(); + } + + /** + * A pending payment is captured by PayPal, but the money has not been + * received yet, e.g. because PayPal reviews it. + */ + public function isPending(): bool + { + return $this->payment->isPending(); + } + + /** + * A paid or pending payment must not be paid again. + */ + public function isPaidOrPending(): bool + { + return $this->isPaid() || $this->isPending(); + } + + public function isCanceled(): bool + { + return $this->payment->isCanceled(); + } + + public function isCreditCard(): bool + { + return $this->provider === PaymentProvider::CreditCard; + } + + /** + * The cart of the order, the events of cart need it. + * + * @throws CheckoutException + */ + public function getCart(): CartCart + { + $cart = $this->cartRecord->getCart(); + if (!$cart instanceof CartCart) { + throw new CheckoutException('The stored cart has no cart.', CheckoutException::NO_ORDER); + } + + return $cart; + } + + /** + * The transaction of a PayPal order created for this payment. + * + * @throws CheckoutException if the PayPal order does not belong to this payment + */ + public function getTransaction(string $payPalOrderId): Transaction + { + foreach ($this->payment->getTransactions() as $transaction) { + if ($payPalOrderId !== '' && $transaction->getTxnId() === $payPalOrderId) { + return $transaction; + } + } + + throw new CheckoutException('The PayPal order does not belong to the order.', CheckoutException::UNKNOWN_PAYPAL_ORDER); + } +} diff --git a/Classes/Checkout/Payment/PaymentProcessor.php b/Classes/Checkout/Payment/PaymentProcessor.php new file mode 100644 index 0000000..5f9858b --- /dev/null +++ b/Classes/Checkout/Payment/PaymentProcessor.php @@ -0,0 +1,248 @@ +isPaidOrPending()) { + throw new CheckoutException('The order is paid or its payment is pending.', CheckoutException::PAID_OR_PENDING); + } + if ($payPalPayment->isCanceled()) { + throw new CheckoutException('The payment of the order was canceled.', CheckoutException::CANCELED); + } + + $orderItem = $payPalPayment->getOrderItem(); + if (!$forRedirect && $payPalPayment->isCreditCard()) { + $orderRequest = $this->orderRequestBuilder->buildForCard($orderItem); + } else { + $orderRequest = $this->orderRequestBuilder->build( + $orderItem, + $this->urlBuilder->getApiUrl('return', $payPalPayment->getSHash()), + $this->urlBuilder->getApiUrl('cancel', $payPalPayment->getFHash()) + ); + } + $order = $this->client->createOrder($orderRequest); + + $payPalOrderId = $this->getPayPalOrderId($order); + $this->transactionWriter->addPayPalOrder( + $payPalPayment->getPayment(), + $payPalOrderId, + (string)($order['status'] ?? '') + ); + + return new PayPalOrder($payPalOrderId, $this->getApproveUrl($order)); + } + + /** + * Captures the PayPal order after the customer approved it. + * + * @param bool $byPayPal the capture is caused by PayPal, e.g. a webhook, not by the customer + * + * @throws CheckoutException if the PayPal order does not belong to the order + * @throws ApiException + */ + public function capture(PayPalPayment $payPalPayment, string $payPalOrderId, bool $byPayPal = false): CaptureResult + { + $transaction = $payPalPayment->getTransaction($payPalOrderId); + + if ($payPalPayment->isPaid()) { + return CaptureResult::Paid; + } + + try { + $order = $this->client->captureOrder($payPalOrderId); + } catch (ApiException $exception) { + if ($exception->getIssue() === 'ORDER_ALREADY_CAPTURED') { + $order = $this->client->getOrder($payPalOrderId); + } elseif ($exception->getStatusCode() === 422) { + // e.g. INSTRUMENT_DECLINED, the customer may try again + $this->logger->warning('PayPal declined the capture of an order.', [ + 'payPalOrderId' => $payPalOrderId, + 'issue' => $exception->getIssue(), + 'debugId' => $exception->getDebugId(), + ]); + $this->transactionWriter->changeStatus($transaction, TransactionStatus::Failed, $exception->getIssue() ?: $exception->getName()); + + return CaptureResult::Failed; + } else { + throw $exception; + } + } + + $capture = $order['purchase_units'][0]['payments']['captures'][0] ?? null; + if (!is_array($capture)) { + $this->transactionWriter->changeStatus($transaction, TransactionStatus::Failed, (string)($order['status'] ?? '')); + + return CaptureResult::Failed; + } + + return $this->applyCapture($payPalPayment, $payPalOrderId, $capture, $byPayPal); + } + + /** + * Updates the payment with a capture, as returned by the capture or sent + * by a webhook. + * + * @param array $capture a capture of the Orders v2 API + * @param bool $byPayPal the capture is reported by PayPal, e.g. a webhook, not by the customer + * + * @throws CheckoutException if the PayPal order does not belong to the order + */ + public function applyCapture(PayPalPayment $payPalPayment, string $payPalOrderId, array $capture, bool $byPayPal): CaptureResult + { + $transaction = $payPalPayment->getTransaction($payPalOrderId); + $orderItem = $payPalPayment->getOrderItem(); + $payment = $payPalPayment->getPayment(); + $status = (string)($capture['status'] ?? ''); + $captureId = (string)($capture['id'] ?? ''); + + if ($status === 'COMPLETED') { + if (!$this->isAmountOfOrder($orderItem, $capture['amount'] ?? null)) { + $this->logger->error('The amount captured by PayPal differs from the order, the payment has to be checked.', [ + 'orderItem' => $orderItem->getUid(), + 'captureId' => $captureId, + ]); + $this->transactionWriter->changeStatus($transaction, TransactionStatus::Pending, $status, $captureId); + $this->paymentStatusUpdater->change($payment, PaymentStatus::PENDING, $byPayPal); + + return CaptureResult::Pending; + } + + $this->transactionWriter->changeStatus($transaction, TransactionStatus::Paid, $status, $captureId); + if ($this->paymentStatusUpdater->change($payment, PaymentStatus::PAID, $byPayPal)) { + $this->eventDispatcher->dispatch( + new FinishEvent($payPalPayment->getCart(), $orderItem, $this->settings->getCartConfiguration()) + ); + } + + return CaptureResult::Paid; + } + + if ($payPalPayment->isPaid()) { + // a webhook sent out of order must not change a paid order + return CaptureResult::Paid; + } + + if ($status === 'PENDING') { + $this->transactionWriter->changeStatus($transaction, TransactionStatus::Pending, $status, $captureId); + $this->paymentStatusUpdater->change($payment, PaymentStatus::PENDING, $byPayPal); + + return CaptureResult::Pending; + } + + $this->transactionWriter->changeStatus($transaction, TransactionStatus::Failed, $status, $captureId); + if ($payPalPayment->isPending()) { + $this->paymentStatusUpdater->change($payment, PaymentStatus::CANCELED, $byPayPal); + } + + return CaptureResult::Failed; + } + + /** + * Cancels the payment when the customer returns to the cart. Returns false + * if the order is paid already and can not be canceled. + */ + public function cancel(PayPalPayment $payPalPayment): bool + { + if ($payPalPayment->isPaidOrPending()) { + return false; + } + + $this->transactionWriter->cancelOpenPayPalOrders($payPalPayment->getPayment()); + + if ($this->paymentStatusUpdater->change($payPalPayment->getPayment(), PaymentStatus::CANCELED)) { + $this->eventDispatcher->dispatch( + new CancelEvent($payPalPayment->getCart(), $payPalPayment->getOrderItem(), $this->settings->getCartConfiguration()) + ); + } + + return true; + } + + private function isAmountOfOrder(Item $orderItem, mixed $amount): bool + { + if (!is_array($amount)) { + return false; + } + + $currencyCode = strtoupper($orderItem->getCurrencyCode()); + + return strtoupper((string)($amount['currency_code'] ?? '')) === $currencyCode + && OrderRequestBuilder::formatAmount((float)($amount['value'] ?? 0), $currencyCode) + === OrderRequestBuilder::formatAmount($orderItem->getTotalGross(), $currencyCode); + } + + /** + * @throws ApiException + */ + private function getPayPalOrderId(array $order): string + { + $payPalOrderId = (string)($order['id'] ?? ''); + if ($payPalOrderId === '') { + throw new ApiException('PayPal did not return the id of the order.', 1795600005); + } + + return $payPalOrderId; + } + + private function getApproveUrl(array $order): string + { + foreach ($order['links'] ?? [] as $link) { + if (in_array($link['rel'] ?? '', ['payer-action', 'approve'], true)) { + return (string)($link['href'] ?? ''); + } + } + + return ''; + } +} diff --git a/Classes/Checkout/Payment/PaymentProvider.php b/Classes/Checkout/Payment/PaymentProvider.php new file mode 100644 index 0000000..11a2666 --- /dev/null +++ b/Classes/Checkout/Payment/PaymentProvider.php @@ -0,0 +1,38 @@ + + */ + public static function values(): array + { + return array_column(self::cases(), 'value'); + } +} diff --git a/Classes/Checkout/Payment/PaymentStatus.php b/Classes/Checkout/Payment/PaymentStatus.php new file mode 100644 index 0000000..f8ba575 --- /dev/null +++ b/Classes/Checkout/Payment/PaymentStatus.php @@ -0,0 +1,26 @@ +connectionPool + ->getConnectionForTable(self::PAYMENT_TABLE) + ->update( + self::PAYMENT_TABLE, + [ + 'status' => $toStatus, + 'tstamp' => time(), + ], + [ + 'uid' => (int)$payment->getUid(), + 'status' => $fromStatus, + ], + [ + 'tstamp' => Connection::PARAM_INT, + 'uid' => Connection::PARAM_INT, + ] + ); + + return $affectedRows > 0; + } + + public function getStoredStatus(Payment $payment): string + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::PAYMENT_TABLE); + $queryBuilder->getRestrictions()->removeAll(); + + return (string)$queryBuilder + ->select('status') + ->from(self::PAYMENT_TABLE) + ->where( + $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$payment->getUid(), Connection::PARAM_INT)) + ) + ->executeQuery() + ->fetchOne(); + } +} diff --git a/Classes/Checkout/Payment/PaymentStatusUpdater.php b/Classes/Checkout/Payment/PaymentStatusUpdater.php new file mode 100644 index 0000000..e2711a3 --- /dev/null +++ b/Classes/Checkout/Payment/PaymentStatusUpdater.php @@ -0,0 +1,58 @@ +paymentStatusStore->updateIfStatus($payment, $payment->getStatus(), $toStatus); + + if (!$changed) { + // changed by another request since the payment was loaded, try again with the stored status + $storedStatus = $this->paymentStatusStore->getStoredStatus($payment); + $payment->setStatus($storedStatus); + $changed = $this->paymentStatusStore->updateIfStatus($payment, $storedStatus, $toStatus); + + if (!$changed && $storedStatus !== $toStatus) { + $this->logger->error('The status of a payment paid with PayPal could not be changed.', [ + 'payment' => $payment->getUid(), + 'toStatus' => $toStatus, + ]); + } + } + + if ($changed) { + $payment->setStatus($toStatus); + } + + return $changed; + } +} diff --git a/Classes/Checkout/Payment/TransactionStatus.php b/Classes/Checkout/Payment/TransactionStatus.php new file mode 100644 index 0000000..8dddb7f --- /dev/null +++ b/Classes/Checkout/Payment/TransactionStatus.php @@ -0,0 +1,29 @@ +setPid((int)$payment->getPid()); + $transaction->setTxnId($payPalOrderId); + $transaction->setStatus(TransactionStatus::Created->value); + $transaction->setExternalStatusCode($externalStatusCode); + + $payment->addTransaction($transaction); + $this->paymentRepository->update($payment); + $this->persistenceManager->persistAll(); + } + + /** + * @param string $captureId the id of the capture at PayPal, stored as note + */ + public function changeStatus( + Transaction $transaction, + TransactionStatus $status, + string $externalStatusCode, + string $captureId = '' + ): void { + $transaction->setStatus($status->value); + $transaction->setExternalStatusCode($externalStatusCode); + if ($captureId !== '') { + $transaction->setNote($captureId); + } + + $this->transactionRepository->update($transaction); + $this->persistenceManager->persistAll(); + } + + /** + * Cancels the PayPal orders of the payment which have not been captured. + */ + public function cancelOpenPayPalOrders(Payment $payment): void + { + foreach ($payment->getTransactions() as $transaction) { + if ($transaction->getStatus() === TransactionStatus::Created->value) { + $transaction->setStatus(TransactionStatus::Canceled->value); + $this->transactionRepository->update($transaction); + } + } + + $this->persistenceManager->persistAll(); + } +} diff --git a/Classes/Checkout/Settings.php b/Classes/Checkout/Settings.php new file mode 100644 index 0000000..540f6fd --- /dev/null +++ b/Classes/Checkout/Settings.php @@ -0,0 +1,90 @@ +cartConfiguration ??= $this->configurationManager->getConfiguration( + ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, + 'Cart' + ); + } + + public function getCartPid(): int + { + return (int)($this->getCartConfiguration()['settings']['cart']['pid'] ?? 0); + } + + public function getOrderPid(): int + { + return (int)($this->getCartConfiguration()['settings']['order']['pid'] ?? 0); + } + + public function getTypeNum(): int + { + return (int)($this->getConfiguration()['redirectTypeNum'] ?? 0); + } + + public function getPaymentPid(): int + { + return (int)($this->getSettings()['paymentPid'] ?? 0); + } + + public function getBrandName(): string + { + return trim((string)($this->getSettings()['brandName'] ?? '')); + } + + public function getLocale(): string + { + return trim((string)($this->getSettings()['locale'] ?? '')); + } + + public function getShippingPreference(): string + { + return trim((string)($this->getSettings()['shippingPreference'] ?? '')) ?: 'NO_SHIPPING'; + } + + private function getSettings(): array + { + $settings = $this->getConfiguration()['settings'] ?? []; + + return is_array($settings) ? $settings : []; + } + + private function getConfiguration(): array + { + return $this->configuration ??= $this->configurationManager->getConfiguration( + ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, + 'CartPaypal' + ); + } +} diff --git a/Classes/Checkout/UrlBuilder.php b/Classes/Checkout/UrlBuilder.php new file mode 100644 index 0000000..3eebacf --- /dev/null +++ b/Classes/Checkout/UrlBuilder.php @@ -0,0 +1,94 @@ +build($this->settings->getCartPid(), [ + 'tx_cartpaypal_api' => [ + 'controller' => 'Api', + 'action' => $action, + 'hash' => $hash, + ], + 'type' => $this->settings->getTypeNum(), + ]); + } + + public function getPaymentPageUrl(string $hash): string + { + return $this->build($this->settings->getPaymentPid(), [ + 'tx_cartpaypal_payment' => [ + 'hash' => $hash, + ], + ]); + } + + /** + * The confirmation page of the order, like after an order without + * payment provider. + */ + public function getOrderUrl(Item $orderItem): string + { + return $this->build($this->settings->getCartPid(), [ + 'tx_cart_cart' => [ + 'controller' => 'Cart\\Order', + 'action' => 'show', + 'orderItem' => $orderItem->getUid(), + ], + ]); + } + + public function getCartUrl(): string + { + return $this->build($this->settings->getCartPid(), []); + } + + private function build(int $pageId, array $parameters): string + { + $language = $this->getCurrentLanguage(); + if ($language instanceof SiteLanguage) { + $parameters['_language'] = $language; + } + + return (string)$this->siteFinder->getSiteByPageId($pageId)->getRouter()->generateUri($pageId, $parameters); + } + + private function getCurrentLanguage(): ?SiteLanguage + { + $request = $GLOBALS['TYPO3_REQUEST'] ?? null; + if (!$request instanceof ServerRequestInterface) { + return null; + } + + $language = $request->getAttribute('language'); + + return $language instanceof SiteLanguage ? $language : null; + } +} diff --git a/Classes/Checkout/Webhook/WebhookEventType.php b/Classes/Checkout/Webhook/WebhookEventType.php new file mode 100644 index 0000000..e51e43b --- /dev/null +++ b/Classes/Checkout/Webhook/WebhookEventType.php @@ -0,0 +1,37 @@ +logger->info('Ignored a webhook of PayPal.', ['eventType' => (string)($event['event_type'] ?? '')]); + return; + } + + $payPalOrderId = match ($eventType) { + WebhookEventType::OrderApproved => (string)($resource['id'] ?? ''), + default => (string)($resource['supplementary_data']['related_ids']['order_id'] ?? ''), + }; + + $payPalPayment = $this->findPayPalPayment($eventType, $payPalOrderId); + if (!$payPalPayment instanceof PayPalPayment) { + return; + } + + match ($eventType) { + WebhookEventType::OrderApproved => $this->paymentProcessor->capture($payPalPayment, $payPalOrderId, true), + WebhookEventType::CaptureCompleted, + WebhookEventType::CapturePending, + WebhookEventType::CaptureDenied, + WebhookEventType::CaptureDeclined => $this->paymentProcessor->applyCapture($payPalPayment, $payPalOrderId, $resource, true), + }; + } + + private function findPayPalPayment(WebhookEventType $eventType, string $payPalOrderId): ?PayPalPayment + { + $cartRecord = $this->cartRecordFinder->findByPayPalOrderId($payPalOrderId); + + if (!$cartRecord instanceof Cart) { + // e.g. a payment of another shop using the same PayPal account + $this->logger->info('Ignored a webhook of PayPal for an unknown order.', [ + 'eventType' => $eventType->value, + 'payPalOrderId' => $payPalOrderId, + ]); + + return null; + } + + return PayPalPayment::fromCartRecord($cartRecord); + } +} diff --git a/Classes/Configuration/CredentialLoaderInterface.php b/Classes/Configuration/CredentialLoaderInterface.php new file mode 100644 index 0000000..39dca0b --- /dev/null +++ b/Classes/Configuration/CredentialLoaderInterface.php @@ -0,0 +1,19 @@ + $credentialLoaders + */ + public function __construct(private readonly iterable $credentialLoaders) {} + + public function getCredentials(): array + { + $credentials = []; + + foreach ($this->credentialLoaders as $credentialLoader) { + $credentials = array_replace_recursive($credentialLoader->getCredentials(), $credentials); + } + + return $credentials; + } +} diff --git a/Classes/Configuration/CredentialsFromConfVars.php b/Classes/Configuration/CredentialsFromConfVars.php new file mode 100644 index 0000000..c62e5c0 --- /dev/null +++ b/Classes/Configuration/CredentialsFromConfVars.php @@ -0,0 +1,47 @@ +extensionConfiguration->get('cart_paypal'); + } catch (ExtensionConfigurationExtensionNotConfiguredException) { + $this->credentials = []; + return; + } + + if (isset($conf['credentials']) && is_array($conf['credentials'])) { + $this->credentials = $conf['credentials']; + } else { + $this->credentials = []; + } + } + + public static function getDefaultPriority(): int + { + return 30; + } + + public function getCredentials(): array + { + return $this->credentials; + } +} diff --git a/Classes/Configuration/CredentialsFromSiteConfiguration.php b/Classes/Configuration/CredentialsFromSiteConfiguration.php new file mode 100644 index 0000000..39a9ed9 --- /dev/null +++ b/Classes/Configuration/CredentialsFromSiteConfiguration.php @@ -0,0 +1,45 @@ +getAttribute('site'); + if (!$site instanceof Site) { + return []; + } + + $credentials = $site->getConfiguration()['cartPaypal']['credentials'] ?? []; + + return is_array($credentials) ? $credentials : []; + } +} diff --git a/Classes/Controller/ApiController.php b/Classes/Controller/ApiController.php new file mode 100644 index 0000000..52ac9a8 --- /dev/null +++ b/Classes/Controller/ApiController.php @@ -0,0 +1,263 @@ +assertPost($this->request); + $cartRecord = $this->getCartRecordOrRespond(); + + try { + $order = $this->paymentProcessor->createPayPalOrder(PayPalPayment::fromCartRecord($cartRecord)); + } catch (CheckoutException) { + $this->respondWithJson(['message' => $this->translate('payment.not_possible')], 409); + } catch (ApiException $exception) { + $this->logApiException($exception); + $this->respondWithJson(['message' => $this->translate('payment.error')], 502); + } + + $this->respondWithJson(['orderId' => $order->id]); + } + + /** + * Called by the JavaScript after the customer approved the payment. + */ + public function captureOrderAction(): ResponseInterface + { + $this->assertPost($this->request); + $cartRecord = $this->getCartRecordOrRespond(); + + $data = json_decode((string)$this->request->getBody(), true); + $payPalOrderId = is_array($data) && is_string($data['orderId'] ?? null) ? $data['orderId'] : ''; + + try { + $payPalPayment = PayPalPayment::fromCartRecord($cartRecord); + $result = $this->paymentProcessor->capture($payPalPayment, $payPalOrderId); + } catch (CheckoutException) { + $this->respondWithJson(['message' => $this->translate('payment.not_possible')], 409); + } catch (ApiException $exception) { + $this->logApiException($exception); + $this->respondWithJson(['message' => $this->translate('payment.error')], 502); + } + + if ($result === CaptureResult::Failed) { + $this->respondWithJson([ + 'status' => $result->value, + 'message' => $this->translate('payment.declined'), + ]); + } + + $this->respondWithJson([ + 'status' => $result->value, + 'redirectUrl' => $this->urlBuilder->getOrderUrl($payPalPayment->getOrderItem()), + ]); + } + + /** + * Sends the customer to PayPal without JavaScript, e.g. if no payment page + * is configured. + */ + public function redirectAction(): ResponseInterface + { + $cartRecord = $this->getCartRecord(); + if (!$cartRecord instanceof Cart) { + return $this->redirectToCart('access_denied'); + } + + try { + $order = $this->paymentProcessor->createPayPalOrder(PayPalPayment::fromCartRecord($cartRecord), forRedirect: true); + } catch (CheckoutException) { + return $this->redirectToOrderOrCart($cartRecord); + } catch (ApiException $exception) { + $this->logApiException($exception); + return $this->cancelAndRedirectToCart($cartRecord, 'payment.error'); + } + + if ($order->approveUrl === '') { + $this->logger->error('PayPal returned no URL to approve the order.', ['payPalOrderId' => $order->id]); + return $this->cancelAndRedirectToCart($cartRecord, 'payment.error'); + } + + return $this->redirectTo($order->approveUrl); + } + + /** + * The customer returns from PayPal after approving the payment. PayPal + * appends the id of its order as "token". + */ + public function returnAction(): ResponseInterface + { + $cartRecord = $this->getCartRecord(); + if (!$cartRecord instanceof Cart) { + return $this->redirectToCart('access_denied'); + } + + $payPalOrderId = $this->request->getQueryParams()['token'] ?? ''; + + try { + $payPalPayment = PayPalPayment::fromCartRecord($cartRecord); + $result = $this->paymentProcessor->capture($payPalPayment, is_string($payPalOrderId) ? $payPalOrderId : ''); + } catch (CheckoutException) { + return $this->redirectToOrderOrCart($cartRecord); + } catch (ApiException $exception) { + $this->logApiException($exception); + return $this->cancelAndRedirectToCart($cartRecord, 'payment.error'); + } + + if ($result === CaptureResult::Failed) { + if ($this->paypalSettings->getPaymentPid() > 0) { + $this->enqueueFlashMessage('extbase.flashmessages.tx_cartpaypal_payment', 'payment.declined'); + return $this->redirectTo($this->urlBuilder->getPaymentPageUrl($cartRecord->getSHash())); + } + return $this->cancelAndRedirectToCart($cartRecord, 'payment.declined'); + } + + return $this->redirectTo($this->urlBuilder->getOrderUrl($payPalPayment->getOrderItem())); + } + + /** + * The customer cancels the payment at PayPal or on the payment page and + * returns to the cart. + */ + public function cancelAction(): ResponseInterface + { + $cartRecord = $this->cartRecordFinder->findByFHash($this->getHashArgument()); + if (!$cartRecord instanceof Cart) { + return $this->redirectToCart('access_denied'); + } + + return $this->cancelAndRedirectToCart($cartRecord, 'payment.canceled'); + } + + private function cancelAndRedirectToCart(Cart $cartRecord, string $translationKey): ResponseInterface + { + try { + $canceled = $this->paymentProcessor->cancel(PayPalPayment::fromCartRecord($cartRecord)); + } catch (CheckoutException) { + return $this->redirectToCart('access_denied'); + } + + if (!$canceled) { + // paid in the meantime, e.g. in another tab + return $this->redirectToOrderOrCart($cartRecord); + } + + $this->cartRestorer->restore($cartRecord); + + return $this->redirectToCart($translationKey); + } + + private function redirectToOrderOrCart(Cart $cartRecord): ResponseInterface + { + $orderItem = $cartRecord->getOrderItem(); + $payment = $orderItem?->getPayment(); + + if ($orderItem !== null && $payment !== null && ($payment->isPaid() || $payment->isPending())) { + return $this->redirectTo($this->urlBuilder->getOrderUrl($orderItem)); + } + + return $this->redirectToCart('payment.not_possible'); + } + + private function redirectToCart(string $translationKey): ResponseInterface + { + $this->enqueueFlashMessage('extbase.flashmessages.tx_cart_cart', $translationKey); + + return $this->redirectTo($this->urlBuilder->getCartUrl()); + } + + /** + * Shows the message in the plugin of the page the customer is redirected to. + */ + private function enqueueFlashMessage(string $queueIdentifier, string $translationKey): void + { + $this->flashMessageService + ->getMessageQueueByIdentifier($queueIdentifier) + ->enqueue(new FlashMessage($this->translate($translationKey), '', ContextualFeedbackSeverity::ERROR, true)); + } + + private function getCartRecord(): ?Cart + { + return $this->cartRecordFinder->findBySHash($this->getHashArgument()); + } + + private function getHashArgument(): string + { + $hash = $this->request->hasArgument('hash') ? $this->request->getArgument('hash') : ''; + + return is_string($hash) ? $hash : ''; + } + + private function getCartRecordOrRespond(): Cart + { + $cartRecord = $this->getCartRecord(); + if (!$cartRecord instanceof Cart) { + $this->respondWithJson(['message' => $this->translate('access_denied')], 404); + } + + return $cartRecord; + } + + private function logApiException(ApiException $exception): void + { + $this->logger->error($exception->getMessage(), [ + 'issue' => $exception->getIssue(), + 'debugId' => $exception->getDebugId(), + ]); + } + + private function translate(string $key): string + { + return LocalizationUtility::translate('tx_cartpaypal.' . $key, 'CartPaypal') ?? $key; + } +} diff --git a/Classes/Controller/Order/PaymentController.php b/Classes/Controller/Order/PaymentController.php deleted file mode 100644 index 7c57bde..0000000 --- a/Classes/Controller/Order/PaymentController.php +++ /dev/null @@ -1,353 +0,0 @@ -logger = $logManager->getLogger(); - $this->persistenceManager = $persistenceManager; - $this->sessionHandler = $sessionHandler; - $this->cartRepository = $cartRepository; - $this->paymentRepository = $paymentRepository; - } - - protected function initializeAction(): void - { - $this->cartConf = - $this->configurationManager->getConfiguration( - ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, - 'Cart' - ); - - $this->cartPaypalConf = - $this->configurationManager->getConfiguration( - ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, - 'CartPayPal' - ); - } - - public function successAction(): void - { - if ($this->request->hasArgument('hash') && !empty($this->request->getArgument('hash'))) { - $this->loadCartByHash($this->request->getArgument('hash')); - - if ($this->cart) { - $orderItem = $this->cart->getOrderItem(); - - $successEvent = new SuccessEvent($this->cart->getCart(), $orderItem, $this->cartConf); - $this->eventDispatcher->dispatch($successEvent); - - $this->redirect('show', 'Cart\Order', 'Cart', ['orderItem' => $orderItem]); - } else { - $this->addFlashMessage( - LocalizationUtility::translate( - 'tx_cartpaypal.controller.order.payment.action.success.error_occured', - 'cart_paypal' - ), - '', - AbstractMessage::ERROR - ); - } - } else { - $this->addFlashMessage( - LocalizationUtility::translate( - 'tx_cartpaypal.controller.order.payment.action.success.access_denied', - 'cart_paypal' - ), - '', - AbstractMessage::ERROR - ); - } - } - - public function cancelAction(): void - { - if ($this->request->hasArgument('hash') && !empty($this->request->getArgument('hash'))) { - $this->loadCartByHash($this->request->getArgument('hash'), 'FHash'); - - if ($this->cart) { - $orderItem = $this->cart->getOrderItem(); - $payment = $orderItem->getPayment(); - - $this->restoreCartSession(); - - $payment->setStatus('canceled'); - - $this->paymentRepository->update($payment); - $this->persistenceManager->persistAll(); - - $this->addFlashMessage( - LocalizationUtility::translate( - 'tx_cartpaypal.controller.order.payment.action.cancel.successfully_canceled', - 'cart_paypal' - ) - ); - - $cancelEvent = new CancelEvent($this->cart->getCart(), $orderItem, $this->cartConf); - $this->eventDispatcher->dispatch($cancelEvent); - - $this->redirect('show', 'Cart\Cart', 'Cart'); - } else { - $this->addFlashMessage( - LocalizationUtility::translate( - 'tx_cartpaypal.controller.order.payment.action.cancel.error_occured', - 'cart_paypal' - ), - '', - AbstractMessage::ERROR - ); - } - } else { - $this->addFlashMessage( - LocalizationUtility::translate( - 'tx_cartpaypal.controller.order.payment.action.cancel.access_denied', - 'cart_paypal' - ), - '', - AbstractMessage::ERROR - ); - } - } - - public function notifyAction() - { - if ($this->request->getMethod() !== 'POST') { - // exit with Status Code in TYPO3 v10.4 - if (isset($this->response)) { - $this->response->setStatus(405); - exit(); - } - return $this->htmlResponse()->withStatus(405, 'Method not allowed.'); - } - - $postData = GeneralUtility::_POST(); - - $curlRequest = $this->getCurlRequestFromPostData($postData); - - if ($this->cartPaypalConf['debug']) { - $this->logger->debug( - 'Log Data', - [ - '$parsedPostData' => $postData, - '$curlRequest' => $curlRequest - ] - ); - } - - $this->execCurlRequest($curlRequest); - - $cartSHash = $postData['custom']; - if (empty($cartSHash)) { - // exit with Status Code in TYPO3 v10.4 - if (isset($this->response)) { - $this->response->setStatus(403); - exit(); - } - return $this->htmlResponse()->withStatus(403, 'Not allowed.'); - } - - $this->loadCartByHash($this->request->getArgument('hash')); - - if ($this->cart === null) { - // exit with Status Code in TYPO3 v10.4 - if (isset($this->response)) { - $this->response->setStatus(404); - exit(); - } - return $this->htmlResponse()->withStatus(404, 'Page / Cart not found.'); - } - - $orderItem = $this->cart->getOrderItem(); - $payment = $orderItem->getPayment(); - - if ($payment->getStatus() !== 'paid') { - $payment->setStatus('paid'); - $this->paymentRepository->update($payment); - $this->persistenceManager->persistAll(); - - $notifyEvent = new NotifyEvent($this->cart->getCart(), $orderItem, $this->cartConf); - $this->eventDispatcher->dispatch($notifyEvent); - } - - // exit with Status Code in TYPO3 v10.4 - if (isset($this->response)) { - $this->response->setStatus(200); - exit(); - } - return $this->htmlResponse()->withStatus(200); - } - - protected function restoreCartSession(): void - { - $cart = $this->cart->getCart(); - $cart->resetOrderNumber(); - $cart->resetInvoiceNumber(); - $this->sessionHandler->write($cart, $this->cartConf['settings']['cart']['pid']); - } - - protected function getCurlRequestFromPostData(array $parsePostData): string - { - $curlRequest = 'cmd=_notify-validate'; - foreach ($parsePostData as $key => $value) { - $value = urlencode($value); - $curlRequest .= "&$key=$value"; - } - - return $curlRequest; - } - - protected function execCurlRequest(string $curlRequest): bool - { - $paypalUrl = $this->getPaypalUrl(); - - $ch = curl_init($paypalUrl); - if ($ch === false) { - return false; - } - - curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $curlRequest); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); - - if (is_array($this->cartPaypalConf) && intval($this->cartPaypalConf['curl_timeout'])) { - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, intval($this->cartPaypalConf['curl_timeout'])); - } else { - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300); - } - curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']); - - $curlResult = strtolower(curl_exec($ch)); - $curlError = curl_errno($ch); - - if ($curlError !== 0) { - $this->logger->warning( - 'paypal-payment-api', - [ - 'ERROR' => 'Can\'t connect to PayPal to validate IPN message', - 'curl_error' => curl_error($ch), - 'curl_request' => $curlRequest, - 'curl_result' => $curlResult, - ] - ); - - curl_close($ch); - exit; - } - - if ($this->cartPaypalConf['debug']) { - $this->logger->debug( - 'paypal-payment-api', - [ - 'curl_info' => curl_getinfo($ch, CURLINFO_HEADER_OUT), - 'curl_request' => $curlRequest, - 'curl_result' => $curlResult, - ] - ); - } - - $curlResults = explode("\r\n\r\n", $curlResult); - - curl_close($ch); - - return true; - } - - protected function getPaypalUrl(): string - { - if ($this->cartPaypalConf['sandbox']) { - return self::PAYPAL_API_SANDBOX; - } - - return self::PAYPAL_API_LIVE; - } - - protected function loadCartByHash(string $hash, string $type = 'SHash'): void - { - $querySettings = GeneralUtility::makeInstance( - Typo3QuerySettings::class - ); - $querySettings->setStoragePageIds([$this->cartConf['settings']['order']['pid']]); - $this->cartRepository->setDefaultQuerySettings($querySettings); - - $findOneByMethod = 'findOneBy' . $type; - $this->cart = $this->cartRepository->$findOneByMethod($hash); - } -} diff --git a/Classes/Controller/PaymentController.php b/Classes/Controller/PaymentController.php new file mode 100644 index 0000000..8b0904e --- /dev/null +++ b/Classes/Controller/PaymentController.php @@ -0,0 +1,97 @@ +request->hasArgument('hash') ? $this->request->getArgument('hash') : ''; + $hash = is_string($hash) ? $hash : ''; + + $cartRecord = $this->cartRecordFinder->findBySHash($hash); + try { + $payPalPayment = $cartRecord instanceof Cart ? PayPalPayment::fromCartRecord($cartRecord) : null; + } catch (CheckoutException) { + $payPalPayment = null; + } + + if (!$payPalPayment instanceof PayPalPayment) { + $this->view->assign('state', 'unknown'); + return $this->htmlResponse(); + } + + $orderItem = $payPalPayment->getOrderItem(); + if ($payPalPayment->isPaidOrPending()) { + return $this->redirectTo($this->urlBuilder->getOrderUrl($orderItem)); + } + if ($payPalPayment->isCanceled()) { + $this->view->assignMultiple([ + 'state' => 'canceled', + 'cartUrl' => $this->urlBuilder->getCartUrl(), + ]); + return $this->htmlResponse(); + } + + $currencyCode = strtoupper($orderItem->getCurrencyCode()); + + $this->view->assignMultiple([ + // the currency format of cart is used unless cart_paypal configures its own + 'settings' => array_replace_recursive( + ['format' => ['currency' => $this->paypalSettings->getCartConfiguration()['settings']['format']['currency'] ?? []]], + $this->settings + ), + 'state' => 'open', + 'paymentMethod' => $payPalPayment->isCreditCard() ? 'card' : 'paypal', + 'orderItem' => $orderItem, + 'amount' => OrderRequestBuilder::formatAmount($orderItem->getTotalGross(), $currencyCode), + 'currencyCode' => $currencyCode, + 'paypal' => [ + 'sdkUrl' => $this->client->getSdkUrl(), + 'clientId' => $this->client->getClientId(), + 'locale' => $this->paypalSettings->getLocale(), + ], + 'urls' => [ + 'createOrder' => $this->urlBuilder->getApiUrl('createOrder', $hash), + 'captureOrder' => $this->urlBuilder->getApiUrl('captureOrder', $hash), + 'redirect' => $this->urlBuilder->getApiUrl('redirect', $hash), + 'cancel' => $this->urlBuilder->getApiUrl('cancel', $payPalPayment->getFHash()), + ], + ]); + + return $this->htmlResponse(); + } +} diff --git a/Classes/Controller/PropagateResponseTrait.php b/Classes/Controller/PropagateResponseTrait.php new file mode 100644 index 0000000..e6bfbff --- /dev/null +++ b/Classes/Controller/PropagateResponseTrait.php @@ -0,0 +1,46 @@ +getMethod() !== 'POST') { + throw new PropagateResponseException( + new JsonResponse(['message' => 'Method not allowed.'], 405, ['Allow' => 'POST']), + 1795600301 + ); + } + } + + private function respondWithJson(array $data, int $statusCode = 200): never + { + throw new PropagateResponseException(new JsonResponse($data, $statusCode), 1795600302); + } + + private function redirectTo(string $uri): never + { + throw new PropagateResponseException(new RedirectResponse($uri, 303), 1795600303); + } +} diff --git a/Classes/Controller/WebhookController.php b/Classes/Controller/WebhookController.php new file mode 100644 index 0000000..9188443 --- /dev/null +++ b/Classes/Controller/WebhookController.php @@ -0,0 +1,66 @@ +assertPost($this->request); + + $body = (string)$this->request->getBody(); + + try { + if (!$this->client->verifyWebhookSignature($this->request, $body)) { + $this->logger->warning('Rejected a webhook of PayPal with an invalid signature.'); + $this->respondWithJson(['message' => 'Invalid signature.'], 400); + } + + $event = json_decode($body, true); + $this->webhookHandler->handle(is_array($event) ? $event : []); + } catch (ApiException $exception) { + $this->logger->error($exception->getMessage(), [ + 'issue' => $exception->getIssue(), + 'debugId' => $exception->getDebugId(), + ]); + // PayPal sends the webhook again + $this->respondWithJson(['message' => 'PayPal could not be reached.'], 503); + } catch (CheckoutException $exception) { + // the webhook does not fit the order, a repetition does not help + $this->logger->warning('Ignored a webhook of PayPal: ' . $exception->getMessage()); + } + + $this->respondWithJson(['status' => 'ok']); + } +} diff --git a/Classes/Event/Order/CancelEvent.php b/Classes/Event/Order/CancelEvent.php index 2f2bd68..6cf90af 100644 --- a/Classes/Event/Order/CancelEvent.php +++ b/Classes/Event/Order/CancelEvent.php @@ -1,5 +1,7 @@ cart = $cart; - $this->orderItem = $orderItem; - $this->settings = $settings; - } + public function __construct( + private readonly Cart $cart, + private readonly OrderItem $orderItem, + private readonly array $settings = [] + ) {} public function getCart(): Cart { diff --git a/Classes/Event/Order/NotifyEvent.php b/Classes/Event/Order/FinishEvent.php similarity index 65% rename from Classes/Event/Order/NotifyEvent.php rename to Classes/Event/Order/FinishEvent.php index 17c0c53..72199dc 100644 --- a/Classes/Event/Order/NotifyEvent.php +++ b/Classes/Event/Order/FinishEvent.php @@ -1,5 +1,7 @@ cart = $cart; - $this->orderItem = $orderItem; - $this->settings = $settings; - } + public function __construct( + private readonly Cart $cart, + private readonly OrderItem $orderItem, + private readonly array $settings = [] + ) {} public function getCart(): Cart { diff --git a/Classes/Event/Order/SuccessEvent.php b/Classes/Event/Order/SuccessEvent.php deleted file mode 100644 index c989681..0000000 --- a/Classes/Event/Order/SuccessEvent.php +++ /dev/null @@ -1,70 +0,0 @@ -cart = $cart; - $this->orderItem = $orderItem; - $this->settings = $settings; - } - - public function getCart(): Cart - { - return $this->cart; - } - - public function getOrderItem(): OrderItem - { - return $this->orderItem; - } - - public function getSettings(): array - { - return $this->settings; - } - - public function setPropagationStopped(bool $isPropagationStopped): void - { - $this->isPropagationStopped = $isPropagationStopped; - } - - public function isPropagationStopped(): bool - { - return $this->isPropagationStopped; - } -} diff --git a/Classes/EventListener/Order/Payment/ClearCart.php b/Classes/EventListener/Order/Payment/ClearCart.php index f10439f..ebff856 100644 --- a/Classes/EventListener/Order/Payment/ClearCart.php +++ b/Classes/EventListener/Order/Payment/ClearCart.php @@ -1,5 +1,7 @@ getOrderItem(); $provider = $orderItem->getPayment()->getProvider(); - if (strpos($provider, 'PAYPAL') === 0) { - parent::__invoke($event); + if (PaymentProvider::tryFrom((string)$provider) instanceof PaymentProvider) { + $cart = $event->getCart(); + $settings = $event->getSettings(); + + $paymentId = $cart->getPayment()->getId(); + + $paymentMethod = $this->paymentMethodsService->getPaymentMethods($cart)[$paymentId] ?? null; + + if ((int)($paymentMethod?->getConfig()['preventClearCart'] ?? 0) !== 1) { + $cartPid = $settings['settings']['cart']['pid']; + + $this->sessionHandler->writeCart( + $cartPid, + $this->cartUtility->getNewCart($settings) + ); + $this->sessionHandler->writeAddress( + 'billing_address_' . $cartPid, + GeneralUtility::makeInstance(BillingAddress::class) + ); + $this->sessionHandler->writeAddress( + 'shipping_address_' . $cartPid, + GeneralUtility::makeInstance(ShippingAddress::class) + ); + } } } } diff --git a/Classes/EventListener/Order/Payment/ProviderRedirect.php b/Classes/EventListener/Order/Payment/ProviderRedirect.php index 78c7966..eae9e48 100644 --- a/Classes/EventListener/Order/Payment/ProviderRedirect.php +++ b/Classes/EventListener/Order/Payment/ProviderRedirect.php @@ -1,5 +1,7 @@ configurationManager = $configurationManager; - $this->persistenceManager = $persistenceManager; - $this->typoScriptService = $typoScriptService; - $this->uriBuilder = $uriBuilder; - $this->cartRepository = $cartRepository; - - $this->cartConf = $this->configurationManager->getConfiguration( - ConfigurationManager::CONFIGURATION_TYPE_FRAMEWORK, - 'Cart' - ); - - $this->cartPaypalConf = $this->configurationManager->getConfiguration( - ConfigurationManager::CONFIGURATION_TYPE_FRAMEWORK, - 'CartPaypal' - ); - } + private readonly CartRepository $cartRepository, + private readonly PersistenceManagerInterface $persistenceManager, + private readonly Settings $settings, + private readonly UrlBuilder $urlBuilder, + ) {} public function __invoke(PaymentEvent $event): void { - $this->orderItem = $event->getOrderItem(); + $orderItem = $event->getOrderItem(); - if ($this->orderItem->getPayment()->getProvider() !== 'PAYPAL') { + if (!PaymentProvider::tryFrom((string)$orderItem->getPayment()?->getProvider()) instanceof PaymentProvider) { return; } - $this->cart = $event->getCart(); - - $cart = $this->saveCurrentCartToDatabase(); - - $this->cartSHash = $cart->getSHash(); - $this->cartFHash = $cart->getFHash(); - - $this->getQuery(); + $cartRecord = new Cart(); + $cartRecord->setOrderItem($orderItem); + $cartRecord->setCart($event->getCart()); + $cartRecord->setPid($this->settings->getOrderPid()); - $paymentQueryString = http_build_query($this->paymentQuery); - header('Location: ' . $this->getQueryUrl() . $paymentQueryString); - - $event->setPropagationStopped(true); - } - - protected function saveCurrentCartToDatabase(): Cart - { - $cart = GeneralUtility::makeInstance(Cart::class); - - $cart->setOrderItem($this->orderItem); - $cart->setCart($this->cart); - $cart->setPid((int)$this->cartConf['settings']['order']['pid']); - - $this->cartRepository->add($cart); + $this->cartRepository->add($cartRecord); $this->persistenceManager->persistAll(); - return $cart; - } - - protected function getQueryUrl(): string - { - if ($this->cartPaypalConf['sandbox']) { - return self::PAYPAL_API_SANDBOX; - } - - return self::PAYPAL_API_LIVE; - } - - protected function getQuery(): void - { - $this->getQueryFromSettings(); - $this->getQueryFromCart(); - $this->getQueryFromOrder(); - } - - protected function getQueryFromSettings(): void - { - $this->paymentQuery['business'] = $this->cartPaypalConf['business']; - $this->paymentQuery['test_ipn'] = intval($this->cartPaypalConf['sandbox']); - - $this->paymentQuery['custom'] = $this->cartSHash; - $this->paymentQuery['notify_url'] = $this->getUrl('notify', $this->cartSHash); - $this->paymentQuery['return'] = $this->getUrl('success', $this->cartSHash); - $this->paymentQuery['cancel_return'] = $this->getUrl('cancel', $this->cartFHash); - - $this->paymentQuery['cmd'] = '_cart'; - $this->paymentQuery['upload'] = '1'; - - $this->paymentQuery['currency_code'] = $this->orderItem->getCurrencyCode(); - } - - protected function getQueryFromCart(): void - { - $this->paymentQuery['invoice'] = $this->cart->getOrderNumber(); + $event->setPropagationStopped(true); - if ($this->cartPaypalConf['sendEachItemToPaypal']) { - $this->addEachItemsFromCartToQuery(); + if ($this->settings->getPaymentPid() > 0) { + $url = $this->urlBuilder->getPaymentPageUrl($cartRecord->getSHash()); } else { - $this->addEntireCartToQuery(); - } - } - - protected function getQueryFromOrder(): void - { - $billingAddress = $this->orderItem->getBillingAddress(); - - $this->paymentQuery['first_name'] = $billingAddress->getFirstName(); - $this->paymentQuery['last_name'] = $billingAddress->getLastName(); - $this->paymentQuery['email'] = $billingAddress->getEmail(); - } - - protected function addEachItemsFromCartToQuery(): void - { - $shippingGross = $this->cart->getShipping()->getGross(); - $this->paymentQuery['handling_cart'] = number_format( - $shippingGross, - 2, - '.', - '' - ); - - $this->addEachCouponFromCartToQuery(); - $this->addEachProductFromCartToQuery(); - - $this->paymentQuery['mc_gross'] = number_format( - $this->cart->getTotalGross(), - 2, - '.', - '' - ); - } - - protected function addEachCouponFromCartToQuery(): void - { - if ($this->cart->getCoupons()) { - $discount = 0; - /** - * @var CartCoupon $cartCoupon - */ - foreach ($this->cart->getCoupons() as $cartCoupon) { - if ($cartCoupon->getIsUseable()) { - $discount += $cartCoupon->getDiscount(); - } - } - - $this->paymentQuery['discount_amount_cart'] = $discount; + $url = $this->urlBuilder->getApiUrl('redirect', $cartRecord->getSHash()); } - } - - protected function addEachProductFromCartToQuery(): void - { - if ($this->orderItem->getProducts()) { - $count = 0; - foreach ($this->orderItem->getProducts() as $productKey => $product) { - $count += 1; - - $this->paymentQuery['item_name_' . $count] = $product->getTitle(); - $this->paymentQuery['quantity_' . $count] = $product->getCount(); - $this->paymentQuery['amount_' . $count] = number_format( - $product->getGross() / $product->getCount(), - 2, - '.', - '' - ); - } - } - } - - protected function addEntireCartToQuery(): void - { - $this->paymentQuery['quantity'] = 1; - $this->paymentQuery['mc_gross'] = number_format( - $this->cart->getGross() + $this->cart->getServiceGross(), - 2, - '.', - '' - ); - - $this->paymentQuery['item_name_1'] = $this->cartPaypalConf['sendEachItemToPaypalTitle']; - $this->paymentQuery['quantity_1'] = 1; - $this->paymentQuery['amount_1'] = $this->paymentQuery['mc_gross']; - } - - protected function getUrl(string $action, string $hash): string - { - $pid = (int)$this->cartConf['settings']['cart']['pid']; - - $arguments = [ - 'tx_cartpaypal_cart' => [ - 'controller' => 'Order\Payment', - 'order' => $this->orderItem->getUid(), - 'action' => $action, - 'hash' => $hash - ] - ]; - return $this->uriBuilder->reset() - ->setTargetPageUid($pid) - ->setTargetPageType((int)$this->cartPaypalConf['redirectTypeNum']) - ->setCreateAbsoluteUri(true) - ->setArguments($arguments) - ->build(); + throw new PropagateResponseException(new RedirectResponse($url, 303), 1795600201); } } diff --git a/Configuration/Icons.php b/Configuration/Icons.php new file mode 100644 index 0000000..0a77f1c --- /dev/null +++ b/Configuration/Icons.php @@ -0,0 +1,12 @@ + [ + 'provider' => SvgIconProvider::class, + 'source' => 'EXT:cart_paypal/Resources/Public/Icons/Extension.svg', + ], +]; diff --git a/Configuration/Services.php b/Configuration/Services.php new file mode 100644 index 0000000..a7f8738 --- /dev/null +++ b/Configuration/Services.php @@ -0,0 +1,56 @@ +services(); + + $services + ->defaults() + ->autowire() + ->autoconfigure() + ->private(); + + $services + ->instanceof(CredentialLoaderInterface::class) + ->tag('cartPaypal.credentialLoader'); + + $services->load( + 'Extcode\\CartPaypal\\', + '../Classes/*' + ); + + $services->set(CredentialLoaderRegistry::class) + ->arg('$credentialLoaders', tagged_iterator('cartPaypal.credentialLoader')); + + $services->set(ClearCart::class) + ->tag('event.listener', [ + 'identifier' => 'cart-paypal--order--payment--clear-cart', + 'event' => PaymentEvent::class, + 'before' => 'cart-paypal--order--payment--provider-redirect', + ]); + + $services->set(ProviderRedirect::class) + ->tag('event.listener', [ + 'identifier' => 'cart-paypal--order--payment--provider-redirect', + 'event' => PaymentEvent::class, + ]); + + $services->set('cart-paypal--event-listener--order--finish--email', Email::class) + ->tag('event.listener', [ + 'identifier' => 'cart-paypal--order--finish--email', + 'event' => FinishEvent::class, + ]); +}; diff --git a/Configuration/Services.yaml b/Configuration/Services.yaml deleted file mode 100644 index dc17ee4..0000000 --- a/Configuration/Services.yaml +++ /dev/null @@ -1,46 +0,0 @@ -services: - _defaults: - autowire: true - autoconfigure: true - public: false - - Extcode\CartPaypal\: - resource: '../Classes/*' - exclude: '../Classes/Widgets/*' - - Extcode\CartPaypal\Controller\Order\PaymentController: - arguments: - $logManager: '@TYPO3\CMS\Core\Log\LogManager' - $persistenceManager: '@TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager' - $sessionHandler: '@Extcode\Cart\Service\SessionHandler' - $cartRepository: '@Extcode\Cart\Domain\Repository\CartRepository' - $paymentRepository: '@Extcode\Cart\Domain\Repository\Order\PaymentRepository' - - Extcode\CartPaypal\EventListener\Order\Payment\ClearCart: - arguments: - $cartUtility: '@Extcode\Cart\Utility\CartUtility' - $parserUtility: '@Extcode\Cart\Utility\ParserUtility' - $sessionHandler: '@Extcode\Cart\Service\SessionHandler' - tags: - - name: event.listener - identifier: 'cart-paypal--order--payment--clear-cart' - event: Extcode\Cart\Event\Order\PaymentEvent - before: 'cart-paypal--order--payment--provider-redirect' - - Extcode\CartPaypal\EventListener\Order\Payment\ProviderRedirect: - arguments: - $configurationManager: '@TYPO3\CMS\Extbase\Configuration\ConfigurationManager' - $persistenceManager: '@TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager' - $typoScriptService: '@TYPO3\CMS\Core\TypoScript\TypoScriptService' - $cartRepository: '@Extcode\Cart\Domain\Repository\CartRepository' - tags: - - name: event.listener - identifier: 'cart-paypal--order--payment--provider-redirect' - event: Extcode\Cart\Event\Order\PaymentEvent - - Extcode\CartPaypal\EventListener\Order\Notify\Email: - class: 'Extcode\Cart\EventListener\Order\Finish\Email' - tags: - - name: event.listener - identifier: 'cart-paypal--order--notify--email' - event: Extcode\CartPaypal\Event\Order\NotifyEvent diff --git a/Configuration/Sets/CartPaypal/config.yaml b/Configuration/Sets/CartPaypal/config.yaml new file mode 100644 index 0000000..4e9b0c6 --- /dev/null +++ b/Configuration/Sets/CartPaypal/config.yaml @@ -0,0 +1,2 @@ +name: extcode/cart-paypal +label: 'Cart PayPal' diff --git a/Configuration/Sets/CartPaypal/settings.definitions.yaml b/Configuration/Sets/CartPaypal/settings.definitions.yaml new file mode 100644 index 0000000..b680d5c --- /dev/null +++ b/Configuration/Sets/CartPaypal/settings.definitions.yaml @@ -0,0 +1,38 @@ +categories: + cartPaypal: + label: 'Cart PayPal' + +settings: + plugin.tx_cartpaypal.paymentPid: + label: 'Payment page' + description: 'Page with the content element "Cart: PayPal payment". Without a page the customer is redirected to PayPal directly after the order.' + category: cartPaypal + type: page + default: 0 + plugin.tx_cartpaypal.redirectTypeNum: + label: 'Page type of the endpoints' + description: 'Page type of the webhook, of the return from PayPal and of the requests of the payment page.' + category: cartPaypal + type: int + default: 2278101 + plugin.tx_cartpaypal.brandName: + label: 'Shop name at PayPal' + description: 'Name of the shop shown by PayPal, at most 127 characters. Empty shows the name of the PayPal account.' + category: cartPaypal + type: string + default: '' + plugin.tx_cartpaypal.locale: + label: 'Language at PayPal' + description: 'Language of the PayPal pages as BCP-47 code, e.g. de-DE. Empty lets PayPal decide.' + category: cartPaypal + type: string + default: '' + plugin.tx_cartpaypal.shippingPreference: + label: 'Shipping address at PayPal' + description: 'NO_SHIPPING: PayPal asks for no shipping address, the order has the addresses of the cart. GET_FROM_FILE: the customer chooses a shipping address stored at PayPal, it is not transferred to the order.' + category: cartPaypal + type: string + enum: + NO_SHIPPING: 'No shipping address' + GET_FROM_FILE: 'Shipping address stored at PayPal' + default: NO_SHIPPING diff --git a/Configuration/Sets/CartPaypal/setup.typoscript b/Configuration/Sets/CartPaypal/setup.typoscript new file mode 100644 index 0000000..813c587 --- /dev/null +++ b/Configuration/Sets/CartPaypal/setup.typoscript @@ -0,0 +1 @@ +@import 'EXT:cart_paypal/Configuration/TypoScript/setup.typoscript' diff --git a/Configuration/TCA/Overrides/sys_template.php b/Configuration/TCA/Overrides/sys_template.php index 6f17b50..ded0bbe 100644 --- a/Configuration/TCA/Overrides/sys_template.php +++ b/Configuration/TCA/Overrides/sys_template.php @@ -1,5 +1,8 @@ [ + 'clientId' => getenv('PAYPAL_CLIENT_ID'), + 'clientSecret' => getenv('PAYPAL_CLIENT_SECRET'), + 'webhookId' => getenv('PAYPAL_WEBHOOK_ID'), + 'sandbox' => getenv('PAYPAL_SANDBOX'), + ], + ]; + +The names of the environment variables are free to choose. + +.. _credentials-environment-variables: + +Environment variables +===================== + +TYPO3 does not read a `.env` file itself. The environment variables have to +be provided by one of these: + +* the web server or PHP-FPM, e.g. `SetEnv` of Apache or `env[...]` in the pool + configuration of PHP-FPM, +* the container, e.g. `environment` or `env_file` in a Docker Compose file, +* the hosting environment, many hosters allow to define environment variables, +* a package reading a `.env` file, e.g. `helhum/dotenv-connector`. + +Environment variables of the web server are not available on the command +line. Provide them there as well if a command needs the credentials. + +.. WARNING:: + + Do not put the credentials into `config/system/settings.php`. The file is + written by the backend and the install tool and often versioned. + +Never commit the `.env` file with the credentials, add it to `.gitignore`. diff --git a/Documentation/Administrator/Configuration/Credentials/CredentialsFromSiteConfiguration.rst b/Documentation/Administrator/Configuration/Credentials/CredentialsFromSiteConfiguration.rst new file mode 100644 index 0000000..a7c43d3 --- /dev/null +++ b/Documentation/Administrator/Configuration/Credentials/CredentialsFromSiteConfiguration.rst @@ -0,0 +1,41 @@ +.. include:: ../../../Includes.rst.txt + +.. _credentials-from-site-configuration: + +======================================= +Credentials from the site configuration +======================================= + +If the sites of an installation use different PayPal apps, the credentials +can be set per site in the site configuration +`config/sites//config.yaml`. Use them only if different +credentials are needed, otherwise use the +:ref:`credentials from $GLOBALS['TYPO3_CONF_VARS'] `. + +The site configuration is usually versioned. Read the values from environment +variables with the placeholder `%env()%` of TYPO3, never write a secret into +the file. Placeholders are kept when the site is saved in the backend module +*Sites*. + +.. code-block:: yaml + :caption: config/sites/shop/config.yaml + + cartPaypal: + credentials: + clientId: '%env(SHOP_PAYPAL_CLIENT_ID)%' + clientSecret: '%env(SHOP_PAYPAL_CLIENT_SECRET)%' + webhookId: '%env(SHOP_PAYPAL_WEBHOOK_ID)%' + sandbox: '%env(SHOP_PAYPAL_SANDBOX)%' + +The credentials of the site take precedence over the credentials of +`$GLOBALS['TYPO3_CONF_VARS']`, credentials missing in the site are taken from +there. Set all credentials in the site to avoid mixing two PayPal apps. + +See :ref:`Environment variables ` for how to +provide the environment variables. + +.. IMPORTANT:: + + Do not use the file `settings.yaml` of the site (site settings). Saving the + site settings in the backend replaces the placeholders with the values of + the environment variables. diff --git a/Documentation/Administrator/Configuration/Credentials/Index.rst b/Documentation/Administrator/Configuration/Credentials/Index.rst new file mode 100644 index 0000000..6a02ace --- /dev/null +++ b/Documentation/Administrator/Configuration/Credentials/Index.rst @@ -0,0 +1,69 @@ +.. include:: ../../../Includes.rst.txt + +.. _credentials: + +=========== +Credentials +=========== + +Cart PayPal needs the credentials of a PayPal app (REST API). + +======================== =================================================== +Credential Description +======================== =================================================== +clientId The client id of the app. It is public, the + JavaScript SDK on the payment page uses it. +clientSecret The secret of the app. +webhookId The id of the webhook of the app, see + :ref:`Webhook `. Without it, webhooks are + rejected. +sandbox `1` uses the PayPal sandbox, `0` the live system. + Without the setting the sandbox is used. +======================== =================================================== + +Store the credentials in environment variables and read them in +`config/system/additional.php`, see +:ref:`Credentials from $GLOBALS['TYPO3_CONF_VARS'] `. +This is the recommended way. + +Use the :ref:`credentials from the site configuration ` +only if the sites of an installation need different PayPal apps. + +.. IMPORTANT:: + + The credentials are no site settings and no TypoScript. Site settings are + shown in the backend module *Site Settings* and in the TypoScript of the + site, and saving them in the backend writes the values of environment + variables into `settings.yaml`. TypoScript is versioned and deployed with + the project or stored in the database. + +If the credentials are to be saved in a different way, +:ref:`Credentials from own CredentialLoader ` +describes how to provide the credentials implementing the +`CredentialLoaderInterface`. + +----- + +.. card-grid:: + :columns: 1 + :columns-md: 2 + :gap: 4 + :class: pb-4 + :card-height: 100 + + .. card:: :ref:`Credentials from TYPO3_CONF_VARS ` + + Credentials are read from $GLOBALS['TYPO3_CONF_VARS'], set from + environment variables in `config/system/additional.php`. + + .. card:: :ref:`Credentials from the site configuration ` + + Credentials are read from the configuration of the site, for + installations with different PayPal apps per site. + +.. toctree:: + :maxdepth: 2 + :titlesonly: + + CredentialsFromConfVars + CredentialsFromSiteConfiguration diff --git a/Documentation/Administrator/Configuration/Index.rst b/Documentation/Administrator/Configuration/Index.rst new file mode 100644 index 0000000..996ff2e --- /dev/null +++ b/Documentation/Administrator/Configuration/Index.rst @@ -0,0 +1,15 @@ +.. include:: ../../Includes.rst.txt + +============= +Configuration +============= + +.. toctree:: + :maxdepth: 2 + :titlesonly: + + Main/Index + Credentials/Index + PaymentMethod/Index + PaymentPage/Index + Webhook/Index diff --git a/Documentation/Administrator/Configuration/Main/Index.rst b/Documentation/Administrator/Configuration/Main/Index.rst new file mode 100644 index 0000000..5369a6d --- /dev/null +++ b/Documentation/Administrator/Configuration/Main/Index.rst @@ -0,0 +1,92 @@ +.. include:: ../../../Includes.rst.txt + +.. _main-configuration: + +================== +Main Configuration +================== + +The settings are site settings of the set **Cart PayPal** +(`extcode/cart-paypal`) and can be edited in the backend module *Site +Settings*. Without the site set, the same names are TypoScript constants of +the static TypoScript. + +.. code-block:: yaml + :caption: config/sites//settings.yaml + + plugin: + tx_cartpaypal: + paymentPid: 42 + brandName: 'Example Shop' + locale: de-DE + +.. code-block:: typoscript + :caption: TypoScript constants, without site set + + plugin.tx_cartpaypal { + paymentPid = 42 + brandName = Example Shop + locale = de-DE + } + +| + +.. container:: table-row + + Property + plugin.tx_cartpaypal.paymentPid + Data type + int (page) + Description + The page with the content element "Cart: PayPal payment", see + :ref:`Payment page `. With 0 the customer is redirected to + PayPal directly after the order. + Default + 0 + +.. container:: table-row + + Property + plugin.tx_cartpaypal.redirectTypeNum + Data type + int + Description + The page type of the endpoints: the webhook, the return of the customer + from PayPal and the requests of the JavaScript on the payment page. + Default + 2278101 + +.. container:: table-row + + Property + plugin.tx_cartpaypal.brandName + Data type + string + Description + The name of the shop shown by PayPal, at most 127 characters. Without a + name PayPal shows the name of the PayPal account. + +.. container:: table-row + + Property + plugin.tx_cartpaypal.locale + Data type + string + Description + The language of the PayPal pages as BCP-47 code, e.g. `de-DE`. Without a + locale PayPal chooses the language. + +.. container:: table-row + + Property + plugin.tx_cartpaypal.shippingPreference + Data type + string + Description + `NO_SHIPPING`: PayPal asks for no shipping address, Cart already has the + addresses of the order. `GET_FROM_FILE`: The customer chooses a shipping + address stored at PayPal; it is not transferred to the order. + Default + NO_SHIPPING + +The credentials are no site settings, see :ref:`Credentials `. diff --git a/Documentation/Administrator/Configuration/PaymentMethod/Index.rst b/Documentation/Administrator/Configuration/PaymentMethod/Index.rst new file mode 100644 index 0000000..d442881 --- /dev/null +++ b/Documentation/Administrator/Configuration/PaymentMethod/Index.rst @@ -0,0 +1,76 @@ +.. include:: ../../../Includes.rst.txt + +============================ +Payment Method Configuration +============================ + +The payment methods for PayPal are configured like any other payment method. +All configuration options of Cart are available. The customer chooses between +them in the cart, e.g. "PayPal" and "Credit card". + +.. code-block:: typoscript + + plugin.tx_cart { + payments { + ... + options { + 2 { + provider = PAYPAL + title = PayPal + extra = 0.00 + taxClassId = 1 + status = open + available.from = 0.01 + } + 3 { + provider = PAYPAL_CREDITCARD + title = Credit card + extra = 0.00 + taxClassId = 1 + status = open + available.from = 0.01 + } + } + ... + } + } + +| + +.. container:: table-row + + Property + plugin.tx_cart.payments....options.n.provider + Data type + string + Description + Lets Cart PayPal take over the payment of the order. + + * `PAYPAL`: The customer pays with the PayPal button and logs in at + PayPal. + * `PAYPAL_CREDITCARD`: The customer pays with a debit or credit card in + an overlay of PayPal, a PayPal account is not required. + +.. container:: table-row + + Property + plugin.tx_cart.payments....options.n.preventClearCart + Data type + boolean + Description + Cart PayPal clears the cart before the customer pays. If the customer + cancels the payment, the cart is restored. With `preventClearCart = 1` + the cart is kept. + +.. NOTE:: + + PayPal decides whether the card payment is offered, e.g. depending on the + country, the currency and the PayPal account of the shop. If it is not + offered, the payment page shows a link to PayPal instead. Check that the + payment with cards (standalone payments) is enabled in the settings of the + PayPal app. + +.. NOTE:: + + For more information and examples on how to configure payment methods, please refer to the + payment method section in the cart documentation. diff --git a/Documentation/Administrator/Configuration/PaymentPage/Index.rst b/Documentation/Administrator/Configuration/PaymentPage/Index.rst new file mode 100644 index 0000000..6c12026 --- /dev/null +++ b/Documentation/Administrator/Configuration/PaymentPage/Index.rst @@ -0,0 +1,35 @@ +.. include:: ../../../Includes.rst.txt + +.. _payment-page: + +============ +Payment page +============ + +The payment page shows the PayPal button, or the card button for the payment +method `PAYPAL_CREDITCARD`. The customer pays in a window of PayPal without +leaving the shop. + +#. Create a page, e.g. "Payment", and hide it in the menu. + +#. Add the content element **Cart: PayPal payment** to the page. + +#. Select the page in the site setting "Payment page" or set the constant + `plugin.tx_cartpaypal.paymentPid` to the uid of the page. + +The page shows the order with its products, costs and addresses next to the +PayPal button. The template `Payment/Show.html` and the partials +`Payment/OrderSummary.html` and `Payment/Addresses.html` can be overridden +like the templates of other Extbase plugins (`plugin.tx_cartpaypal.view`). +The amounts are formatted with the currency format of Cart. The element with the attribute +`data-cart-paypal-payment` and its data attributes are needed by the +JavaScript `EXT:cart_paypal/Resources/Public/JavaScript/Payment.js`. + +If PayPal can not be offered by the JavaScript SDK, e.g. for the currency, the +page shows a link which redirects the customer to PayPal instead. + +.. IMPORTANT:: + + With a Content Security Policy for the frontend, allow the PayPal JavaScript + SDK (`https://www.paypal.com`, `https://www.sandbox.paypal.com`) for + scripts, frames and connections. diff --git a/Documentation/Administrator/Configuration/Webhook/Index.rst b/Documentation/Administrator/Configuration/Webhook/Index.rst new file mode 100644 index 0000000..1b48787 --- /dev/null +++ b/Documentation/Administrator/Configuration/Webhook/Index.rst @@ -0,0 +1,28 @@ +.. include:: ../../../Includes.rst.txt + +.. _webhook: + +======= +Webhook +======= + +PayPal informs the shop about payments with webhooks. They finish the order if +the customer closes the browser after approving the payment, and if PayPal +completes a reviewed payment later. + +#. Add a webhook to the PayPal app with the URL of the page type on the cart + page, e.g. `https://example.org/cart?type=2278101`. + +#. Select the events + + * `CHECKOUT.ORDER.APPROVED` + * `PAYMENT.CAPTURE.COMPLETED` + * `PAYMENT.CAPTURE.PENDING` + * `PAYMENT.CAPTURE.DENIED` + * `PAYMENT.CAPTURE.DECLINED` + +#. Configure the id of the webhook as credential `webhookId`. + +The signature of each webhook is verified by PayPal. Webhooks of orders the +shop does not know, e.g. of another shop with the same PayPal account, are +acknowledged and ignored. diff --git a/Documentation/Administrator/Index.rst b/Documentation/Administrator/Index.rst new file mode 100644 index 0000000..476378c --- /dev/null +++ b/Documentation/Administrator/Index.rst @@ -0,0 +1,14 @@ +.. include:: ../Includes.rst.txt + +.. _administrator: + +================== +For Administrators +================== + +.. toctree:: + :maxdepth: 2 + :titlesonly: + + Installation/Index + Configuration/Index diff --git a/Documentation/Administrator/Installation/Index.rst b/Documentation/Administrator/Installation/Index.rst new file mode 100644 index 0000000..6edd667 --- /dev/null +++ b/Documentation/Administrator/Installation/Index.rst @@ -0,0 +1,62 @@ +.. include:: ../../Includes.rst.txt + +.. _installation: + +============ +Installation +============ + +Installation using Composer +--------------------------- + +The recommended way to install the extension is by using `Composer `_. +In your Composer based TYPO3 project root, just do + +`composer require extcode/cart-paypal`. + +Installation from TYPO3 Extension Repository (TER) +-------------------------------------------------- + +Download and install the extension with the extension manager module. + +Preparation: Add the site set or include the static TypoScript +-------------------------------------------------------------- + +With site sets, add the set **Cart PayPal** (`extcode/cart-paypal`) to the +site, either in the backend module *Sites* or in the `config.yaml` of the site: + +.. code-block:: yaml + + dependencies: + - extcode/cart-paypal + +The settings of the set can then be edited in the backend module *Site +Settings*, see :ref:`Main Configuration `. + +.. NOTE:: + + If the site has a TypoScript record (`sys_template`) as well, its flags + "Clear constants" and "Clear setup" must not be set, otherwise the + TypoScript of the set is discarded. + +Without site sets, include the static TypoScript: + +#. Switch to the root page of your site. + +#. Switch to the **Template module** and select *Info/Modify*. + +#. Press the link **Edit the whole template record** and switch to the tab *Includes*. + +#. Select **Shopping Cart - PayPal** at the field *Include static (from extensions):* + +Preparation: PayPal app +----------------------- + +#. Create an app in the `PayPal Developer Dashboard `_, + one for the sandbox and one for live. + +#. Configure the client id and the secret of the app as + :ref:`credentials `. + +#. Add a webhook to the app, see :ref:`Webhook `, and configure its id + as credential as well. diff --git a/Documentation/AdministratorManual/Configuration/Index.rst b/Documentation/AdministratorManual/Configuration/Index.rst deleted file mode 100644 index 8ea634e..0000000 --- a/Documentation/AdministratorManual/Configuration/Index.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. include:: ../../Includes.txt - -Configuration -============= - -.. toctree:: - :maxdepth: 5 - :titlesonly: - - Main/Index - PaymentMethod/Index diff --git a/Documentation/AdministratorManual/Configuration/Main/Index.rst b/Documentation/AdministratorManual/Configuration/Main/Index.rst deleted file mode 100644 index 7a7bb58..0000000 --- a/Documentation/AdministratorManual/Configuration/Main/Index.rst +++ /dev/null @@ -1,53 +0,0 @@ -.. include:: ../../../Includes.txt - -Main Configuration -================== - -.. IMPORTANT:: - The EventListeners are configured for the new Feature "Split Up ProcessOrderCreateEvent" in extcode/cart v7.2.0. - The feature must be switched on and, if necessary, own event listeners must be adapted to these new events. - For more information, please read the cart documentation: - - * `Feature-337-SplitUpProcessOrderCreateEvent `__ - * `Deprecation-337-SplitUpProcessOrderCreateEvent `__ - -The plugin needs to know the merchant e-mail address. - -:: - - plugin.tx_cartpaypal { - sandbox = 1 - business = pp-wt-merchant@extco.de - debug = 1 - } - -| - -.. container:: table-row - - Property - plugin.tx_cartpaypal.sandbox - Data type - boolean - Description - This configuration determines whether the extension is in live or in sandbox mode. - Default - The default value is chosen so that the plugin is always in sandbox mode after installation, so that payment can be tested with PayPal. - -.. container:: table-row - - Property - plugin.tx_cartpaypal.business - Data type - string - Description - The e-mail address stored in the PayPal business account must be entered here. - -.. container:: table-row - - Property - plugin.tx_cartpaypal.debug - Data type - boolean - Description - Enables the logging for some debug messages. \ No newline at end of file diff --git a/Documentation/AdministratorManual/Configuration/PaymentMethod/Index.rst b/Documentation/AdministratorManual/Configuration/PaymentMethod/Index.rst deleted file mode 100644 index 110d842..0000000 --- a/Documentation/AdministratorManual/Configuration/PaymentMethod/Index.rst +++ /dev/null @@ -1,36 +0,0 @@ -.. include:: ../../../Includes.txt - -Payment Method Configuration -============================ - -The payment method for PayPal is configured like any other payment method. There are all configuration options -from Cart available. - -:: - - plugin.tx_cart { - payments { - options { - 2 { - provider = PAYPAL - title = Paypal - extra = 0.00 - taxClassId = 1 - status = open - } - } - } - } - -| - -.. container:: table-row - - Property - plugin.tx_cart.payments.options.n.provider - Data type - string - Description - Defines that the payment provider for PayPal should be used. - This information is mandatory and ensures that the extension Cart PayPal takes control and for the authorization - of payment the user forwards to the PayPal site. diff --git a/Documentation/AdministratorManual/Index.rst b/Documentation/AdministratorManual/Index.rst deleted file mode 100644 index 6ce92e5..0000000 --- a/Documentation/AdministratorManual/Index.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. include:: ../Includes.txt - -Administrator Manual -==================== - -.. toctree:: - :maxdepth: 5 - :titlesonly: - - Installation/Index - Configuration/Index diff --git a/Documentation/AdministratorManual/Installation/Index.rst b/Documentation/AdministratorManual/Installation/Index.rst deleted file mode 100644 index 067c31c..0000000 --- a/Documentation/AdministratorManual/Installation/Index.rst +++ /dev/null @@ -1,38 +0,0 @@ -.. include:: ../../Includes.txt - -Installation -============ - -Installation using Composer ---------------------------- - -The recommended way to install the extension is by using `Composer `_. -In your Composer based TYPO3 project root, just do - -`composer require extcode/cart-paypal`. - -Installation from TYPO3 Extension Repository (TER) --------------------------------------------------- - -Download and install the extension with the extension manager module. - -Latest version from git ------------------------ -You can get the latest version from git by using the git command: - -.. code-block:: bash - - git clone git@github.com:extcode/cart_paypal.git - -Preparation: Include static TypoScript --------------------------------------- - -The extension ships some TypoScript code which needs to be included. - -#. Switch to the root page of your site. - -#. Switch to the **Template module** and select *Info/Modify*. - -#. Press the link **Edit the whole template record** and switch to the tab *Includes*. - -#. Select **Shopping Cart - PayPal** at the field *Include static (from extensions):* diff --git a/Documentation/Changelog/3.0/Index.rst b/Documentation/Changelog/3.0/Index.rst index bee315d..06eac98 100644 --- a/Documentation/Changelog/3.0/Index.rst +++ b/Documentation/Changelog/3.0/Index.rst @@ -1,4 +1,4 @@ -.. include:: ../../Includes.txt +.. include:: ../../Includes.rst.txt 3.0 Changes =========== diff --git a/Documentation/Changelog/4.0/Index.rst b/Documentation/Changelog/4.0/Index.rst index b984555..0aa4922 100644 --- a/Documentation/Changelog/4.0/Index.rst +++ b/Documentation/Changelog/4.0/Index.rst @@ -1,4 +1,4 @@ -.. include:: ../../Includes.txt +.. include:: ../../Includes.rst.txt 4.0 Changes =========== diff --git a/Documentation/Changelog/5.0/Index.rst b/Documentation/Changelog/5.0/Index.rst index a1eddd1..78b1d16 100644 --- a/Documentation/Changelog/5.0/Index.rst +++ b/Documentation/Changelog/5.0/Index.rst @@ -1,4 +1,4 @@ -.. include:: ../../Includes.txt +.. include:: ../../Includes.rst.txt 5.0 Changes =========== diff --git a/Documentation/Changelog/6.0/Index.rst b/Documentation/Changelog/6.0/Index.rst index 3999add..53d6a68 100644 --- a/Documentation/Changelog/6.0/Index.rst +++ b/Documentation/Changelog/6.0/Index.rst @@ -1,4 +1,4 @@ -.. include:: ../../Includes.txt +.. include:: ../../Includes.rst.txt 6.0 Changes =========== diff --git a/Documentation/Changelog/8.0/Index.rst b/Documentation/Changelog/8.0/Index.rst new file mode 100644 index 0000000..f3d7b03 --- /dev/null +++ b/Documentation/Changelog/8.0/Index.rst @@ -0,0 +1,38 @@ +.. include:: ../../Includes.rst.txt + +=========== +8.0 Changes +=========== + +The version 8.x is a release for TYPO3 v13.4 and extcode/cart 11.x. It is a +rewrite, nothing of the previous versions is kept. + +Breaking +======== + +* The payment uses the PayPal Orders v2 API instead of PayPal Payments + Standard and IPN. The PayPal account needs an app with client id and secret, + see :ref:`Credentials `. The setting `business` is gone. +* The settings `sendEachItemToPaypal`, `sendEachItemToPaypalTitle`, `debug` + and `curl_timeout` are gone. PayPal gets the total of the order only. +* The events `SuccessEvent` and `NotifyEvent` are replaced by + `\Extcode\CartPaypal\Event\Order\FinishEvent`, see :ref:`Events `. +* The actions `success`, `cancel` and `notify` of the plugin `Cart` are + replaced by the plugin `Api`. Old IPN URLs are no longer answered. + +Features +======== + +* The payment page shows the PayPal button of the PayPal JavaScript SDK v6, + see :ref:`Payment page `. +* The payment method `PAYPAL_CREDITCARD` lets the customer pay with a debit + or credit card without a PayPal account. +* Webhooks finish the order if the customer does not return to the shop, see + :ref:`Webhook `. +* The PayPal order is stored as transaction of the payment, no field is added + to the tables of Cart. +* The settings are available as site settings of the site set + `extcode/cart-paypal`, see :ref:`Main Configuration `. +* The credentials are read from `$GLOBALS['TYPO3_CONF_VARS']`, e.g. set from + environment variables, or per site from the site configuration, see + :ref:`Credentials `. diff --git a/Documentation/Changelog/Index.rst b/Documentation/Changelog/Index.rst index f722ac7..43155ec 100644 --- a/Documentation/Changelog/Index.rst +++ b/Documentation/Changelog/Index.rst @@ -1,12 +1,13 @@ -.. include:: ../Includes.txt +.. include:: ../Includes.rst.txt ChangeLog ========= .. toctree:: - :maxdepth: 5 + :maxdepth: 3 :titlesonly: + 8.0/Index 6.0/Index 5.0/Index 4.0/Index diff --git a/Documentation/Developer/Credentials/CredentialsFromOwnCredentialLoader.rst b/Documentation/Developer/Credentials/CredentialsFromOwnCredentialLoader.rst new file mode 100644 index 0000000..f5184d4 --- /dev/null +++ b/Documentation/Developer/Credentials/CredentialsFromOwnCredentialLoader.rst @@ -0,0 +1,17 @@ +.. include:: ../../Includes.rst.txt + +.. _credentials-from-own-credentialloader: + +===================================== +Credentials from own CredentialLoader +===================================== + +If the credentials are to be saved in a different location, a separate configuration loader +can provide the configuration. It is sufficient if this implements the +`\Extcode\CartPaypal\Configuration\CredentialLoaderInterface`. +The loader is automatically registered via the interface. + +The loaders are called in the order of their `getDefaultPriority()`, the +credentials of a loader with a higher priority take precedence. The +credentials from the site configuration have the priority 40, the credentials +from `$GLOBALS['TYPO3_CONF_VARS']` the priority 30. diff --git a/Documentation/Developer/Events/Index.rst b/Documentation/Developer/Events/Index.rst new file mode 100644 index 0000000..f4b34ed --- /dev/null +++ b/Documentation/Developer/Events/Index.rst @@ -0,0 +1,19 @@ +.. include:: ../../Includes.rst.txt + +.. _events: + +====== +Events +====== + +Cart PayPal stops the `\Extcode\Cart\Event\Order\PaymentEvent` of Cart, so the +`\Extcode\Cart\Event\Order\FinishEvent` of Cart is not dispatched. Instead +Cart PayPal dispatches its own events after the payment. + +`\Extcode\CartPaypal\Event\Order\FinishEvent` + Dispatched once when the payment is completed. Cart PayPal registers the + email listener of Cart for it. + +`\Extcode\CartPaypal\Event\Order\CancelEvent` + Dispatched once when the customer cancels the payment and returns to the + cart. diff --git a/Documentation/Developer/Index.rst b/Documentation/Developer/Index.rst new file mode 100644 index 0000000..7eb3a73 --- /dev/null +++ b/Documentation/Developer/Index.rst @@ -0,0 +1,16 @@ +.. include:: ../Includes.rst.txt + +.. _developer: + +============== +For Developers +============== + +Information for developer how to extend the extension. + +.. toctree:: + :maxdepth: 2 + :titlesonly: + + Events/Index + Credentials/CredentialsFromOwnCredentialLoader diff --git a/Documentation/Includes.rst.txt b/Documentation/Includes.rst.txt new file mode 100644 index 0000000..2362507 --- /dev/null +++ b/Documentation/Includes.rst.txt @@ -0,0 +1 @@ +.. You can put central messages to display on all pages here diff --git a/Documentation/Includes.txt b/Documentation/Includes.txt deleted file mode 100644 index 3fb69af..0000000 --- a/Documentation/Includes.txt +++ /dev/null @@ -1,20 +0,0 @@ -.. This is 'Includes.txt'. It is included at the very top of each and - every ReST source file in THIS documentation project (= manual). - -.. role:: aspect (emphasis) -.. role:: html(code) -.. role:: js(code) -.. role:: php(code) -.. role:: typoscript(code) -.. role:: typescript(code) -.. role:: shell(code) -.. role:: sql(code) -.. role:: yaml(code) - -.. role:: ts(typoscript) - :class: typoscript -.. role:: javascript(js) - :class: js - -.. default-role:: code -.. highlight:: php diff --git a/Documentation/Index.rst b/Documentation/Index.rst index 76bbecf..14a5d7d 100644 --- a/Documentation/Index.rst +++ b/Documentation/Index.rst @@ -1,20 +1,23 @@ -.. include:: Includes.txt +.. include:: Includes.rst.txt .. _start: -================ -EXT: Cart Paypal -================ +=========== +Cart PayPal +=========== .. image:: Images/cart_paypal_logo.png - :height: 200 - :width: 200 + :height: 100 + :width: 100 .. only:: html - :Classification: - cart + :Extension key: + cart_paypal + + :Package name: + extcode/cart-paypal :Version: |release| @@ -22,35 +25,48 @@ EXT: Cart Paypal :Language: en - :Description: - Cart is a small but powerful extension which "solely" adds a shopping cart to your TYPO3 installation. - Cart PayPal is a payment provider and implements the PayPal IPN message service. - - :Keywords: - cart, shop, shopping, e-commerce, ecommerce, checkout, payment, paypal - - :Autor: - Daniel Gohlke - - :E-Mail: - ext.cart@extco.de + :Author: + Daniel Gohlke & Contributors :License: - This document is published under the Open Publication License - available from http://www.opencontent.org/openpub/ + This document is published under the + `Open Publication License `__. :Rendered: |today| - The content of this document is related to TYPO3, - a GNU/GPL CMS/Framework available from `www.typo3.org `__. +----- + +Cart PayPal is a payment provider for Cart and implements the payment with +PayPal using the Orders v2 API and the PayPal JavaScript SDK v6. + +----- + +.. card-grid:: + :columns: 1 + :columns-md: 2 + :gap: 4 + :class: pb-4 + :card-height: 100 + + .. card:: :ref:`Introduction ` + + Introduction to the extension, general information. + + .. card:: :ref:`For Administrators ` + + Install the extension and configure it correctly. + + .. card:: :ref:`For Developers ` + + Information about the events and the credentials. - **Table of Contents** .. toctree:: - :maxdepth: 5 + :maxdepth: 2 :titlesonly: Introduction/Index - AdministratorManual/Index - Changelog/Index \ No newline at end of file + Administrator/Index + Developer/Index + Changelog/Index diff --git a/Documentation/Introduction/Index.rst b/Documentation/Introduction/Index.rst index 1cde97f..2d9fb24 100644 --- a/Documentation/Introduction/Index.rst +++ b/Documentation/Introduction/Index.rst @@ -1,15 +1,41 @@ -.. include:: ../Includes.txt +.. include:: ../Includes.rst.txt +.. _introduction: + +============ Introduction ------------- +============ Cart is a small but powerful extension which "solely" adds a shopping cart to your TYPO3 installation. -Cart PayPal is a payment provider and implements the PayPal IPN message service. +Cart PayPal is a payment provider and implements the payment with PayPal. + +How the payment works +===================== + +#. The customer orders with the payment method PayPal. Cart stores the order, + Cart PayPal stores the cart and sends the customer to the payment page. +#. The payment page shows the PayPal button of the PayPal JavaScript SDK, or + the card button if the customer chose to pay by card. When the customer + clicks it, the shop creates the order at PayPal with the total + of the stored order. The browser never sends an amount. +#. The customer approves the payment in the PayPal window. The shop captures + the payment and shows the order confirmation of Cart. +#. A webhook of PayPal finishes the order if the customer closes the browser + after approving the payment, and reports payments which are reviewed by + PayPal first. + +Without a payment page, or if the JavaScript can not be used, the customer is +redirected to PayPal and returns to the shop after approving the payment. + +Each order at PayPal is stored as transaction of the payment of the order. The +id of the PayPal order is the transaction id, the id of the capture is stored +as note. No further database fields are needed. + +The emails of Cart are sent after the payment is completed. .. toctree:: - :maxdepth: 5 + :maxdepth: 2 :titlesonly: Support/Index Sponsoring/Index - NoteOfThanks/Index diff --git a/Documentation/Introduction/NoteOfThanks/Index.rst b/Documentation/Introduction/NoteOfThanks/Index.rst deleted file mode 100644 index 507ee01..0000000 --- a/Documentation/Introduction/NoteOfThanks/Index.rst +++ /dev/null @@ -1,4 +0,0 @@ -.. include:: ../../Includes.txt - -Note of thanks -============== diff --git a/Documentation/Introduction/Sponsoring/Index.rst b/Documentation/Introduction/Sponsoring/Index.rst index 135965d..61064bb 100644 --- a/Documentation/Introduction/Sponsoring/Index.rst +++ b/Documentation/Introduction/Sponsoring/Index.rst @@ -1,4 +1,4 @@ -.. include:: ../../Includes.txt +.. include:: ../../Includes.rst.txt Sponsoring ========== @@ -10,7 +10,3 @@ There is also the possibility to support the further development independently o * Ask for an invoice. * `GitHub Sponsors `_ * `paypal.me `_ -* `patreon.com `_ - -Sponsors --------- diff --git a/Documentation/Introduction/Support/Index.rst b/Documentation/Introduction/Support/Index.rst index eeef55f..1a158fa 100644 --- a/Documentation/Introduction/Support/Index.rst +++ b/Documentation/Introduction/Support/Index.rst @@ -1,11 +1,11 @@ -.. include:: ../../Includes.txt +.. include:: ../../Includes.rst.txt Support ======= Slack ----- -There is an own channel at the TYPO3 Slack. Please use this cannel to contact us. +There is an own channel at the TYPO3 Slack. Please use this channel to contact us. The URL is: https://typo3.slack.com/messages/ext-cart/ diff --git a/Documentation/Settings.cfg b/Documentation/Settings.cfg deleted file mode 100644 index 5314ff7..0000000 --- a/Documentation/Settings.cfg +++ /dev/null @@ -1,20 +0,0 @@ -[general] - -project = Cart PayPal -version = 6.0 -release = 6.0.0 -t3author = Daniel Gohlke -copyright = 2021-2024 - -[html_theme_options] - -project_issues = https://github.com/extcode/cart_paypal/issues -project_repository = https://github.com/extcode/cart_paypal - -[extlinks] - -issue = https://github.com/extcode/cart/issues/%s | Issue # - -[intersphinx_mapping] - -t3tsref = https://docs.typo3.org/typo3cms/TyposcriptReference/ diff --git a/Documentation/guides.xml b/Documentation/guides.xml new file mode 100644 index 0000000..fe3a16b --- /dev/null +++ b/Documentation/guides.xml @@ -0,0 +1,19 @@ + + + + + + diff --git a/README.md b/README.md index 57802cb..8008769 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,41 @@ # Cart PayPal Cart is a small but powerful extension which "solely" adds a shopping cart to your TYPO3 installation. -Cart PayPal is a payment provider and implements the PayPal IPN message service. +Cart PayPal is a payment provider. -## 1. Features - -- -- -- - -## 2. Installation / Upgrade - -### 2.1 Installation +Read the [extension documentation](https://docs.typo3.org/p/extcode/cart-paypal/main/en-us/). -#### Installation using Composer - -The recommended way to install the extension is by using [Composer][2]. In your Composer based TYPO3 project root, just do `composer require extcode/cart-paypal`. - -#### Installation as extension from TYPO3 Extension Repository (TER) +## 1. Features -Download and install the extension with the extension manager module. +- Shows the PayPal button of the PayPal JavaScript SDK on a payment page. +- Creates and captures the payment with the PayPal Orders v2 API on the server. +- Redirects the customer to PayPal if no payment page is configured. +- Finishes the order with PayPal webhooks if the customer does not return to the shop. -### 2.2 Upgrade +## 2. Installation -**If upgrading from cart version 4.8.1 or earlier: Please read the documentation very carefully! Please make a backup of your filesystem -and database!** If possible test the update in a test copy of your TYPO3 instance. +Please have a look into the [installation chapter of the documentation](https://docs.typo3.org/p/extcode/cart-paypal/main/en-us/Administrator/Installation/Index.html). -## 3. Administration +## 3. Versions -## 3.1 Compatibility and supported Versions +### 3.1 Compatibility and supported versions -| Cart PayPal | TYPO3 | PHP | Support/Development | -|---------------| ---------- | ----------|--------------------------------------| -| 6.x.x | 10.4, 11.5 | 7.2+ | Features, Bugfixes, Security Updates | -| 5.x.x | 10.4 | 7.2 - 7.4 | Bugfixes, Security Updates | -| 4.x.x | 9.5 | 7.2 - 7.4 | Security Updates | -| 3.x.x | 8.7 | 7.0 - 7.4 | | -| 2.x.x | 6.2 - 8.7 | 5.6 - 7.0 | | -| 1.x.x | | | | +The compatibility with TYPO3 and PHP and the support status of all versions are listed in the +[official extension documentation in chapter supported versions](https://docs.typo3.org/p/extcode/cart-paypal/main/en-us/Introduction/SupportedVersions/Index.html). -### 3.2. Changelog +If you need extended support for features and bug fixes outside of the currently supported versions, +we are happy to offer paid services. -Please have a look into the [official extension documentation in changelog chapter](https://docs.typo3.org/p/extcode/cart_paypal/main/en-us/Changelog/Index.html) +### 3.2 Changelog -### 3.3. Release Management +Please have a look into the [official extension documentation in changelog chapter](https://docs.typo3.org/p/extcode/cart-paypal/main/en-us/Changelog/Index.html) -News uses **semantic versioning** which basically means for you, that -- **bugfix updates** (e.g. 1.0.0 => 1.0.1) just includes small bugfixes or security relevant stuff without breaking changes. -- **minor updates** (e.g. 1.0.0 => 1.1.0) includes new features and smaller tasks without breaking changes. -- **major updates** (e.g. 1.0.0 => 2.0.0) breaking changes wich can be refactorings, features or bugfixes. +**Attention:** Before updating to a new minor version or upgrading to a new major version, be sure to check the +changelog section in the documentation. +Sometimes minor versions also result in minor adjustments to own templates or configurations. ## 4. Sponsoring * Ask for an invoice. * [GitHub Sponsors](https://github.com/sponsors/extcode) * [PayPal.Me](https://paypal.me/extcart) -* [Patreon](https://patreon.com/ext_cart) - -[1]: https://docs.typo3.org/typo3cms/extensions/cart_paypal/ -[2]: https://getcomposer.org/ \ No newline at end of file diff --git a/Resources/Private/.htaccess b/Resources/Private/.htaccess deleted file mode 100644 index dfc0272..0000000 --- a/Resources/Private/.htaccess +++ /dev/null @@ -1 +0,0 @@ -deny from all \ No newline at end of file diff --git a/Resources/Private/Language/de.locallang.xlf b/Resources/Private/Language/de.locallang.xlf deleted file mode 100644 index 133e54a..0000000 --- a/Resources/Private/Language/de.locallang.xlf +++ /dev/null @@ -1,32 +0,0 @@ - - - -
- - - The order was successfully paid. - Die Bestellung wurde erfolgreich bezahlt. - - - An error occurred while updating the order. - Es ist ein Fehler bei der Aktualisierung der Bestellung aufgetreten. - - - Access denied! - Access denied! - - - The order has been canceled. - Die Bestellung wurde abgebrochen. - - - An error occurred while updating the order. - Es ist ein Fehler bei der Aktualisierung der Bestellung aufgetreten. - - - Access denied! - Access denied! - - - - diff --git a/Resources/Private/Language/de.locallang_db.xlf b/Resources/Private/Language/de.locallang_db.xlf deleted file mode 100644 index 9bc2ea0..0000000 --- a/Resources/Private/Language/de.locallang_db.xlf +++ /dev/null @@ -1,46 +0,0 @@ - - - -
- - - - completed - completed - - - created - created - - - denied - denied - - - expired - expired - - - failed - failed - - - refunded - refunded - - - reversed - reversed - - - processed - processed - - - voided - voided - - - - - \ No newline at end of file diff --git a/Resources/Private/Language/locallang.xlf b/Resources/Private/Language/locallang.xlf index 5448ed5..743bfe2 100644 --- a/Resources/Private/Language/locallang.xlf +++ b/Resources/Private/Language/locallang.xlf @@ -1,26 +1,92 @@ - - + +
- - The order was successfully paid. + + + Pay for your order - - An error occurred while updating the order. + + Your order %1$s has been placed. Please complete it with the payment via PayPal. - - Access denied! + + Amount due + + + You log in and approve the payment in a window of PayPal. Your order is completed as soon as the payment is received. + + + You enter your debit or credit card in a window of PayPal, a PayPal account is not required. Your order is completed as soon as the payment is received. + + + Your order + + + Product + + + Quantity + + + Price + + + Subtotal + + + Shipping (%1$s) + + + Payment fee (%1$s) + + + Total + + + Billing address + + + Shipping address + + + Same as billing address + + + Continue to PayPal + + + Cancel the payment and return to the cart + + + Return to the cart + + + The payment was not completed. Please try again. + + + The payment of this order was canceled. + + + The order could not be found. + + + + The payment process was aborted. + + + PayPal declined the payment. Please choose another payment method at PayPal or in the cart. - - The order has been canceled. + + An error occurred during the payment with PayPal. Please try again later. - - An error occurred while updating the order. + + The order can not be paid (anymore). - + Access denied! + diff --git a/Resources/Private/Language/locallang_db.xlf b/Resources/Private/Language/locallang_db.xlf index 765e7c9..5af78f4 100644 --- a/Resources/Private/Language/locallang_db.xlf +++ b/Resources/Private/Language/locallang_db.xlf @@ -1,37 +1,14 @@ - - + +
- - - completed + + Cart: PayPal payment - - created + + Shows the PayPal button for an order. Place it on the page configured as plugin.tx_cartpaypal.paymentPid. - - denied - - - expired - - - failed - - - refunded - - - reversed - - - processed - - - voided - - - \ No newline at end of file + diff --git a/Resources/Private/Layouts/Default.html b/Resources/Private/Layouts/Default.html index 1bbd2ea..2ff8aa2 100644 --- a/Resources/Private/Layouts/Default.html +++ b/Resources/Private/Layouts/Default.html @@ -1,3 +1,7 @@ + +
-
\ No newline at end of file + + \ No newline at end of file diff --git a/Resources/Private/Partials/Payment/Addresses.html b/Resources/Private/Partials/Payment/Addresses.html new file mode 100644 index 0000000..606348a --- /dev/null +++ b/Resources/Private/Partials/Payment/Addresses.html @@ -0,0 +1,33 @@ + + +
+
+

+ +
+
+

+ + + + + +

+
+
+
+
+ + +
+ {address.company}
+ {address.firstName} {address.lastName}
+ {address.street} {address.streetNumber}
+ {address.zip} {address.city}
+ + + +
+
+ diff --git a/Resources/Private/Partials/Payment/OrderSummary.html b/Resources/Private/Partials/Payment/OrderSummary.html new file mode 100644 index 0000000..5a7e25e --- /dev/null +++ b/Resources/Private/Partials/Payment/OrderSummary.html @@ -0,0 +1,74 @@ + + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ {product.title} + +
{product.sku} +
+
{product.count} + {product.gross} +
+ {orderItem.gross} +
{discount.title} + {discount.gross} +
+ + + {orderItem.shipping.gross} +
+ + + {orderItem.payment.gross} +
+ {orderItem.totalGross} +
+ diff --git a/Resources/Private/Templates/Order/Payment/Cancel.html b/Resources/Private/Templates/Order/Payment/Cancel.html deleted file mode 100644 index fcb9b98..0000000 --- a/Resources/Private/Templates/Order/Payment/Cancel.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - -
- -
-
-
diff --git a/Resources/Private/Templates/Order/Payment/Confirm.html b/Resources/Private/Templates/Order/Payment/Confirm.html deleted file mode 100644 index fedd8a4..0000000 --- a/Resources/Private/Templates/Order/Payment/Confirm.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - -
- -
-
- -
-
-
diff --git a/Resources/Private/Templates/Order/Payment/Notify.html b/Resources/Private/Templates/Order/Payment/Notify.html deleted file mode 100644 index fcb9b98..0000000 --- a/Resources/Private/Templates/Order/Payment/Notify.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - -
- -
-
-
diff --git a/Resources/Private/Templates/Order/Payment/Success.html b/Resources/Private/Templates/Order/Payment/Success.html deleted file mode 100644 index fedd8a4..0000000 --- a/Resources/Private/Templates/Order/Payment/Success.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - -
- -
-
- -
-
-
diff --git a/Resources/Private/Templates/Payment/Show.html b/Resources/Private/Templates/Payment/Show.html new file mode 100644 index 0000000..be17c95 --- /dev/null +++ b/Resources/Private/Templates/Payment/Show.html @@ -0,0 +1,109 @@ + + + + + + + + + + + + +
+ +
+

+ + + +

+
+ +
+ +
+
+
+
+ + +
+

+

+ +

+ +
+
+ + +
+ +
+
+
+

+ +

+

+ {orderItem.totalGross} +

+ + + + + + + + + + + + + + + + + +

+ +

+
+ +
+
+
+
+ + +
+ diff --git a/Resources/Public/JavaScript/Payment.js b/Resources/Public/JavaScript/Payment.js new file mode 100644 index 0000000..8db1e66 --- /dev/null +++ b/Resources/Public/JavaScript/Payment.js @@ -0,0 +1,164 @@ +/* + * This file is part of the package extcode/cart-paypal. + * + * For the full copyright and license information, please read the + * LICENSE file that was distributed with this source code. + */ + +/** + * Shows the button of the PayPal JavaScript SDK v6 on the payment page: the + * PayPal button, or the card button for a debit or credit card without a + * PayPal account. + * + * The order is created and captured by the server, the browser only passes + * the id of the PayPal order. The amount is never sent by the browser. + * If the SDK can not be used, a link sends the customer to PayPal instead. + */ +(() => { + 'use strict'; + + const container = document.querySelector('[data-cart-paypal-payment]'); + if (!container) { + return; + } + + const config = container.dataset; + const message = container.querySelector('[data-cart-paypal-message]'); + const fallback = container.querySelector('[data-cart-paypal-fallback]'); + + const paymentMethods = { + paypal: { + component: 'paypal-payments', + eligibility: 'paypal', + button: 'paypal-button', + createSession: (sdkInstance, callbacks) => sdkInstance.createPayPalOneTimePaymentSession(callbacks), + }, + card: { + component: 'paypal-guest-payments', + eligibility: 'card', + button: 'paypal-basic-card-button', + createSession: (sdkInstance, callbacks) => sdkInstance.createPayPalGuestOneTimePaymentSession({ + ...callbacks, + // a declined card is reported in the overlay, the customer may correct it there + onWarn: () => {}, + onComplete: () => {}, + }), + }, + }; + const paymentMethod = paymentMethods[config.paymentMethod] || paymentMethods.paypal; + const button = container.querySelector(paymentMethod.button); + + const showMessage = (text) => { + message.textContent = text || config.messageError; + message.hidden = false; + }; + + const hideMessage = () => { + message.hidden = true; + }; + + const showFallback = () => { + if (button) { + button.hidden = true; + } + fallback.hidden = false; + }; + + const loadSdk = () => new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.src = config.sdkUrl; + script.async = true; + script.onload = resolve; + script.onerror = reject; + document.head.appendChild(script); + }); + + const postJson = async (url, body) => { + const response = await fetch(url, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body || {}), + }); + + const data = await response.json().catch(() => ({})); + if (!response.ok) { + const error = new Error(data.message || response.statusText); + error.userMessage = data.message; + throw error; + } + + return data; + }; + + const createOrder = async () => { + const data = await postJson(config.createOrderUrl); + + return { orderId: data.orderId }; + }; + + const onApprove = async ({ orderId }) => { + try { + const data = await postJson(config.captureOrderUrl, { orderId }); + if (data.redirectUrl) { + window.location.assign(data.redirectUrl); + return; + } + showMessage(data.message); + } catch (error) { + showMessage(error.userMessage); + } + }; + + const init = async () => { + if (!config.clientId || !button) { + showFallback(); + return; + } + + await loadSdk(); + + const options = { + clientId: config.clientId, + components: [paymentMethod.component], + pageType: 'checkout', + }; + if (config.locale) { + options.locale = config.locale; + } + const sdkInstance = await window.paypal.createInstance(options); + + const eligibility = await sdkInstance.findEligibleMethods({ + currencyCode: config.currencyCode, + amount: config.amount, + }); + if (!eligibility.isEligible(paymentMethod.eligibility)) { + showFallback(); + return; + } + + const session = await paymentMethod.createSession(sdkInstance, { + onApprove, + onCancel: () => showMessage(config.messageCanceled), + onError: () => showMessage(config.messageError), + }); + + button.addEventListener('click', async () => { + hideMessage(); + try { + // not awaited before start(), the window needs the click of the customer + const orderPromise = createOrder(); + await session.start({ presentationMode: 'auto' }, orderPromise); + } catch (error) { + showMessage(error.userMessage); + } + }); + + button.hidden = false; + }; + + init().catch(() => showFallback()); +})(); diff --git a/Tests/Functional/AbstractPayPalTestCase.php b/Tests/Functional/AbstractPayPalTestCase.php new file mode 100644 index 0000000..601dc9e --- /dev/null +++ b/Tests/Functional/AbstractPayPalTestCase.php @@ -0,0 +1,260 @@ + 'typo3conf/sites', + ]; + + protected array $configurationToUseInTestInstance = [ + 'EXTENSIONS' => [ + 'cart_paypal' => [ + 'credentials' => [ + 'clientId' => 'client-id', + 'clientSecret' => 'client-secret', + 'webhookId' => 'webhook-id', + ], + ], + ], + 'FE' => [ + 'cacheHash' => [ + 'enforceValidation' => false, + ], + ], + 'MAIL' => [ + 'transport' => 'null', + ], + ]; + + protected function setUp(): void + { + parent::setUp(); + + $this->importPHPDataSet(__DIR__ . '/Fixtures/DataSets/Base.php'); + $this->importPHPDataSet(__DIR__ . '/Fixtures/DataSets/Order.php'); + + $cart = new Cart([]); + $cart->setBillingCountry('de'); + $cart->setOrderNumber('ORD-2026-0001'); + + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_cart') + ->insert('tx_cart_domain_model_cart', [ + 'uid' => 1, + 'pid' => 2, + 's_hash' => self::CART_HASH, + 'f_hash' => self::CART_FAILURE_HASH, + 'order_item' => 1, + 'serialized_cart' => serialize($cart), + ]); + + EventRecorder::reset(); + PayPalApiMock::reset(); + } + + protected function tearDown(): void + { + self::assertSame([], PayPalApiMock::getUnusedResponses(), 'Not all prepared responses of PayPal were requested.'); + + parent::tearDown(); + } + + /** + * Calls an endpoint of the Api plugin on the page type of cart_paypal. + * + * @param string|null $hash null omits the hash argument + */ + protected function callApi( + string $action, + string $method = 'GET', + string $body = '', + array $queryParameters = [], + ?string $hash = self::CART_HASH, + array $headers = [], + ): ResponseInterface { + $pluginArguments = []; + if ($action !== '') { + $pluginArguments['tx_cartpaypal_api[controller]'] = 'Api'; + $pluginArguments['tx_cartpaypal_api[action]'] = $action; + } + if ($hash !== null) { + $pluginArguments['tx_cartpaypal_api[hash]'] = $hash; + } + + $request = (new InternalRequest('http://localhost/')) + ->withPageId(1) + ->withQueryParameters(['type' => self::TYPE_NUM] + $pluginArguments + $queryParameters) + ->withMethod($method); + + if ($body !== '') { + $stream = new Stream('php://temp', 'rw'); + $stream->write($body); + $stream->rewind(); + $request = $request->withBody($stream)->withHeader('Content-Type', 'application/json'); + } + foreach ($headers as $name => $value) { + $request = $request->withHeader($name, $value); + } + + return $this->executeFrontendSubRequest($request); + } + + protected function decodeJson(ResponseInterface $response): array + { + $data = json_decode((string)$response->getBody(), true); + self::assertIsArray($data, 'The response is no JSON: ' . $response->getBody()); + + return $data; + } + + /** + * Stores the PayPal order the customer has approved as transaction. + */ + protected function addTransaction(string $status = 'created'): void + { + $connectionPool = $this->get(ConnectionPool::class); + $connectionPool + ->getConnectionForTable('tx_cart_domain_model_order_transaction') + ->insert('tx_cart_domain_model_order_transaction', [ + 'uid' => 1, + 'pid' => 2, + 'payment' => 1, + 'txn_id' => self::PAYPAL_ORDER_ID, + 'status' => $status, + 'external_status_code' => 'PAYER_ACTION_REQUIRED', + ]); + $connectionPool + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->update('tx_cart_domain_model_order_payment', ['transactions' => 1], ['uid' => 1]); + } + + protected function setPaymentStatus(string $status): void + { + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->update('tx_cart_domain_model_order_payment', ['status' => $status], ['uid' => 1]); + } + + protected function setPaymentProvider(string $provider): void + { + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->update('tx_cart_domain_model_order_payment', ['provider' => $provider], ['uid' => 1]); + } + + protected function setPaymentPid(int $paymentPid): void + { + $connection = $this->get(ConnectionPool::class)->getConnectionForTable('sys_template'); + $constants = (string)$connection->select(['constants'], 'sys_template', ['uid' => 1])->fetchOne(); + $connection->update( + 'sys_template', + ['constants' => str_replace('plugin.tx_cartpaypal.paymentPid = 3', 'plugin.tx_cartpaypal.paymentPid = ' . $paymentPid, $constants)], + ['uid' => 1] + ); + } + + protected function getPaymentStatus(): string + { + return (string)$this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->select(['status'], 'tx_cart_domain_model_order_payment', ['uid' => 1]) + ->fetchOne(); + } + + /** + * @return list> + */ + protected function getTransactions(): array + { + return $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_transaction') + ->select( + ['payment', 'txn_id', 'status', 'external_status_code', 'note'], + 'tx_cart_domain_model_order_transaction', + [], + [], + ['uid' => 'ASC'] + ) + ->fetchAllAssociative(); + } + + /** + * The response of the Orders v2 API with the capture of the order. + */ + protected static function capturedOrder(string $captureStatus = 'COMPLETED', string $value = '119.00'): array + { + return [ + 'id' => self::PAYPAL_ORDER_ID, + 'status' => $captureStatus === 'COMPLETED' ? 'COMPLETED' : 'APPROVED', + 'purchase_units' => [ + [ + 'payments' => [ + 'captures' => [ + self::capture($captureStatus, $value), + ], + ], + ], + ], + ]; + } + + protected static function capture(string $status = 'COMPLETED', string $value = '119.00'): array + { + return [ + 'id' => self::CAPTURE_ID, + 'status' => $status, + 'amount' => [ + 'currency_code' => 'EUR', + 'value' => $value, + ], + 'supplementary_data' => [ + 'related_ids' => [ + 'order_id' => self::PAYPAL_ORDER_ID, + ], + ], + ]; + } +} diff --git a/Tests/Functional/Checkout/Payment/PaymentStatusUpdaterTest.php b/Tests/Functional/Checkout/Payment/PaymentStatusUpdaterTest.php new file mode 100644 index 0000000..53941c5 --- /dev/null +++ b/Tests/Functional/Checkout/Payment/PaymentStatusUpdaterTest.php @@ -0,0 +1,78 @@ +get(PaymentStatusUpdater::class); + self::assertInstanceOf(PaymentStatusUpdater::class, $subject); + $this->subject = $subject; + } + + #[Test] + public function changeChangesTheStatus(): void + { + $payment = $this->getPayment(); + + self::assertTrue($this->subject->change($payment, 'paid')); + self::assertSame('paid', $this->getPaymentStatus()); + self::assertTrue($payment->isPaid()); + } + + #[Test] + public function changeTriesAgainWithTheStoredStatusIfThePaymentWasChangedInTheMeantime(): void + { + $payment = $this->getPayment(); + // e.g. by a webhook of PayPal while the customer returns to the shop + $this->setPaymentStatus('pending'); + + self::assertTrue($this->subject->change($payment, 'paid')); + self::assertSame('paid', $this->getPaymentStatus()); + self::assertTrue($payment->isPaid()); + } + + #[Test] + public function changeReturnsFalseIfThePaymentGotTheStatusInTheMeantime(): void + { + $payment = $this->getPayment(); + $this->setPaymentStatus('paid'); + + self::assertFalse($this->subject->change($payment, 'paid'), 'Only the request which changed the status may dispatch the events.'); + self::assertSame('paid', $this->getPaymentStatus()); + } + + private function getPayment(): Payment + { + $persistenceManager = GeneralUtility::makeInstance(PersistenceManager::class); + $persistenceManager->clearState(); + $payment = $persistenceManager->getObjectByIdentifier(1, Payment::class); + self::assertInstanceOf(Payment::class, $payment); + self::assertTrue($payment->isOpen()); + + return $payment; + } +} diff --git a/Tests/Functional/Configuration/CredentialsFromSiteConfigurationTest.php b/Tests/Functional/Configuration/CredentialsFromSiteConfigurationTest.php new file mode 100644 index 0000000..e71ef39 --- /dev/null +++ b/Tests/Functional/Configuration/CredentialsFromSiteConfigurationTest.php @@ -0,0 +1,59 @@ + 'typo3conf/sites', + ]; + + protected function setUp(): void + { + putenv('CART_PAYPAL_TEST_CLIENT_SECRET=client-secret-from-env'); + + parent::setUp(); + } + + protected function tearDown(): void + { + putenv('CART_PAYPAL_TEST_CLIENT_SECRET'); + + parent::tearDown(); + } + + #[Test] + public function requestsTheAccessTokenWithTheCredentialsOfTheSite(): void + { + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders', 200, ['id' => self::PAYPAL_ORDER_ID]); + + $this->callApi('createOrder', 'POST'); + + $requests = PayPalApiMock::getRequests('/v1/oauth2/token'); + self::assertCount(1, $requests); + self::assertSame( + 'Basic ' . base64_encode('client-id-of-the-site:client-secret-from-env'), + $requests[0]->getHeaderLine('Authorization') + ); + } +} diff --git a/Tests/Functional/Configuration/SiteSetTest.php b/Tests/Functional/Configuration/SiteSetTest.php new file mode 100644 index 0000000..afdb754 --- /dev/null +++ b/Tests/Functional/Configuration/SiteSetTest.php @@ -0,0 +1,83 @@ + 'typo3conf/sites', + ]; + + protected function setUp(): void + { + parent::setUp(); + + $connection = $this->get(ConnectionPool::class)->getConnectionForTable('sys_template'); + $template = $connection->select(['include_static_file', 'constants'], 'sys_template', ['uid' => 1])->fetchAssociative(); + self::assertIsArray($template); + $connection->update( + 'sys_template', + [ + 'include_static_file' => str_replace(',EXT:cart_paypal/Configuration/TypoScript', '', (string)$template['include_static_file']), + 'constants' => str_replace('plugin.tx_cartpaypal.paymentPid = 3', '', (string)$template['constants']), + // the TypoScript of the site sets is kept + 'clear' => 0, + ], + ['uid' => 1] + ); + } + + #[Test] + public function paymentPageOfTheSiteSettingsIsUsed(): void + { + $response = $this->executeFrontendSubRequest( + (new InternalRequest('http://localhost/')) + ->withPageId(1) + ->withQueryParameters(['type' => 4711]) + ); + + self::assertSame(303, $response->getStatusCode()); + self::assertStringStartsWith('http://localhost/payment?', $response->getHeaderLine('Location')); + } + + #[Test] + public function endpointsAreAvailableOnThePageTypeOfTheSiteSet(): void + { + $response = $this->callApi('createOrder'); + + self::assertSame(405, $response->getStatusCode()); + } + + #[Test] + public function brandNameOfTheSiteSettingsIsSentToPayPal(): void + { + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders', 200, ['id' => self::PAYPAL_ORDER_ID]); + + $this->callApi('createOrder', 'POST'); + + $order = json_decode((string)PayPalApiMock::getRequests('/v2/checkout/orders')[0]->getBody(), true); + self::assertSame('Shop from site settings', $order['payment_source']['paypal']['experience_context']['brand_name']); + } +} diff --git a/Tests/Functional/Controller/ApiControllerCaptureOrderTest.php b/Tests/Functional/Controller/ApiControllerCaptureOrderTest.php new file mode 100644 index 0000000..5927f02 --- /dev/null +++ b/Tests/Functional/Controller/ApiControllerCaptureOrderTest.php @@ -0,0 +1,220 @@ +addTransaction(); + } + + #[Test] + public function completedCaptureMarksTheOrderAsPaid(): void + { + $this->prepareCapture(201, self::capturedOrder()); + + $data = $this->decodeJson($this->captureOrder()); + + self::assertSame('paid', $data['status']); + self::assertStringContainsString('tx_cart_cart%5Baction%5D=show', $data['redirectUrl']); + self::assertStringContainsString('tx_cart_cart%5BorderItem%5D=1', $data['redirectUrl']); + self::assertSame('paid', $this->getPaymentStatus()); + self::assertSame( + [ + 'payment' => 1, + 'txn_id' => self::PAYPAL_ORDER_ID, + 'status' => 'paid', + 'external_status_code' => 'COMPLETED', + 'note' => self::CAPTURE_ID, + ], + $this->getTransactions()[0] + ); + } + + #[Test] + public function completedCaptureDispatchesTheFinishEventOnce(): void + { + $this->prepareCapture(201, self::capturedOrder()); + + $this->captureOrder(); + $this->captureOrder(); + + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + self::assertArrayNotHasKey(CancelEvent::class, EventRecorder::getEvents()); + + $event = EventRecorder::getEvents()[FinishEvent::class][0]; + self::assertInstanceOf(FinishEvent::class, $event); + self::assertSame('ORD-2026-0001', $event->getOrderItem()->getOrderNumber()); + self::assertSame('1', (string)$event->getSettings()['settings']['cart']['pid']); + } + + #[Test] + public function captureIsSentWithTheIdOfTheOrderAsRequestId(): void + { + $this->prepareCapture(201, self::capturedOrder()); + + $this->captureOrder(); + + $requests = PayPalApiMock::getRequests('/v2/checkout/orders/' . self::PAYPAL_ORDER_ID . '/capture'); + self::assertCount(1, $requests); + self::assertSame('capture-' . self::PAYPAL_ORDER_ID, $requests[0]->getHeaderLine('PayPal-Request-Id')); + } + + #[Test] + public function pendingCaptureMarksThePaymentAsPendingWithoutFinishingTheOrder(): void + { + $this->prepareCapture(201, self::capturedOrder('PENDING')); + + $data = $this->decodeJson($this->captureOrder()); + + self::assertSame('pending', $data['status']); + self::assertArrayHasKey('redirectUrl', $data); + self::assertSame('pending', $this->getPaymentStatus()); + self::assertSame('pending', $this->getTransactions()[0]['status']); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function declinedCaptureLetsTheCustomerTryAgain(): void + { + $this->prepareCapture(422, [ + 'name' => 'UNPROCESSABLE_ENTITY', + 'details' => [ + ['issue' => 'INSTRUMENT_DECLINED'], + ], + ]); + + $data = $this->decodeJson($this->captureOrder()); + + self::assertSame('failed', $data['status']); + self::assertArrayNotHasKey('redirectUrl', $data); + self::assertNotSame('', $data['message']); + self::assertSame('open', $this->getPaymentStatus()); + self::assertSame( + ['status' => 'failed', 'external_status_code' => 'INSTRUMENT_DECLINED'], + array_intersect_key($this->getTransactions()[0], ['status' => 0, 'external_status_code' => 0]) + ); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function alreadyCapturedOrderIsReadFromPayPal(): void + { + $this->prepareCapture(422, [ + 'name' => 'UNPROCESSABLE_ENTITY', + 'details' => [ + ['issue' => 'ORDER_ALREADY_CAPTURED'], + ], + ]); + PayPalApiMock::addResponse('GET', '/v2/checkout/orders/' . self::PAYPAL_ORDER_ID, 200, self::capturedOrder()); + + $data = $this->decodeJson($this->captureOrder()); + + self::assertSame('paid', $data['status']); + self::assertSame('paid', $this->getPaymentStatus()); + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + } + + #[Test] + public function captureWithAnotherAmountIsNotMarkedAsPaid(): void + { + $this->prepareCapture(201, self::capturedOrder('COMPLETED', '1.00')); + + $data = $this->decodeJson($this->captureOrder()); + + self::assertSame('pending', $data['status']); + self::assertSame('pending', $this->getPaymentStatus()); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function paidOrderIsNotCapturedAgain(): void + { + $this->setPaymentStatus('paid'); + + $data = $this->decodeJson($this->captureOrder()); + + self::assertSame('paid', $data['status']); + self::assertSame([], PayPalApiMock::getRequests()); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function payPalOrderOfAnotherOrderIsRejected(): void + { + $response = $this->callApi('captureOrder', 'POST', '{"orderId": "PAYPAL-ORDER-OF-SOMEONE-ELSE"}'); + + self::assertSame(409, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + self::assertSame('open', $this->getPaymentStatus()); + } + + #[Test] + public function captureWithoutOrderIdIsRejected(): void + { + $response = $this->callApi('captureOrder', 'POST', '{}'); + + self::assertSame(409, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function unknownCartIsRejected(): void + { + $response = $this->callApi('captureOrder', 'POST', '{"orderId": "' . self::PAYPAL_ORDER_ID . '"}', hash: 'unknown-cart-hash'); + + self::assertSame(404, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function unreachablePayPalIsAnsweredWithAnError(): void + { + $this->prepareCapture(503, ['name' => 'SERVICE_UNAVAILABLE']); + + $response = $this->captureOrder(); + + self::assertSame(502, $response->getStatusCode()); + self::assertSame('open', $this->getPaymentStatus()); + self::assertSame('created', $this->getTransactions()[0]['status']); + } + + private function prepareCapture(int $statusCode, array $body): void + { + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders/' . self::PAYPAL_ORDER_ID . '/capture', $statusCode, $body); + } + + private function captureOrder(): ResponseInterface + { + return $this->callApi('captureOrder', 'POST', '{"orderId": "' . self::PAYPAL_ORDER_ID . '"}'); + } +} diff --git a/Tests/Functional/Controller/ApiControllerCreateOrderTest.php b/Tests/Functional/Controller/ApiControllerCreateOrderTest.php new file mode 100644 index 0000000..3fbae4b --- /dev/null +++ b/Tests/Functional/Controller/ApiControllerCreateOrderTest.php @@ -0,0 +1,182 @@ +preparePayPalOrder(); + + $response = $this->callApi('createOrder', 'POST'); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame(['orderId' => self::PAYPAL_ORDER_ID], $this->decodeJson($response)); + self::assertSame( + [ + [ + 'payment' => 1, + 'txn_id' => self::PAYPAL_ORDER_ID, + 'status' => 'created', + 'external_status_code' => 'PAYER_ACTION_REQUIRED', + 'note' => '', + ], + ], + $this->getTransactions() + ); + self::assertSame('open', $this->getPaymentStatus()); + } + + #[Test] + public function sendsTheAmountOfTheStoredOrder(): void + { + $this->preparePayPalOrder(); + + $this->callApi('createOrder', 'POST', '{"amount": "0.01"}'); + + $requests = PayPalApiMock::getRequests('/v2/checkout/orders'); + self::assertCount(1, $requests); + self::assertSame('Bearer access-token', $requests[0]->getHeaderLine('Authorization')); + self::assertStringStartsWith('create-', $requests[0]->getHeaderLine('PayPal-Request-Id')); + + $order = json_decode((string)$requests[0]->getBody(), true); + self::assertSame('CAPTURE', $order['intent']); + self::assertSame( + [ + 'custom_id' => '1', + 'amount' => [ + 'currency_code' => 'EUR', + 'value' => '119.00', + ], + 'invoice_id' => 'ORD-2026-0001', + ], + $order['purchase_units'][0] + ); + + $experienceContext = $order['payment_source']['paypal']['experience_context']; + self::assertSame('PAY_NOW', $experienceContext['user_action']); + self::assertSame('NO_SHIPPING', $experienceContext['shipping_preference']); + self::assertStringContainsString('tx_cartpaypal_api%5Baction%5D=return', $experienceContext['return_url']); + self::assertStringContainsString('tx_cartpaypal_api%5Bhash%5D=' . self::CART_HASH, $experienceContext['return_url']); + self::assertStringContainsString('tx_cartpaypal_api%5Baction%5D=cancel', $experienceContext['cancel_url']); + self::assertStringContainsString('tx_cartpaypal_api%5Bhash%5D=' . self::CART_FAILURE_HASH, $experienceContext['cancel_url']); + } + + #[Test] + public function createsTheOrderForTheCardButtonWithoutPaymentSource(): void + { + $this->setPaymentProvider('PAYPAL_CREDITCARD'); + $this->preparePayPalOrder(); + + $response = $this->callApi('createOrder', 'POST'); + + self::assertSame(['orderId' => self::PAYPAL_ORDER_ID], $this->decodeJson($response)); + $order = json_decode((string)PayPalApiMock::getRequests('/v2/checkout/orders')[0]->getBody(), true); + self::assertSame(['intent', 'purchase_units'], array_keys($order)); + self::assertSame('119.00', $order['purchase_units'][0]['amount']['value']); + self::assertSame(self::PAYPAL_ORDER_ID, $this->getTransactions()[0]['txn_id']); + } + + #[Test] + public function requestsTheAccessTokenWithTheCredentials(): void + { + $this->preparePayPalOrder(); + + $this->callApi('createOrder', 'POST'); + + $requests = PayPalApiMock::getRequests('/v1/oauth2/token'); + self::assertCount(1, $requests); + self::assertSame('api-m.sandbox.paypal.com', $requests[0]->getUri()->getHost()); + self::assertSame('Basic ' . base64_encode('client-id:client-secret'), $requests[0]->getHeaderLine('Authorization')); + self::assertSame('grant_type=client_credentials', (string)$requests[0]->getBody()); + } + + #[Test] + public function rejectsOtherMethodsThanPost(): void + { + $response = $this->callApi('createOrder'); + + self::assertSame(405, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function rejectsUnknownCarts(): void + { + $response = $this->callApi('createOrder', 'POST', hash: 'unknown-cart-hash'); + + self::assertSame(404, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function rejectsPaidOrders(): void + { + $this->setPaymentStatus('paid'); + + $response = $this->callApi('createOrder', 'POST'); + + self::assertSame(409, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function rejectsOrdersOfOtherPaymentProviders(): void + { + $this->setPaymentProvider('GIROSOLUTION_PAYPAL'); + + $response = $this->callApi('createOrder', 'POST'); + + self::assertSame(409, $response->getStatusCode()); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function answersWithAnErrorIfPayPalFails(): void + { + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders', 500, [ + 'name' => 'INTERNAL_SERVER_ERROR', + 'debug_id' => 'debug-1', + ]); + + $response = $this->callApi('createOrder', 'POST'); + + self::assertSame(502, $response->getStatusCode()); + self::assertArrayHasKey('message', $this->decodeJson($response)); + self::assertSame([], $this->getTransactions()); + } + + private function preparePayPalOrder(): void + { + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders', 200, [ + 'id' => self::PAYPAL_ORDER_ID, + 'status' => 'PAYER_ACTION_REQUIRED', + 'links' => [ + [ + 'href' => 'https://www.sandbox.paypal.com/checkoutnow?token=' . self::PAYPAL_ORDER_ID, + 'rel' => 'payer-action', + 'method' => 'GET', + ], + ], + ]); + } +} diff --git a/Tests/Functional/Controller/ApiControllerRedirectFlowTest.php b/Tests/Functional/Controller/ApiControllerRedirectFlowTest.php new file mode 100644 index 0000000..c0f4d09 --- /dev/null +++ b/Tests/Functional/Controller/ApiControllerRedirectFlowTest.php @@ -0,0 +1,206 @@ + self::PAYPAL_ORDER_ID, + 'status' => 'PAYER_ACTION_REQUIRED', + 'links' => [ + ['href' => 'https://api-m.sandbox.paypal.com/v2/checkout/orders/' . self::PAYPAL_ORDER_ID, 'rel' => 'self'], + ['href' => self::APPROVE_URL, 'rel' => 'payer-action'], + ], + ]); + + $response = $this->callApi('redirect'); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame(self::APPROVE_URL, $response->getHeaderLine('Location')); + self::assertSame('created', $this->getTransactions()[0]['status']); + } + + #[Test] + public function redirectOfACreditCardPaymentSendsTheCustomerToPayPalWithReturnUrls(): void + { + $this->setPaymentProvider('PAYPAL_CREDITCARD'); + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders', 200, [ + 'id' => self::PAYPAL_ORDER_ID, + 'status' => 'PAYER_ACTION_REQUIRED', + 'links' => [ + ['href' => self::APPROVE_URL, 'rel' => 'payer-action'], + ], + ]); + + $response = $this->callApi('redirect'); + + self::assertSame(self::APPROVE_URL, $response->getHeaderLine('Location')); + $order = json_decode((string)PayPalApiMock::getRequests('/v2/checkout/orders')[0]->getBody(), true); + self::assertArrayHasKey('return_url', $order['payment_source']['paypal']['experience_context']); + } + + #[Test] + public function redirectOfAPaidOrderShowsTheOrder(): void + { + $this->setPaymentStatus('paid'); + + $response = $this->callApi('redirect'); + + self::assertSame(303, $response->getStatusCode()); + self::assertStringContainsString('tx_cart_cart%5BorderItem%5D=1', $response->getHeaderLine('Location')); + self::assertSame([], PayPalApiMock::getRequests()); + } + + #[Test] + public function returnCapturesTheOrderAndShowsIt(): void + { + $this->addTransaction(); + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders/' . self::PAYPAL_ORDER_ID . '/capture', 201, self::capturedOrder()); + + $response = $this->callApi('return', queryParameters: ['token' => self::PAYPAL_ORDER_ID, 'PayerID' => 'PAYER-1']); + + self::assertSame(303, $response->getStatusCode()); + self::assertStringContainsString('tx_cart_cart%5BorderItem%5D=1', $response->getHeaderLine('Location')); + self::assertSame('paid', $this->getPaymentStatus()); + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + } + + #[Test] + public function returnWithDeclinedPaymentSendsTheCustomerBackToThePaymentPage(): void + { + $this->addTransaction(); + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders/' . self::PAYPAL_ORDER_ID . '/capture', 422, [ + 'name' => 'UNPROCESSABLE_ENTITY', + 'details' => [['issue' => 'INSTRUMENT_DECLINED']], + ]); + + $response = $this->callApi('return', queryParameters: ['token' => self::PAYPAL_ORDER_ID]); + + self::assertSame(303, $response->getStatusCode()); + self::assertStringContainsString('/payment', $response->getHeaderLine('Location')); + self::assertStringContainsString('tx_cartpaypal_payment%5Bhash%5D=' . self::CART_HASH, $response->getHeaderLine('Location')); + self::assertSame('open', $this->getPaymentStatus()); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function returnWithDeclinedPaymentWithoutPaymentPageCancelsThePayment(): void + { + $this->setPaymentPid(0); + $this->addTransaction(); + PayPalApiMock::addAccessToken(); + PayPalApiMock::addResponse('POST', '/v2/checkout/orders/' . self::PAYPAL_ORDER_ID . '/capture', 422, [ + 'name' => 'UNPROCESSABLE_ENTITY', + 'details' => [['issue' => 'INSTRUMENT_DECLINED']], + ]); + + $response = $this->callApi('return', queryParameters: ['token' => self::PAYPAL_ORDER_ID]); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame('http://localhost/', $response->getHeaderLine('Location')); + self::assertSame('canceled', $this->getPaymentStatus()); + self::assertCount(1, EventRecorder::getEvents()[CancelEvent::class] ?? []); + } + + #[Test] + public function returnWithAnotherPayPalOrderDoesNotCapture(): void + { + $this->addTransaction(); + + $response = $this->callApi('return', queryParameters: ['token' => 'PAYPAL-ORDER-OF-SOMEONE-ELSE']); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame('http://localhost/', $response->getHeaderLine('Location')); + self::assertSame([], PayPalApiMock::getRequests()); + self::assertSame('open', $this->getPaymentStatus()); + } + + #[Test] + public function cancelCancelsThePaymentAndReturnsToTheCart(): void + { + $this->addTransaction(); + + $response = $this->callApi('cancel', hash: self::CART_FAILURE_HASH); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame('http://localhost/', $response->getHeaderLine('Location')); + self::assertSame('canceled', $this->getPaymentStatus()); + self::assertSame('canceled', $this->getTransactions()[0]['status']); + self::assertCount(1, EventRecorder::getEvents()[CancelEvent::class] ?? []); + self::assertArrayNotHasKey(FinishEvent::class, EventRecorder::getEvents()); + } + + #[Test] + public function repeatedCancelDispatchesTheCancelEventOnce(): void + { + $this->callApi('cancel', hash: self::CART_FAILURE_HASH); + $this->callApi('cancel', hash: self::CART_FAILURE_HASH); + + self::assertCount(1, EventRecorder::getEvents()[CancelEvent::class] ?? []); + } + + #[Test] + public function cancelOfAPaidOrderShowsTheOrder(): void + { + $this->setPaymentStatus('paid'); + + $response = $this->callApi('cancel', hash: self::CART_FAILURE_HASH); + + self::assertStringContainsString('tx_cart_cart%5BorderItem%5D=1', $response->getHeaderLine('Location')); + self::assertSame('paid', $this->getPaymentStatus()); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function cancelWithTheSuccessHashIsRejected(): void + { + $response = $this->callApi('cancel', hash: self::CART_HASH); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame('http://localhost/', $response->getHeaderLine('Location')); + self::assertSame('open', $this->getPaymentStatus()); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function unknownCartReturnsToTheCart(): void + { + $response = $this->callApi('cancel', hash: 'unknown-cart-hash'); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame('http://localhost/', $response->getHeaderLine('Location')); + self::assertSame('open', $this->getPaymentStatus()); + } +} diff --git a/Tests/Functional/Controller/PaymentControllerTest.php b/Tests/Functional/Controller/PaymentControllerTest.php new file mode 100644 index 0000000..8ae8530 --- /dev/null +++ b/Tests/Functional/Controller/PaymentControllerTest.php @@ -0,0 +1,137 @@ +showPaymentPage(); + + self::assertSame(200, $response->getStatusCode()); + $html = (string)$response->getBody(); + self::assertStringContainsString('