diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..8848b6b7 --- /dev/null +++ b/.babelrc @@ -0,0 +1,16 @@ +{ + "plugins": [ + "@babel/plugin-proposal-class-properties" + ], + "presets": [ + "@babel/preset-typescript", + [ + "@babel/preset-env", + { + "targets": { + "node": "6.9" + } + } + ] + ] +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..0782fb75 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +[*] +charset = utf-8 +end_of_line = crlf +indent_size = 4 +indent_style = space +insert_final_newline = false +max_line_length = 200 +tab_width = 4 +trim_trailing_whitespace = true +ij_continuation_indent_size = 4 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = true +ij_smart_tabs = false +ij_visual_guides = none +ij_wrap_on_typing = false \ No newline at end of file diff --git a/.github/workflows/sonarqube.yml b/.github/workflows/sonarqube.yml new file mode 100644 index 00000000..19ac64b6 --- /dev/null +++ b/.github/workflows/sonarqube.yml @@ -0,0 +1,20 @@ +on: + push: + branches: + - main + - develop + pull_request: + types: [opened, synchronize, reopened] +name: SonarQube PR Analysis +jobs: + sonarqube: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: SonarQube Scan + uses: sonarsource/sonarqube-scan-action@master + env: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} diff --git a/.gitignore b/.gitignore index 071aebbc..22fd4251 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,6 @@ dist/ *.lock *.cache package-lock.json -*.js *.map *.d.ts .idea/ diff --git a/.prettierignore b/.prettierignore index 53c37a16..1521c8b7 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1 +1 @@ -dist \ No newline at end of file +dist diff --git a/.prettierrc.json b/.prettierrc.json index 216efb86..7b308a2f 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,8 +1,10 @@ { - "printWidth": 100, + "bracketSpacing": true, + "printWidth": 120, + "trailingComma": "es5", "tabWidth": 4, "singleQuote": true, - "bracketSameLine": true, - "trailingComma": "none", - "semi": false + "singleAttributePerLine": true, + "htmlWhitespaceSensitivity": "ignore", + "bracketSameLine": false } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..2e193626 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +--- + +## [Released] + +## [1.0.0] + +- Refactor method calls. +- Batch api calls. +- Response and push validation. +- Add general models. +- Add PayByBank +- Add In3 new + +## [0.9.0] + +- Beta release. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 11412766..042bdfac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,23 +2,24 @@ ### Repository setup: -- Fork the repository to your account -- more details about [how to fork a repo](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) can be found [here](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo): +- Fork the repository to your account +- more details about [how to fork a repo](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) can be + found [here](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo): ### Making changes: -- create a branch from develop branch -- name of the branch shoul be something like: `feature/GITHUB-ISSUE-ID-slug` (eg: `feature/50-configprovider-update`) -- including unit tests is encouraged +- create a branch from develop branch +- name of the branch shoul be something like: `feature/GITHUB-ISSUE-ID-slug` (eg: `feature/50-configprovider-update`) +- including unit tests is encouraged ### Pull Request: -- open the PR to develop branch -- if there is no issue referenced, add a description about the problem and the way it is being solved -- Allow edits from maintainers +- open the PR to develop branch +- if there is no issue referenced, add a description about the problem and the way it is being solved +- Allow edits from maintainers ### Contribution to refactoring: -- include unit tests -- open the Pull Request -- check that git workflows checks have passed +- include unit tests +- open the Pull Request +- check that git workflows checks have passed diff --git a/README.md b/README.md index 2b4b35ed..31bb1ada 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -

# Node SDK + [![Latest release](https://badgen.net/github/release/buckaroo-it/BuckarooSDK_Node)](https://github.com/buckaroo-it/BuckarooSDK_Node/releases)

@@ -11,7 +11,9 @@

--- + ### Index + - [About](#about) - [Requirements](#requirements) - [Installation](#installation) @@ -19,18 +21,21 @@ - [Contribute](#contribute) - [Versioning](#versioning) - [Additional information](#additional-information) + --- ### About -Buckaroo is the the Payment Service Provider for all your online payments with more than 15,000 companies relying on Buckaroo's platform to securely process their payments, subscriptions and unpaid invoices. Buckaroo developed their own Node SDK. The SDK is a modern, open-source Node.js library that makes it easy to integrate your Javascript application with Buckaroo's services. Start accepting payments today with Buckaroo. +Buckaroo is the Payment Service Provider for all your online payments with more than 15,000 companies relying on Buckaroo's platform to securely process their payments, subscriptions and unpaid +invoices. Buckaroo developed their own Node SDK. The SDK is a modern, open-source Node.js library that makes it easy to integrate your Javascript application with Buckaroo's services. Start accepting +payments today with Buckaroo. ### Requirements To use the Buckaroo API client, the following things are required: -- A Buckaroo account ([Dutch](https://www.buckaroo.nl/start) or [English](https://www.buckaroo.eu/solutions/request-form)) -- Node.js 6.14.× or greater +- A Buckaroo account ([Dutch](https://www.buckaroo.nl/start) or [English](https://www.buckaroo.eu/solutions/request-form)) +- Node.js 6.14.× or greater ### Installation @@ -43,37 +48,54 @@ npm install @buckaroo/buckaroo_sdk Initiate the buckaroo client with your website key and secret key. The keys can be retrieved from your [Buckaroo account](https://plaza.buckaroo.nl/Login). ```javascript -import { initializeBuckarooClient } from './BuckarooClient' -initializeBuckarooClient({ websiteKey: 'KEY', secretKey: 'SECRET' }) +import Buckaroo from '@buckaroo/buckaroo_sdk'; + +const buckarooClient = Buckaroo.InitializeClient( + { + secretKey: 'KEY', + websiteKey: 'SECRET', + }, + { + mode: 'TEST', // OR 'LIVE' + currency: 'EUR', + returnURL: 'RETURN_URL', + pushURL: 'PUSH_URL', + } +) ``` Create a payment with all the available payment methods. In this example, we show how to create a credit card payment. Each payment has a slightly different payload. ```javascript -import creditCard from './PaymentMethods/CreditCard' - -const payment = await creditCard().pay({ - amountDebit: 10, - name: 'Mastercard', - invoice: 'UNIQUE-INVOICE-NO' -}) +const payment = await buckarooClient + .method('mastercard') + .pay({ + amountDebit: 100, + }) + .request(); ``` After you create a transaction, you can retrieve several transaction information on demand. ```javascript -const transactionKey = payment.Key +const transaction = buckarooClient.transaction(payment.getTransactionKey()); -import { buckarooClient } from './BuckarooClient' - -buckarooClient().status(transactionKey) // Retrieve transaction status -buckarooClient().refundInfo(transactionKey) // Retrieve refund info -buckarooClient().cancelInfo(transactionKey) // Retrieve cancellation info +await transaction.status(); // Retrieve transaction status +await transaction.refundInfo(); // Retrieve refund info +await transaction.cancelInfo(); // Retrieve cancellation info ``` Find our full documentation online on [docs.buckaroo.io](https://docs.buckaroo.io/docs/node-sdk). +### Regarding Usage Outside of Node.js +This library is written in JavaScript, a versatile programming language with broad applicability. While it's technically possible to integrate this library into a website or mobile application, it's strongly advised against doing so. + +In the standard configuration, you make requests to the Buckaroo API using one of our provided libraries, typically from your server (such as a Node.js server). Your secret key is securely stored on this server, inaccessible to external entities. + +However, if you incorporate this library directly into a website or app, your secret key will be exposed to users. This could enable users to take actions on your behalf using that key. + #### Need more examples? + More examples can be found in the [examples folder](https://github.com/buckaroo-it/BuckarooSDK_Node/tree/master/example) ### Contribute @@ -87,14 +109,14 @@ If you want to contribute as well, then please follow our [Contribution Guidelin

-- **MAJOR:** Breaking changes that require additional testing/caution -- **MINOR:** Changes that should not have a big impact -- **PATCHES:** Bug and hotfixes only +- **MAJOR:** Breaking changes that require additional testing/caution +- **MINOR:** Changes that should not have a big impact +- **PATCHES:** Bug and hotfixes only ### Additional information -- **Support:** https://support.buckaroo.eu/contact -- **Contact:** [support@buckaroo.nl](mailto:support@buckaroo.nl) or [+31 (0)30 711 50 50](tel:+310307115050) +- **Support:** https://support.buckaroo.eu/contact +- **Contact:** [support@buckaroo.nl](mailto:support@buckaroo.nl) or [+31 (0)30 711 50 50](tel:+310307115050) ## License diff --git a/example/BuckarooClient.ts b/example/BuckarooClient.ts deleted file mode 100644 index bccdd989..00000000 --- a/example/BuckarooClient.ts +++ /dev/null @@ -1,33 +0,0 @@ -import buckarooClient, { initializeBuckarooClient } from '../src/BuckarooClient' - -initializeBuckarooClient( - { secretKey: 'secretKey', websiteKey: 'websiteKey' }, - { - mode: 'test', - currency: 'EUR', - pushURL: process.env.BPE_PUSH_URL || '', - returnURL: process.env.BPE_RETURN_URL || '', - returnURLCancel: process.env.BPE_RETURN_URL_CANCEL || '', - baseUrl: process.env.BPE_BASE_URL || '' - } -) -async function getSpecificationsOfIdeal() { - return await buckarooClient() - .specification('ideal', 1) - .then((res) => { - expect(res).toBeDefined() - }) -} -async function startTransactionRequest() { - return await buckarooClient() - .transactionRequest({ - currency: 'EUR', - amountDebit: 10, - servicesExcludedForClient: 'ideal', - servicesSelectableByClient: 'ideal,bancontactmrcash,paypal' - }) - .then((res) => { - expect(res).toBeDefined() - }) -} -export default buckarooClient diff --git a/example/CreditManagment.ts b/example/CreditManagment.ts deleted file mode 100644 index 8b84f9c4..00000000 --- a/example/CreditManagment.ts +++ /dev/null @@ -1,26 +0,0 @@ -require('./BuckarooClient') -import CreditManagement from '../src/PaymentMethods/CreditManagement' - -const creditManagement = new CreditManagement() - -;(async () => { - try { - const info = await creditManagement.invoiceInfo({ - invoice: 'test1' - }) - - const infoMultiple = await creditManagement.invoiceInfo({ - invoice: 'invoice1', - invoices: [ - { - invoiceNumber: 'invoice2' - }, - { - invoiceNumber: 'invoice3' - } - ] - }) - } catch (error) { - console.warn(error) - } -})() diff --git a/example/ValidateResponse.ts b/example/ValidateResponse.ts deleted file mode 100644 index 7d2a6637..00000000 --- a/example/ValidateResponse.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {ReplyHandler} from "../src/Handlers/Reply/ReplyHandler"; - -const buckarooClient = require('./BuckarooClient') - -const JsonDATA = '{"Key":"5340604668D74435AA344E1428ED1292","Invoice":"62d68b6c8ab0c","ServiceCode":"ideal","Status":{"Code":{"Code":190,"Description":"Success"},"SubCode":{"Code":"S001","Description":"Transaction successfully processed"},"DateTime":"2022-07-19T12:46:12"},"IsTest":true,"Order":"ORDER_NO_62d68b6ca2df3","Currency":"EUR","AmountDebit":10.1,"TransactionType":"C021","Services":[{"Name":"ideal","Action":null,"Parameters":[{"Name":"consumerIssuer","Value":"ABN AMRO"},{"Name":"transactionId","Value":"0000000000000001"},{"Name":"consumerName","Value":"J. de Tèster"},{"Name":"consumerIBAN","Value":"NL44RABO0123456789"},{"Name":"consumerBIC","Value":"RABONL2U"}],"VersionAsProperty":2}],"CustomParameters":null,"AdditionalParameters":{"List":[{"Name":"initiated_by_magento","Value":"1"},{"Name":"service_action","Value":"something"}]},"MutationType":1,"RelatedTransactions":null,"IsCancelable":false,"IssuingCountry":null,"StartRecurrent":false,"Recurring":false,"CustomerName":"J. de Tèster","PayerHash":"2d26d34584a4eafeeaa97eed10cfdae22ae64cdce1649a80a55fafca8850e3e22cb32eb7c8fc95ef0c6f96669a21651d4734cc568816f9bd59c2092911e6c0da","PaymentKey":"AEC974D455FF4A4B9B4C21E437A04838","Description":null}' -const auth_header = 'hmac N8hyQHxZ9W:swtPNR5+XSxKBYUJIWpJ8W/zDcZVuUJGn5kUR0HJEZg=:d550afab01d74207ad75f4ffe3e76beb:1686733946'; - -const url = 'https://buckaroo.dev/push' - -//Validate Json Response -let replyHandler = new ReplyHandler(buckarooClient().getCredentials(),JsonDATA,auth_header,url) -replyHandler.validate() -replyHandler.isValid // Returns true or false - -const HttpData = `ADD_service_action=1&brq_amount=10.10&brq_currency=EUR&brq_customer_name=J.+de+T%C3%A8ster&brq_invoicenumber=5fe146d9f7b198&brq_ordernumber=5fe146d9f78dd8&brq_payer_hash=2d26d34584a4eafeeaa97eed10cfdae22ae64cdce1649a80a55fafca8850e3e22cb32eb7c8fc95ef0c6f96669a21651d4734cc568816f9bd59c2092911e6c0da&brq_payment=82F023D0AE17443C9C674E8DEFE5279B&brq_payment_method=ideal&brq_SERVICE_ideal_consumerBIC=RABONL2U&brq_SERVICE_ideal_consumerIBAN=NL44RABO0123456789&brq_SERVICE_ideal_consumerIssuer=ABN+AMRO&brq_SERVICE_ideal_consumerName=J.+de+T%C3%A8ster&brq_SERVICE_ideal_transactionId=0000000000000001&brq_statuscode=190&brq_statuscode_detail=S001&brq_statusmessage=Transaction+successfully+processed&brq_test=true&brq_timestamp=2023-06-14+12%3A30%3A06&brq_transactions=85A3373B1A284B8F8E1D175CA5C0273B&brq_websitekey=N8hyQHxZ9W&brq_signature=62be159a87975a45d7b025cfbbff968c2dc8b9a1` - - -//Validate Http Response - -replyHandler = new ReplyHandler(buckarooClient().getCredentials(),HttpData) -replyHandler.validate() -replyHandler.isValid // Returns true or false diff --git a/example/additional_services/creditManagment.js b/example/additional_services/creditManagment.js new file mode 100644 index 00000000..28f87470 --- /dev/null +++ b/example/additional_services/creditManagment.js @@ -0,0 +1,63 @@ +import buckaroo from '../buckarooClient'; +const creditManagement = buckaroo.method('CreditManagement3'); +// Sometimes we need to combine multiple payments. +// By calling "combine" it will combine the payload of the method with the next method or a given payload. +const invoice = creditManagement.createCombinedInvoice({ + invoice: '', + applyStartRecurrent: false, + invoiceAmount: 10, + invoiceAmountVAT: 1, + invoiceDate: '', + dueDate: '', + schemeKey: '2amq34', + maxStepIndex: 1, + allowedServices: 'ideal,mastercard', + debtor: { + code: 'johnsmith4' + }, + email: 'youremail@example.nl', + phone: { + mobile: '06198765432' + }, + person: { + culture: 'nl-NL', + title: 'Msc', + initials: 'JS', + firstName: 'Test', + lastNamePrefix: 'Jones', + lastName: 'Aflever', + gender: 'male' + }, + company: { + culture: 'nl-NL', + name: 'My Company Corporation', + vatApplicable: true, + vatNumber: 'NL140619562B01', + chamberOfCommerce: '20091741' + }, + address: { + street: 'Hoofdtraat', + houseNumber: '90', + houseNumberAdditional: 'A', + zipcode: '8441ER', + city: 'Heerenveen', + state: 'Friesland', + country: 'NL' + } +}); +const sepadirectdebit = buckaroo.method('sepadirectdebit'); +sepadirectdebit + .combine(invoice.data) + .pay({ + invoice: '', + amountDebit: 10.1, + iban: 'NL13TEST0123456789', + bic: 'TESTNL2A', + collectdate: '2022-06-03', + mandateReference: '1DCtestreference', + mandateDate: '2022-07-03', + customer: { + name: 'John Smith' + } +}) + .request(); diff --git a/example/additional_services/creditManagment.ts b/example/additional_services/creditManagment.ts new file mode 100644 index 00000000..77cb68f0 --- /dev/null +++ b/example/additional_services/creditManagment.ts @@ -0,0 +1,67 @@ +import buckaroo from '../buckarooClient'; + +const creditManagement = buckaroo.method('CreditManagement3'); + +// Sometimes we need to combine multiple payments. +// By calling "combine" it will combine the payload of the method with the next method or a given payload. + +const invoice = creditManagement.createCombinedInvoice({ + invoice: '', + applyStartRecurrent: false, + invoiceAmount: 10, + invoiceAmountVAT: 1, + invoiceDate: '', + dueDate: '', + schemeKey: '2amq34', + maxStepIndex: 1, + allowedServices: 'ideal,mastercard', + debtor: { + code: 'johnsmith4', + }, + email: 'youremail@example.nl', + phone: { + mobile: '06198765432', + }, + person: { + culture: 'nl-NL', + title: 'Msc', + initials: 'JS', + firstName: 'Test', + lastNamePrefix: 'Jones', + lastName: 'Aflever', + gender: 'male', + }, + company: { + culture: 'nl-NL', + name: 'My Company Corporation', + vatApplicable: true, + vatNumber: 'NL140619562B01', + chamberOfCommerce: '20091741', + }, + address: { + street: 'Hoofdtraat', + houseNumber: '90', + houseNumberAdditional: 'A', + zipcode: '8441ER', + city: 'Heerenveen', + state: 'Friesland', + country: 'NL', + }, +}); + +buckaroo + .method('sepadirectdebit') + .combine(invoice.data) + .pay({ + invoice: '', + amountDebit: 10.1, + iban: 'NL13TEST0123456789', + bic: 'TESTNL2A', + collectdate: '2022-06-03', + mandateReference: '1DCtestreference', + mandateDate: '2022-07-03', + customer: { + name: 'John Smith', + }, + }) + .request(); diff --git a/example/subscription.ts b/example/additional_services/subscription.js similarity index 54% rename from example/subscription.ts rename to example/additional_services/subscription.js index b0d1740f..2b84c343 100644 --- a/example/subscription.ts +++ b/example/additional_services/subscription.js @@ -1,7 +1,6 @@ -require('./BuckarooClient') -import Subscriptions from '../src/PaymentMethods/Subscriptions' -import Ideal from '../src/PaymentMethods/Ideal' - +require('../buckarooClient'); +import Subscriptions from '../../src/PaymentMethods/Subscriptions'; +import Ideal from '../../src/PaymentMethods/Ideal'; const subscription = new Subscriptions().createCombined({ address: undefined, allowedServices: '', @@ -15,26 +14,23 @@ const subscription = new Subscriptions().createCombined({ customerBIC: '', customerIBAN: '', debtor: { code: '' }, - email: { - email: '345345345', - }, + email: '345345345', includeTransaction: false, mandateReference: '', - person: undefined, - phone: undefined, - ratePlan: undefined, - ratePlanCharge: undefined, subscriptionGuid: '', termStartDay: 0, termStartMonth: 0, termStartWeek: '', transactionVatPercentage: 0 -}) - -;(async () => { - const combinedPayment = await new Ideal().combine(subscription).pay({ - issuer: 'ABNANL2A', - amountDebit: 10 +}); +(async () => { + const combinedPayment = await new Ideal() + .pay({ + amountDebit: 1, + currency: 'EUR', + description: 'test' }) - console.log(combinedPayment) -})() + .combine('subscriptions') + .create({}); + console.log(combinedPayment); +})(); diff --git a/example/additional_services/subscription.ts b/example/additional_services/subscription.ts new file mode 100644 index 00000000..6b253898 --- /dev/null +++ b/example/additional_services/subscription.ts @@ -0,0 +1,36 @@ +import buckaroo from '../buckarooClient'; + +const subscription = buckaroo.method('CreditManagement3'); + +subscription.createCombined({ + address: undefined, + allowedServices: '', + b2b: '', + bankAccount: { accountName: '', bic: '', iban: '' }, + billingTiming: 0, + company: undefined, + configuration: undefined, + configurationCode: '', + customerAccountName: '', + customerBIC: '', + customerIBAN: '', + debtor: { code: '' }, + email: '345345345', + includeTransaction: false, + mandateReference: '', + subscriptionGuid: '', + termStartDay: 0, + termStartMonth: 0, + termStartWeek: '', + transactionVatPercentage: 0, +}); + +buckaroo + .method('ideal') + .combine(subscription) + .pay({ + amountDebit: 1, + currency: 'EUR', + description: 'test', + }) + .request(); diff --git a/example/buckarooClient.js b/example/buckarooClient.js new file mode 100644 index 00000000..112e489e --- /dev/null +++ b/example/buckarooClient.js @@ -0,0 +1,12 @@ +import Buckaroo from "@buckaroo/buckaroo_sdk"; +const buckaroo = Buckaroo.InitializeClient({ + secretKey: 'secret', + websiteKey: 'website' +}); +buckaroo.config = { + mode: 'TEST', + currency: 'EUR', + returnURL: 'https://example.com/return', + pushURL: 'https://example.com/push' +}; +export default buckaroo; diff --git a/example/buckarooClient.ts b/example/buckarooClient.ts new file mode 100644 index 00000000..5f276ac5 --- /dev/null +++ b/example/buckarooClient.ts @@ -0,0 +1,16 @@ +import Buckaroo from '@buckaroo/buckaroo_sdk'; + +const buckaroo = Buckaroo.InitializeClient( + { + secretKey: process.env.BPE_SECRET_KEY || '', + websiteKey: process.env.BPE_WEBSITE_KEY || '', + }, + { + mode: 'TEST', + currency: 'EUR', + returnURL: 'https://example.com/return', + pushURL: 'https://example.com/push', + } +); + +export default buckaroo; diff --git a/example/creditCard.ts b/example/creditCard.ts deleted file mode 100644 index 28dccab9..00000000 --- a/example/creditCard.ts +++ /dev/null @@ -1,16 +0,0 @@ -require('./BuckarooClient') -import CreditCard from '../src/PaymentMethods/CreditCard' - -const paymentMethod = new CreditCard() - -;(async () => { - try { - const info = await paymentMethod.pay({ - invoice: 'test1', - amountDebit: 12, - name: 'Visa' - }) - } catch (error) { - console.warn(error) - } -})() diff --git a/example/ideal.ts b/example/ideal.ts deleted file mode 100644 index a808e4ed..00000000 --- a/example/ideal.ts +++ /dev/null @@ -1,19 +0,0 @@ -require('../BuckarooClient.test') - -import Ideal from '../src/PaymentMethods/Ideal' - -const ideal = new Ideal() -async function startIdealPayment() { - return await ideal.pay({ - amountDebit: 10.1, - issuer: 'ABNANL2A', - clientIP: { - address: '123.456.789.123', - type: 0 - }, - description: 'Ideal Payment' - }) -} -startIdealPayment().then((response) => { - response.getRedirectUrl() -}) diff --git a/example/klarna.ts b/example/klarna.ts deleted file mode 100644 index eab0ea7f..00000000 --- a/example/klarna.ts +++ /dev/null @@ -1,27 +0,0 @@ -require('./BuckarooClient') -import Klarna from '../src/PaymentMethods/Klarna' - -const klarna = new Klarna() - -klarna.pay({ - article: [ - { - description: '', - grossUnitPrice: 0, - identifier: '', - quantity: '', - vatPercentage: '' - } - ], - amountDebit: 0, - billingCustomer: { - city: '', - country: '', - email: '', - firstName: '', - lastName: '', - postalCode: '', - street: '', - streetNumber: '' - } -}) diff --git a/example/payByBank.ts b/example/payByBank.ts deleted file mode 100644 index 6a6c77b8..00000000 --- a/example/payByBank.ts +++ /dev/null @@ -1,12 +0,0 @@ -require('../BuckarooClient.test') - -import PaymentInitiation from '../src/PaymentMethods/PaymentInitiation' - -const payByBank = new PaymentInitiation() -async function startPayByBankPayment() { - return await payByBank.pay({ - amountDebit: 10.1, - issuer: 'ABNANL2A', - countryCode: "NL", - }) -} diff --git a/example/response/push.js b/example/response/push.js new file mode 100644 index 00000000..8047966e --- /dev/null +++ b/example/response/push.js @@ -0,0 +1,39 @@ +import buckaroo from '../buckarooClient'; +import { ReplyHandler } from '../../src/Handlers/Reply/ReplyHandler'; +//START HTTP POST PUSH +let post_data = `{ + "brq_amount": "10.10", + "brq_currency": "EUR", + "brq_customer_name": "J. de Tèster", + "brq_invoicenumber": "SDKDevelopment.com_INVOICE_NO_628c6d032af90", + "brq_ordernumber": "SDKDevelopment.com_ORDER_NO_628c6d032af95", + "brq_payer_hash": "2d26d34584a4eafeeaa97eed10cfdae22ae64cdce1649a80a55fafca8850e3e22cb32eb7c8fc95ef0c6f96669a21651d4734cc568816f9bd59c2092911e6c0da", + "brq_payment": "D44ACDD0F99D4A1C811D2CD3EFDB05BA", + "brq_payment_method": "ideal", + "brq_SERVICE_ideal_consumerBIC": "RABONL2U", + "brq_SERVICE_ideal_consumerIBAN": "NL44RABO0123456789", + "brq_SERVICE_ideal_consumerIssuer": "ABN AMRO", + "brq_SERVICE_ideal_consumerName": "J. de Tèster", + "brq_SERVICE_ideal_transactionId": "0000000000000001", + "brq_statuscode": "190", + "brq_statuscode_detail": "S001", + "brq_statusmessage": "Transaction successfully processed", + "brq_test": "true", + "brq_timestamp": "2022-05-24 07:29:09", + "brq_transactions": "4C1BE53E2C42412AB32A799D9316E7DD", + "brq_websitekey": "IBjihN7Fhp", + "brq_signature": "bf7a62c830da2d2e004199919a8fe0d53b0668f5", +}`; +let reply_handler = new ReplyHandler(buckaroo.credentials, post_data); +reply_handler.validate(); +reply_handler.isValid(); // Return either true or false +//END HTTP POST PUSH +//START JSON PUSH +const auth_header = 'IBjihN7Fhp:0YvyjYAzDQ28W+hQi80f2nhe0Z1QFJLbz7IH//6LsAU=:cad1832100784f57a6e6de835d9f3638:1658227572'; +post_data = + '{"transaction":{"Key":"5340604668D74435AA344E1428ED1292","Invoice":"62d68b6c8ab0c","ServiceCode":"ideal","Status":{"Code":{"Code":190,"Description":"Success"},"SubCode":{"Code":"S001","Description":"transaction successfully processed"},"DateTime":"2022-07-19T12:46:12"},"IsTest":true,"Order":"ORDER_NO_62d68b6ca2df3","Currency":"EUR","AmountDebit":10.1,"TransactionType":"C021","Services":[{"Name":"ideal","Action":null,"Parameters":[{"Name":"consumerIssuer","Value":"ABN AMRO"},{"Name":"transactionId","Value":"0000000000000001"},{"Name":"consumerName","Value":"J. de Tèster"},{"Name":"consumerIBAN","Value":"NL44RABO0123456789"},{"Name":"consumerBIC","Value":"RABONL2U"}],"VersionAsProperty":2}],"CustomParameters":null,"AdditionalParameters":{"List":[{"Name":"initiated_by_magento","Value":"1"},{"Name":"service_action","Value":"something"}]},"MutationType":1,"RelatedTransactions":null,"IsCancelable":false,"IssuingCountry":null,"StartRecurrent":false,"Recurring":false,"CustomerName":"J. de Tèster","PayerHash":"2d26d34584a4eafeeaa97eed10cfdae22ae64cdce1649a80a55fafca8850e3e22cb32eb7c8fc95ef0c6f96669a21651d4734cc568816f9bd59c2092911e6c0da","PaymentKey":"AEC974D455FF4A4B9B4C21E437A04838","Description":null}}'; +const uri = 'https://buckaroo.dev/push'; +reply_handler = new ReplyHandler(buckaroo.credentials, post_data, auth_header, uri); +reply_handler.validate(); +reply_handler.isValid(); // Return either true or false +//END JSON PUSH diff --git a/example/response/push.ts b/example/response/push.ts new file mode 100644 index 00000000..17c9b2f5 --- /dev/null +++ b/example/response/push.ts @@ -0,0 +1,43 @@ +import buckaroo from '../buckarooClient'; +import { ReplyHandler } from '../../src/Handlers/Reply/ReplyHandler'; + +//START HTTP POST PUSH +let post_data = `{ + "brq_amount": "10.10", + "brq_currency": "EUR", + "brq_customer_name": "J. de Tèster", + "brq_invoicenumber": "SDKDevelopment.com_INVOICE_NO_628c6d032af90", + "brq_ordernumber": "SDKDevelopment.com_ORDER_NO_628c6d032af95", + "brq_payer_hash": "2d26d34584a4eafeeaa97eed10cfdae22ae64cdce1649a80a55fafca8850e3e22cb32eb7c8fc95ef0c6f96669a21651d4734cc568816f9bd59c2092911e6c0da", + "brq_payment": "D44ACDD0F99D4A1C811D2CD3EFDB05BA", + "brq_payment_method": "ideal", + "brq_SERVICE_ideal_consumerBIC": "RABONL2U", + "brq_SERVICE_ideal_consumerIBAN": "NL44RABO0123456789", + "brq_SERVICE_ideal_consumerIssuer": "ABN AMRO", + "brq_SERVICE_ideal_consumerName": "J. de Tèster", + "brq_SERVICE_ideal_transactionId": "0000000000000001", + "brq_statuscode": "190", + "brq_statuscode_detail": "S001", + "brq_statusmessage": "Transaction successfully processed", + "brq_test": "true", + "brq_timestamp": "2022-05-24 07:29:09", + "brq_transactions": "4C1BE53E2C42412AB32A799D9316E7DD", + "brq_websitekey": "IBjihN7Fhp", + "brq_signature": "bf7a62c830da2d2e004199919a8fe0d53b0668f5", +}`; + +let reply_handler = new ReplyHandler(buckaroo.credentials, post_data); +reply_handler.validate(); +reply_handler.isValid(); // Return either true or false +//END HTTP POST PUSH + +//START JSON PUSH +const auth_header = 'IBjihN7Fhp:0YvyjYAzDQ28W+hQi80f2nhe0Z1QFJLbz7IH//6LsAU=:cad1832100784f57a6e6de835d9f3638:1658227572'; +post_data = + '{"transaction":{"Key":"5340604668D74435AA344E1428ED1292","Invoice":"62d68b6c8ab0c","ServiceCode":"ideal","Status":{"Code":{"Code":190,"Description":"Success"},"SubCode":{"Code":"S001","Description":"transaction successfully processed"},"DateTime":"2022-07-19T12:46:12"},"IsTest":true,"Order":"ORDER_NO_62d68b6ca2df3","Currency":"EUR","AmountDebit":10.1,"TransactionType":"C021","Services":[{"Name":"ideal","Action":null,"Parameters":[{"Name":"consumerIssuer","Value":"ABN AMRO"},{"Name":"transactionId","Value":"0000000000000001"},{"Name":"consumerName","Value":"J. de Tèster"},{"Name":"consumerIBAN","Value":"NL44RABO0123456789"},{"Name":"consumerBIC","Value":"RABONL2U"}],"VersionAsProperty":2}],"CustomParameters":null,"AdditionalParameters":{"List":[{"Name":"initiated_by_magento","Value":"1"},{"Name":"service_action","Value":"something"}]},"MutationType":1,"RelatedTransactions":null,"IsCancelable":false,"IssuingCountry":null,"StartRecurrent":false,"Recurring":false,"CustomerName":"J. de Tèster","PayerHash":"2d26d34584a4eafeeaa97eed10cfdae22ae64cdce1649a80a55fafca8850e3e22cb32eb7c8fc95ef0c6f96669a21651d4734cc568816f9bd59c2092911e6c0da","PaymentKey":"AEC974D455FF4A4B9B4C21E437A04838","Description":null}}'; +const uri = 'https://buckaroo.dev/push'; + +reply_handler = new ReplyHandler(buckaroo.credentials, post_data, auth_header, uri); +reply_handler.validate(); +reply_handler.isValid(); // Return either true or false +//END JSON PUSH diff --git a/example/transaction/creditCard.js b/example/transaction/creditCard.js new file mode 100644 index 00000000..03b9c67d --- /dev/null +++ b/example/transaction/creditCard.js @@ -0,0 +1,15 @@ +require('../buckarooClient'); +import CreditCard from '../../src/PaymentMethods/CreditCard'; +const paymentMethod = new CreditCard('nexi'); +(async () => { + try { + const info = await paymentMethod.pay({ + invoice: 'test1', + amountDebit: 12 + }); + console.log(info); + } + catch (error) { + console.warn(error); + } +})(); diff --git a/example/transaction/creditCard.ts b/example/transaction/creditCard.ts new file mode 100644 index 00000000..505902fd --- /dev/null +++ b/example/transaction/creditCard.ts @@ -0,0 +1,6 @@ +import buckaroo from '../buckarooClient'; + +buckaroo.method('nexi').pay({ + invoice: 'test1', + amountDebit: 12, +}); diff --git a/example/transaction/ideal.js b/example/transaction/ideal.js new file mode 100644 index 00000000..a44f74a6 --- /dev/null +++ b/example/transaction/ideal.js @@ -0,0 +1,20 @@ +import buckarooClient from '../buckarooClient'; +const ideal = buckarooClient.method('ideal'); +//Pay +ideal + .pay({ + amountDebit: 10.1, + issuer: 'ABNANL2A', + description: 'Ideal Payment' +}) + .request(); +//Refund +ideal + .refund({ + originalTransactionKey: '', + amountCredit: 10.1, + invoice: '' +}) + .request(); +//Issuers +ideal.issuers(); diff --git a/example/transaction/ideal.ts b/example/transaction/ideal.ts new file mode 100644 index 00000000..b61ac5c9 --- /dev/null +++ b/example/transaction/ideal.ts @@ -0,0 +1,23 @@ +import buckarooClient from '../buckarooClient'; + +const ideal = buckarooClient.method('ideal'); + +//Pay +ideal + .pay({ + amountDebit: 10.1, + issuer: 'ABNANL2A', + description: 'Ideal Payment', + }) + .request(); +//Refund +ideal + .refund({ + originalTransactionKey: '', + amountCredit: 10.1, + invoice: '', + }) + .request(); + +//Issuers +ideal.issuers(); diff --git a/jest.config.js b/jest.config.js index 9d1dd1c9..ab7459e0 100644 --- a/jest.config.js +++ b/jest.config.js @@ -3,5 +3,5 @@ module.exports = { testEnvironment: 'node', testRegex: '/tests/.*.test.(ts|tsx)$', modulePathIgnorePatterns: ['/tests/.*(.d.ts)'], - moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'] -} + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], +}; diff --git a/package.json b/package.json index d04f07a9..b98c9888 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,19 @@ { "name": "@buckaroo/buckaroo_sdk", - "version": "0.9.0", + "version": "1.0.0", "description": "Buckaroo payment SDK", - "main": "dist/BuckarooClient.js", + "main": "dist/buckaroo.cjs.js", + "module": "dist/buckaroo.esm.js", + "types": "dist/index.d.ts", "engines": { "node": ">=6.14" }, "scripts": { - "prepare": "npm run build", - "build": "tsc", + "build": "yarn build:library && yarn build:declarations", + "dev": "yarn dev:library && yarn build:declarations", + "build:library": "rollup --config rollup.config.js", + "dev:library": "rollup --config rollup.config.js -w", + "build:declarations": "tsc --project tsconfig-declarations.json", "test": "jest", "prettier": "prettier --write ." }, @@ -23,6 +28,13 @@ "author": "Rinor Haziri", "license": "ISC", "devDependencies": { + "@babel/plugin-proposal-class-properties": "^7.18.6", + "@babel/preset-env": "^7.23.2", + "@babel/preset-typescript": "^7.23.2", + "@rollup/plugin-babel": "^6.0.4", + "@rollup/plugin-json": "^6.0.1", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-typescript": "^11.1.5", "@types/crypto-js": "^4.1.1", "@types/jest": "^29.4.0", "@types/node": "^18.11.18", @@ -33,7 +45,6 @@ "typescript": "^4.9.4" }, "dependencies": { - "axios": "^1.3.5", "crypto-js": "^4.1.1", "ip-address": "^8.1.0" }, @@ -46,6 +57,6 @@ }, "homepage": "https://github.com/buckaroo-it/BuckarooSDK_Node#readme", "files": [ - "dist/**/*" + "dist" ] } diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 00000000..dfa12a13 --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,47 @@ +const { join } = require('path'); +const json = require('@rollup/plugin-json'); +const resolve = require('@rollup/plugin-node-resolve'); +const babel = require('@rollup/plugin-babel'); +const typescript = require('@rollup/plugin-typescript'); + +module.exports = { + input: join('src', 'index.ts'), + external: [ + // These Node.js internals are external to our bundles… + 'crypto', + 'https', + 'querystring', + 'url', + 'util', + // …as are the dependencies listed in our package.json. + ...Object.keys(require('./package.json').dependencies), + ], + output: [ + { file: join('dist', 'buckaroo.cjs.js'), format: 'cjs' }, + { file: join('dist', 'buckaroo.esm.js'), format: 'es' }, + ], + plugins: [ + typescript(), + json(), + resolve({ + extensions: ['.ts'], + moduleDirectories: ['src'], + preferBuiltins: true, + }), + babel({ + extensions: ['.ts'], + }), + { + name: 'cert', + transform(code, id) { + if (id.endsWith('.pem') == false) { + return null; + } + return { + code: `export default ${JSON.stringify(code)}`, + map: { mappings: '' }, + }; + }, + }, + ], +}; diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 00000000..a1b5f9b5 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,9 @@ +# Unique key for the project +sonar.projectKey=buckaroo:node_sdk + +# Display name and version for the SonarQube UI +sonar.projectName=Buckaroo Node SDK +sonar.projectVersion=1.0 + +# Path to the source code, relative to the sonar-project.properties file +sonar.sources=. diff --git a/src/BuckarooClient.ts b/src/BuckarooClient.ts deleted file mode 100644 index 8d2f5a29..00000000 --- a/src/BuckarooClient.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IConfig, ICredentials } from './Utils/Types' -import { Client } from './Request/Client' - -let _client: Client -export function initializeBuckarooClient(credentials: ICredentials, config?: IConfig) { - if (!_client) { - _client = Client.initialize(credentials, config) - } - return _client -} -const BuckarooClient = () => (_client instanceof Client ? _client : Client.initialize()) -export default BuckarooClient diff --git a/src/Constants/CreditManagementInstallmentInterval.ts b/src/Constants/CreditManagementInstallmentInterval.ts index 245163cc..2902e8af 100644 --- a/src/Constants/CreditManagementInstallmentInterval.ts +++ b/src/Constants/CreditManagementInstallmentInterval.ts @@ -8,7 +8,7 @@ enum CreditManagementInstallmentInterval { TWOMONTHS = 'TwoMonths', QUARTERYEAR = 'QuarterYear', HALFYEAR = 'HalfYear', - YEAR = 'Year' + YEAR = 'Year', } -export default CreditManagementInstallmentInterval +export default CreditManagementInstallmentInterval; diff --git a/src/Constants/Endpoints.ts b/src/Constants/Endpoints.ts index afdb6cad..bd6b8885 100644 --- a/src/Constants/Endpoints.ts +++ b/src/Constants/Endpoints.ts @@ -1,10 +1,13 @@ enum Endpoints { - LIVE = 'https://checkout.buckaroo.nl/', - TEST = 'https://testcheckout.buckaroo.nl/' + LIVE = 'https://checkout.buckaroo.nl', + TEST = 'https://testcheckout.buckaroo.nl', } -enum RequestType { - Data = 1, - Transaction = 2 + +export enum RequestTypes { + Data = '/json/DataRequest', + Transaction = '/json/Transaction', + BatchData = '/json/batch/DataRequests', + BatchTransaction = '/json/batch/Transactions', } -export { RequestType } -export default Endpoints + +export default Endpoints; diff --git a/src/Constants/Gender.ts b/src/Constants/Gender.ts index dda7de2b..0a4f8284 100644 --- a/src/Constants/Gender.ts +++ b/src/Constants/Gender.ts @@ -2,6 +2,7 @@ enum Gender { UNKNOWN = 0, MALE = 1, FEMALE = 2, - NOT_APPLICABLE = 9 + NOT_APPLICABLE = 9, } -export default Gender + +export default Gender; diff --git a/src/Constants/HttpMethods.ts b/src/Constants/HttpMethods.ts index 2903572c..1d12e316 100644 --- a/src/Constants/HttpMethods.ts +++ b/src/Constants/HttpMethods.ts @@ -1,5 +1,6 @@ enum HttpMethods { GET = 'GET', - POST = 'POST' + POST = 'POST', } -export default HttpMethods + +export default HttpMethods; diff --git a/src/Constants/IPProtocolVersion.ts b/src/Constants/IPProtocolVersion.ts index 47af76ef..eb8f8d0d 100644 --- a/src/Constants/IPProtocolVersion.ts +++ b/src/Constants/IPProtocolVersion.ts @@ -1,16 +1,28 @@ -import * as IpAddress from 'ip-address' +import * as IpAddress from 'ip-address'; + +import { getIPAddress } from '../Utils'; export class IPProtocolVersion { - public static readonly IPV4: number = 0 - public static readonly IPV6: number = 1 + public static readonly IPV4: number = 0; + public static readonly IPV6: number = 1; public static getVersion(ipAddress: string = '0.0.0.0'): number { if (IpAddress.Address4.isValid(ipAddress)) { - return IPProtocolVersion.IPV4 + return IPProtocolVersion.IPV4; } if (IpAddress.Address6.isValid(ipAddress)) { - return IPProtocolVersion.IPV6 + return IPProtocolVersion.IPV6; } - throw new Error(`Invalid IP address: ${ipAddress}`) + throw new Error(`Invalid IP address: ${ipAddress}`); + } +} + +export class ClientIP { + type: IPProtocolVersion; + address: string; + + constructor(ipAddress: string = getIPAddress()) { + this.type = IPProtocolVersion.getVersion(ipAddress); + this.address = ipAddress; } } diff --git a/src/Constants/RecipientCategory.ts b/src/Constants/RecipientCategory.ts index 542fed45..edd1954d 100644 --- a/src/Constants/RecipientCategory.ts +++ b/src/Constants/RecipientCategory.ts @@ -1,7 +1,6 @@ enum RecipientCategory { - PERSON = 'Person', - COMPANY = 'Company', - B2B = 'B2B', - B2C = 'B2C' + PERSON = 'PERSON', + COMPANY = 'COMPANY', } -export default RecipientCategory + +export default RecipientCategory; diff --git a/src/Constants/ResponseStatus.ts b/src/Constants/ResponseStatus.ts index cb768207..81b2b57e 100644 --- a/src/Constants/ResponseStatus.ts +++ b/src/Constants/ResponseStatus.ts @@ -1,17 +1,18 @@ enum ResponseStatus { - BUCKAROO_STATUSCODE_SUCCESS = '190', - BUCKAROO_STATUSCODE_FAILED = '490', - BUCKAROO_STATUSCODE_VALIDATION_FAILURE = '491', - BUCKAROO_STATUSCODE_TECHNICAL_ERROR = '492', - BUCKAROO_STATUSCODE_REJECTED = '690', - BUCKAROO_STATUSCODE_WAITING_ON_USER_INPUT = '790', - BUCKAROO_STATUSCODE_PENDING_PROCESSING = '791', - BUCKAROO_STATUSCODE_WAITING_ON_CONSUMER = '792', - BUCKAROO_STATUSCODE_PAYMENT_ON_HOLD = '793', - BUCKAROO_STATUSCODE_CANCELLED_BY_USER = '890', - BUCKAROO_STATUSCODE_CANCELLED_BY_MERCHANT = '891', - BUCKAROO_AUTHORIZE_TYPE_CANCEL = 'I014', - BUCKAROO_AUTHORIZE_TYPE_ACCEPT = 'I013', - BUCKAROO_AUTHORIZE_TYPE_GROUP_TRANSACTION = 'I150' + STATUSCODE_SUCCESS = '190', + STATUSCODE_FAILED = '490', + STATUSCODE_VALIDATION_FAILURE = '491', + STATUSCODE_TECHNICAL_ERROR = '492', + STATUSCODE_REJECTED = '690', + STATUSCODE_WAITING_ON_USER_INPUT = '790', + STATUSCODE_PENDING_PROCESSING = '791', + STATUSCODE_WAITING_ON_CONSUMER = '792', + STATUSCODE_PAYMENT_ON_HOLD = '793', + STATUSCODE_CANCELLED_BY_USER = '890', + STATUSCODE_CANCELLED_BY_MERCHANT = '891', + AUTHORIZE_TYPE_CANCEL = 'I014', + AUTHORIZE_TYPE_ACCEPT = 'I013', + AUTHORIZE_TYPE_GROUP_TRANSACTION = 'I150', } -export default ResponseStatus + +export default ResponseStatus; diff --git a/src/Constants/index.ts b/src/Constants/index.ts new file mode 100644 index 00000000..c7dbcd7f --- /dev/null +++ b/src/Constants/index.ts @@ -0,0 +1,11 @@ +import Endpoints, { RequestTypes } from './Endpoints'; + +export { default as CreditManagementInstallmentInterval } from './CreditManagementInstallmentInterval'; +export { default as Gender } from './Gender'; +export { default as HttpMethods } from './HttpMethods'; +export * from './IPProtocolVersion'; +export * from './ResponseStatus'; +export { default as RecipientCategory } from './RecipientCategory'; +export { default as ResponseStatus } from './ResponseStatus'; + +export { Endpoints, RequestTypes }; \ No newline at end of file diff --git a/src/Handlers/Credentials.ts b/src/Handlers/Credentials.ts new file mode 100644 index 00000000..5accfd98 --- /dev/null +++ b/src/Handlers/Credentials.ts @@ -0,0 +1,27 @@ +import { ICredentials } from '../Utils'; +import { Request } from '../Request'; +import { RequestTypes } from '../Constants'; + +export class Credentials implements ICredentials { + secretKey: string; + websiteKey: string; + + constructor(secretKey: string, websiteKey: string) { + this.secretKey = secretKey; + this.websiteKey = websiteKey; + } + + confirm() { + return Request.Specification(RequestTypes.Transaction, { + name: 'ideal', + version: 2, + }) + .request() + .then((response) => { + return response.httpResponse.status === 200; + }) + .catch(() => { + return false; + }); + } +} diff --git a/src/Handlers/Reply/ReplyHandler.ts b/src/Handlers/Reply/ReplyHandler.ts index bd28fd24..9319088a 100644 --- a/src/Handlers/Reply/ReplyHandler.ts +++ b/src/Handlers/Reply/ReplyHandler.ts @@ -1,68 +1,68 @@ -import crypto from "crypto"; -import HttpMethods from "../../Constants/HttpMethods"; -import {ICredentials} from "../../Utils/Types"; -import {Hmac} from "../../Request/Hmac"; -import buckarooClient from "../../BuckarooClient"; +import crypto from 'crypto'; +import { ICredentials } from '../../Utils'; +import { Hmac } from '../../Request'; +import { HttpMethods } from '../../Constants'; export class ReplyHandler { - private readonly data: object - private readonly uri?: string - private readonly auth_header?: string - private credentials: ICredentials; - private _isValid: boolean = false + private readonly _data: object; + private readonly uri?: string; + private readonly auth_header?: string; + private readonly credentials: ICredentials; + private _isValid: boolean = false; + private strategy: 'JSON' | 'HTTP' = 'JSON'; + private method?: string; - constructor(credentials: ICredentials, data: string,auth_header?: string, uri?: string) { - try { - this.data = JSON.parse(data) - } catch (e){ - let objData = {} - new URLSearchParams(data).forEach((value, name)=>{ - objData[name] = value - }) - this.data = objData - } - this.credentials = credentials - this.uri = uri - this.auth_header = auth_header + constructor(credentials: ICredentials, data: string, auth_header?: string, uri?: string, httpMethod?: string) { + this._data = this.formatStringData(data); + this.credentials = credentials; + this.uri = uri; + this.auth_header = auth_header; + this.method = httpMethod; } - get isValid(){ - return this._isValid + + isValid(): boolean { + return this._isValid; } + validate() { - if(this.data["Key"] && this.auth_header && this.uri) { - this._isValid = this.validateJson(this.auth_header) - return this + if (this.strategy === 'HTTP') { + let { brq_signature, BRQ_SIGNATURE, ...data } = this._data as any; + this._isValid = this.validateHttp(data, brq_signature || BRQ_SIGNATURE); + return this; } - - if (this.data["brq_signature"] || this.data["BRQ_SIGNATURE"]){ - let { brq_signature , BRQ_SIGNATURE, ...data} = this.data as any - this._isValid = this.validateHttp(data,brq_signature || BRQ_SIGNATURE) - return this + if (this.strategy === 'JSON' && this.auth_header && this.uri) { + this._isValid = this.validateJson(this.auth_header, this.uri, JSON.stringify(this._data)); + return this; } - - throw new Error('Invalid reply data') + throw new Error('Invalid response data'); } - private validateJson(auth_header:string){ - let header = auth_header.split(':') - let providedHash = header[1] - let nonce = header[2] - let time = header[3] - let hmac = new Hmac(HttpMethods.POST,this.uri,this.data,nonce,time) - - let hash = hmac.hashData(hmac.getHashString()) + private formatStringData(value: string) { + try { + let data = JSON.parse(value); + this.strategy = 'JSON'; + return data; + } catch (e) { + let objData: Record = {}; + new URLSearchParams(value).forEach((value, name) => { + objData[name] = value; + }); + this.strategy = 'HTTP'; + return objData; + } + } - return crypto.timingSafeEqual(Buffer.from(hash),Buffer.from(providedHash)) + private validateJson(auth_header: string, url: string, data: string) { + return new Hmac().validate(this.credentials, auth_header, url, data, this.method || HttpMethods.POST); } - private validateHttp(data:object,signature:string){ - let stringData = '' - for (const key in data ) { - stringData+= key + '=' + data[key] - } - stringData = stringData + buckarooClient().getCredentials().websiteKey - let hash = crypto.createHash('sha1').update(stringData).digest('hex') + private validateHttp(data: Record, signature: string): boolean { + const stringData = + Object.keys(data) + .map((key) => `${key}=${data[key]}`) + .join('') + this.credentials.secretKey; + const hash = crypto.createHash('sha1').update(stringData).digest('hex'); - return crypto.timingSafeEqual(Buffer.from(hash),Buffer.from(signature)) + return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(signature)); } } diff --git a/src/Handlers/index.ts b/src/Handlers/index.ts new file mode 100644 index 00000000..f4b26137 --- /dev/null +++ b/src/Handlers/index.ts @@ -0,0 +1,2 @@ +export * from './Credentials'; +export * from './Reply/ReplyHandler'; diff --git a/src/Models/DataRequestResponse.ts b/src/Models/DataRequestResponse.ts deleted file mode 100644 index 9a1b2f1b..00000000 --- a/src/Models/DataRequestResponse.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { firstLowerCase, firstUpperCase } from '../Utils/Functions' -import {Response} from "../Request/Response"; - -export class DataRequestResponse extends Response { - get data(): IDataRequestResponse { - return this._data - } - getActionRequestParameters(actionName: string): RequestParameter[] | undefined { - actionName = firstUpperCase(actionName) - let actions = this.data.Actions?.find((action) => action.Name === actionName)?.RequestParameters - if (actions) { - actions.sort((a, b) => a.Name.localeCompare(b.Name)) - } - return actions - } - getServiceParameters(actionName: string) { - actionName = firstUpperCase(actionName) - let parameters = this.getActionRequestParameters(actionName) - let data: { [key: string]: any } = {} - if (parameters) { - parameters.forEach((param) => { - let current = data - param.Group = param.Group ? firstLowerCase(param.Group) : '' - if (param.Group) { - current = data[param.Group] = data[param.Group] ?? {} - } - current[firstLowerCase(param.Name)] = param.Required - }) - return data - } - } -} - -type ListItemDescription = { - Value: string - Description: string - GroupName: string -} -type SupportedCurrency = { - IsoNumber: number - Code: string - Name: string -} - -type Action = { - Name: string - Type: number - Default: boolean - Description: string - RequestParameters: RequestParameter[] - ResponseParameters: RequestParameter[] -} -export type RequestParameter = { - ListItemDescriptions: ListItemDescription[] - isRequestParameter: boolean - Name: string - DataType: number - MaxLength: number - MaxOccurs: number - Required: boolean - Global: boolean - Group?: string - Description: string - ExplanationHTML: string - DisplayName: string - InputPattern: string - AutoCompleteType: string -} -export interface IDataRequestResponse { - Actions?: Action[] - SupportedCurrencies?: SupportedCurrency[] - Name: string - Version: number - Description: string -} diff --git a/src/Models/IParameters.ts b/src/Models/IParameters.ts new file mode 100644 index 00000000..91228beb --- /dev/null +++ b/src/Models/IParameters.ts @@ -0,0 +1,43 @@ +import { Model } from './Model'; +import { Str } from '../Utils'; + +export interface IParameter { + name: string; + value: string | number | boolean; + groupType?: string; + groupID?: number; +} + +export class Parameter extends Model implements IParameter { + set name(value: string) { + this.set('name', Str.ucfirst(value)); + } + + set value(value: ParameterTypes) { + this.set('value', value); + } + + set groupType(value: string) { + this.set('groupType', value); + } + + set groupID(value: number) { + this.set('groupID', value); + } +} + +export type ParameterTypes = string | number | boolean; + +export declare type IAdditionalParameters = { + [name: string]: ParameterTypes; +}; +export declare type ServiceParameterTypes = ParameterTypes | ParameterTypes[] | IServiceParameters; + +export declare interface IServiceParameters { + [name: keyof any]: ServiceParameterTypes | undefined; +} + +export type IFormattedParameter = { + name: string; + value: string | number | boolean; +}; diff --git a/src/Models/IRequest.ts b/src/Models/IRequest.ts new file mode 100644 index 00000000..697d53d1 --- /dev/null +++ b/src/Models/IRequest.ts @@ -0,0 +1,44 @@ +import { ServiceCode } from '../Utils'; +import { IAdditionalParameters } from './IParameters'; + +export default interface IRequest { + clientIP?: string; + currency?: string; + clientUserAgent?: string; + returnURL?: string; + returnURLError?: string; + returnURLCancel?: string; + returnURLReject?: string; + pushURL?: string; + pushURLFailure?: string; + invoice?: string; + order?: string; + amountDebit?: number; + amountCredit?: number; + description?: string; + originalTransactionKey?: string; + originalTransactionReference?: { + type: string; + reference: string; + }; + culture?: string; + startRecurrent?: boolean; + continueOnIncomplete?: boolean; + servicesSelectableByClient?: ServiceCode[] | string; + servicesExcludedForClient?: ServiceCode[] | string; + customParameters?: IAdditionalParameters; + additionalParameters?: IAdditionalParameters; + + [key: string]: any; +} + +export declare interface IPaymentRequest extends IRequest { + amountDebit: number; + amountCredit?: never; +} + +export declare interface IRefundRequest extends IRequest { + amountCredit: number; + amountDebit?: never; + originalTransactionKey: string; +} diff --git a/src/Models/IServiceList.ts b/src/Models/IServiceList.ts new file mode 100644 index 00000000..f664defc --- /dev/null +++ b/src/Models/IServiceList.ts @@ -0,0 +1,61 @@ +import { Model } from './Model'; +import { IParameter, Parameter } from './IParameters'; + +export interface IService { + name: string; + action?: string; + version?: number; + parameters?: IParameter[]; +} + +export class Service extends Model implements IService { + constructor(data: IService) { + super(data); + } + + set action(value: string) { + this.set('action', value); + } + + set name(value: string) { + this.set('name', value); + } + + set version(value: number) { + this.set('version', value); + } + + set parameters(value: IParameter[]) { + this.set( + 'parameters', + value.map((parameter) => new Parameter(parameter)) + ); + } +} + +export class ServiceList extends Model { + constructor(...list: IService[]) { + super({ list: list }); + } + + get list(): Service[] { + return this.get('serviceList'); + } + + set list(services: IService[]) { + this.set( + 'serviceList', + services.map((service) => new Service(service)) + ); + } + + addService(service: IService) { + if (this.getService(service.name)) { + this.list[this.list.findIndex((s) => s.name === service.name)] = new Service(service); + } else this.list.push(new Service(service)); + } + + getService(name: string) { + return this.list.find((service) => service.name.toLowerCase() === name.toLowerCase()); + } +} diff --git a/src/Models/ITransaction.ts b/src/Models/ITransaction.ts deleted file mode 100644 index 75df864d..00000000 --- a/src/Models/ITransaction.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { AdditionalParameter, IPAddress } from '../Utils/Types' - -export declare interface ITransaction { - clientIP?: string | IPAddress - currency?: string - returnURL?: string - returnURLError?: string - returnURLCancel?: string - returnURLReject?: string - pushURL?: string - pushURLFailure?: string - invoice?: string - order?: string - amountDebit?: number - amountCredit?: number - description?: string - originalTransactionKey?: string - originalTransactionReference?: string - culture?: string - startRecurrent?: boolean - /** - * 0 = No - * 1 = RedirectToHTML - */ - continueOnIncomplete?: 0 | 1 - servicesSelectableByClient?: string - servicesExcludedForClient?: string - customParameters?: AdditionalParameter - additionalParameters?: AdditionalParameter -} - -export declare interface Payload extends Omit { - invoice?: string - order?: string - amountDebit: number -} - -export declare interface RefundPayload extends Omit { - order?: string - amountCredit: number - originalTransactionKey: string -} -export declare interface ICapture extends Payload { - originalTransactionKey: string -} diff --git a/src/Models/Interfaces/IAddress.ts b/src/Models/Interfaces/IAddress.ts new file mode 100644 index 00000000..98dc9f20 --- /dev/null +++ b/src/Models/Interfaces/IAddress.ts @@ -0,0 +1,43 @@ +import { Model } from '../Model'; + +export default interface IAddress { + street: string; + houseNumber: string; + houseNumberAdditional: string; + zipcode: string; + city: string; + state?: string; + country: string; + + [key: string]: any; +} + +export class Address extends Model implements IAddress { + set street(street: string) { + this.set('street', street); + } + + set houseNumber(houseNumber: string) { + this.set('houseNumber', houseNumber); + } + + set houseNumberAdditional(houseNumberAdditional: string) { + this.set('houseNumberAdditional', houseNumberAdditional); + } + + set zipcode(zipcode: string) { + this.set('zipcode', zipcode); + } + + set city(city: string) { + this.set('city', city); + } + + set state(state: string) { + this.set('state', state); + } + + set country(country: string) { + this.set('country', country); + } +} diff --git a/src/Models/Interfaces/IArticle.ts b/src/Models/Interfaces/IArticle.ts new file mode 100644 index 00000000..8128310c --- /dev/null +++ b/src/Models/Interfaces/IArticle.ts @@ -0,0 +1,56 @@ +import { Model } from '../Model'; + +export default interface IArticle { + identifier: string; + type: string; + brand?: string; + manufacturer?: string; + unitCode: string; + price: number; + quantity: number; + vatPercentage: number; + vatCategory: string; + description: string; +} + +export class Article extends Model implements IArticle { + set identifier(identifier: string) { + this.set('identifier', identifier); + } + + set type(type: string) { + this.set('type', type); + } + + set brand(brand: string) { + this.set('brand', brand); + } + + set manufacturer(manufacturer: string) { + this.set('manufacturer', manufacturer); + } + + set unitCode(unitCode: string) { + this.set('unitCode', unitCode); + } + + set price(price: number) { + this.set('price', price); + } + + set quantity(quantity: number) { + this.set('quantity', quantity); + } + + set vatPercentage(vatPercentage: number) { + this.set('vatPercentage', vatPercentage); + } + + set vatCategory(vatCategory: string) { + this.set('vatCategory', vatCategory); + } + + set description(description: string) { + this.set('description', description); + } +} diff --git a/src/Models/Interfaces/IBankAccount.ts b/src/Models/Interfaces/IBankAccount.ts new file mode 100644 index 00000000..a9e4bd70 --- /dev/null +++ b/src/Models/Interfaces/IBankAccount.ts @@ -0,0 +1,21 @@ +import { Model } from '../Model'; + +export default interface IBankAccount { + iban: string; + bic: string; + accountName: string; +} + +export class BankAccount extends Model implements IBankAccount { + set accountName(accountName: string) { + this.set('accountName', accountName); + } + + set bic(bic: string) { + this.set('bic', bic); + } + + set iban(iban: string) { + this.set('iban', iban); + } +} diff --git a/src/Models/Interfaces/ICustomer.ts b/src/Models/Interfaces/ICustomer.ts new file mode 100644 index 00000000..bf3c7ee5 --- /dev/null +++ b/src/Models/Interfaces/ICustomer.ts @@ -0,0 +1,30 @@ +import { Address, Company, IAddress, ICompany, IPerson, IPhone, Model, Person, Phone } from './../'; +import { RecipientCategory } from '../../Constants'; + +export interface ICustomer { + phone?: Partial; + email?: string; + recipient?: Partial; + address?: Partial; +} + +export class Customer extends Model { + set address(address: Partial) { + this.set('address', new Address(address)); + } + + set email(email: string) { + this.set('email', email); + } + + set phone(phone: Partial) { + this.set('phone', new Phone(phone)); + } + + set recipient(recipient: IPerson | ICompany) { + this.set( + 'recipient', + recipient.category === RecipientCategory.COMPANY ? new Company(recipient) : new Person(recipient) + ); + } +} diff --git a/src/Models/Interfaces/IDebtor.ts b/src/Models/Interfaces/IDebtor.ts new file mode 100644 index 00000000..f2d1cc9e --- /dev/null +++ b/src/Models/Interfaces/IDebtor.ts @@ -0,0 +1,11 @@ +import { Model } from '../Model'; + +export default interface IDebtor { + code: string; +} + +export class Debtor extends Model { + set code(value: string) { + this.set('code', value); + } +} diff --git a/src/Models/Interfaces/IEmail.ts b/src/Models/Interfaces/IEmail.ts new file mode 100644 index 00000000..a03eeb5c --- /dev/null +++ b/src/Models/Interfaces/IEmail.ts @@ -0,0 +1,19 @@ +import { Model } from '../Model'; + +export default interface IEmail { + email: string; +} + +export class Email extends Model implements IEmail { + constructor(data: IEmail) { + super(data); + } + + get email() { + return ''; + } + + set email(email: string) { + this.set('email', email); + } +} diff --git a/src/Models/Interfaces/IPhone.ts b/src/Models/Interfaces/IPhone.ts new file mode 100644 index 00000000..850ab726 --- /dev/null +++ b/src/Models/Interfaces/IPhone.ts @@ -0,0 +1,21 @@ +import { Model } from '../Model'; + +export default interface IPhone { + landline?: string; + mobile?: string; + fax?: string; +} + +export class Phone extends Model implements IPhone { + set landline(landline: string) { + this.set('landline', landline); + } + + set mobile(mobile: string) { + this.set('mobile', mobile); + } + + set fax(fax: string) { + this.set('fax', fax); + } +} diff --git a/src/Models/Interfaces/IRecipient.ts b/src/Models/Interfaces/IRecipient.ts new file mode 100644 index 00000000..382c5f83 --- /dev/null +++ b/src/Models/Interfaces/IRecipient.ts @@ -0,0 +1,119 @@ +import { Gender, RecipientCategory } from '../../Constants'; +import { Model } from '../Model'; + +export interface IRecipient { + [key: string]: any; +} + +export interface IPerson extends IRecipient { + category: RecipientCategory.PERSON; + gender: string | Gender; + culture: string; + careOf?: string; + title?: string; + initials?: string; + firstName: string; + lastName?: string; + lastNamePrefix?: string; + birthDate: string; + placeOfBirth: string; +} + +export interface ICompany extends IRecipient { + category: RecipientCategory.COMPANY; + companyName: string; + culture: string; + vatApplicable: boolean; + vatNumber: string; + chamberOfCommerce: string; +} + +export class Recipient extends Model implements IRecipient { + set birthDate(value: string) { + this.set('birthDate', value); + } + + set careOf(value: string) { + this.set('careOf', value); + } + + set category(value: RecipientCategory) { + this.set('category', value); + } + + set culture(value: string) { + this.set('culture', value); + } + + set firstName(value: string) { + this.set('firstName', value); + } + + set gender(value: string) { + this.set('gender', value); + } + + set initials(value: string) { + this.set('initials', value); + } + + set lastName(value: string) { + this.set('lastName', value); + } + + set lastNamePrefix(value: string) { + this.set('lastNamePrefix', value); + } + + set placeOfBirth(value: string) { + this.set('placeOfBirth', value); + } + + set title(value: string) { + this.set('title', value); + } +} + +export class Person extends Recipient implements IPerson { + constructor(data: Partial) { + super(data); + } + + set name(value: string) { + this.set('name', value); + } + + set category(value: RecipientCategory.PERSON) { + this.set('category', value); + } +} + +export class Company extends Recipient implements ICompany { + constructor(data: Partial) { + super(data as any); + } + + set category(value: RecipientCategory.COMPANY) { + this.set('category', value); + } + + set chamberOfCommerce(value: string) { + this.set('chamberOfCommerce', value); + } + + set companyName(value: string) { + this.set('companyName', value); + } + + set culture(value: string) { + this.set('culture', value); + } + + set vatApplicable(value: boolean) { + this.set('vatApplicable', value); + } + + set vatNumber(value: string) { + this.set('vatNumber', value); + } +} diff --git a/src/Models/Interfaces/index.ts b/src/Models/Interfaces/index.ts new file mode 100644 index 00000000..c5f7ee8b --- /dev/null +++ b/src/Models/Interfaces/index.ts @@ -0,0 +1,24 @@ +import IAddress, { Address } from './IAddress'; +import IArticle, { Article } from './IArticle'; +import IBankAccount, { BankAccount } from './IBankAccount'; +import IDebtor, { Debtor } from './IDebtor'; +import IEmail, { Email } from './IEmail'; +import IPhone, { Phone } from './IPhone'; + +export * from './ICustomer'; + +export * from './IRecipient'; +export { + IArticle, + Article, + IAddress, + Address, + IBankAccount, + BankAccount, + IDebtor, + Debtor, + IEmail, + Email, + IPhone, + Phone, +}; \ No newline at end of file diff --git a/src/Models/Model.ts b/src/Models/Model.ts new file mode 100644 index 00000000..48f4456c --- /dev/null +++ b/src/Models/Model.ts @@ -0,0 +1,137 @@ +import { Str } from '../Utils'; + +export class Model { + [key: keyof any]: any; + + constructor(...args: any[]) { + this.initialize(...args); + } + + initialize(data?: any) { + if (data instanceof Object && !Array.isArray(data)) { + if (data.constructor === this.constructor) { + this.setDataProperties(data); + } else this.setOwnProperties(data); + } + return this; + } + + set(name: string, value: any, hidden: boolean = false): this { + this.defineProperty(name, value, hidden); + return this; + } + + get(prop: string): any { + return this.has(prop)?.get?.call(this); + } + + has(prop: string, model = this): PropertyDescriptor | undefined { + return getObjectProperty(model, prop, Model.prototype); + } + + getData(callBack?: ((this: any, key: string, value: any) => any) | undefined): { + [key: string]: any; + } { + return JSON.parse(JSON.stringify(this), callBack); + } + + protected setOwnProperties( + data: Record = {}, + properties: { [key: string]: PropertyDescriptor } = this.getAllPropertyDescriptors() + ) { + for (const key in properties) { + if (properties[key].set) { + let value = data[key] ?? properties[key].get?.call(this); + if (value !== undefined) this[key] = value; + } + } + return this; + } + + protected setDataProperties(data: Record = {}) { + for (const dataKey in data) { + if (data.hasOwnProperty(dataKey) && data[dataKey] !== undefined) this.set(dataKey, data[dataKey]); + } + return this; + } + + protected privateName(name: string): string { + return Str.ucfirst(name); + } + + protected publicName(name: string): string { + return Str.lcfirst(name); + } + + protected getAllPropertyDescriptors(descriptors = {}, root = Model.prototype): { [p: string]: PropertyDescriptor } { + // Loop through the prototype chain + let currentObj = Object.getPrototypeOf(this); + while (currentObj !== root) { + const currentDescriptors = Object.getOwnPropertyDescriptors(currentObj); + + // Merge the descriptors into the result + descriptors = { ...currentDescriptors, ...descriptors }; + + // Move up the prototype chain + currentObj = Object.getPrototypeOf(currentObj); + } + return descriptors; + } + + protected defineProperty(name: string, value: any, hidden: boolean = false) { + let privateName = this.privateName(name); + Object.defineProperty(this, privateName, { + value, + writable: true, + enumerable: !hidden, + configurable: true, + }); + let publicName = this.publicName(name); + Object.defineProperty(this, publicName, { + get: () => value, + set: this.has(publicName)?.set ?? ((value) => this.set(publicName, value, hidden)), + enumerable: false, + configurable: true, + }); + } +} + +export class JsonModel extends Model { + constructor(data: object) { + super(data); + } + + initialize(data?: any) { + return this.setDataProperties(data); + } + + set(key: string, value: any) { + Object.defineProperty(this, Str.lcfirst(key), { + get: this.get.bind(this, value), + enumerable: true, + }); + return this; + } + + get(value: any) { + if (Array.isArray(value)) { + return value.map((v) => new JsonModel(v)); + } + if (value instanceof Object) { + return new JsonModel(value); + } + if (value === null) { + return undefined; + } + return value; + } +} + +export function getObjectProperty(object: object, property: string, root: any = null): PropertyDescriptor | undefined { + if (object !== root) { + return ( + Object.getOwnPropertyDescriptor(object, property) ?? + getObjectProperty(Object.getPrototypeOf(object), property, root) + ); + } +} diff --git a/src/Models/Parameters.ts b/src/Models/Parameters.ts deleted file mode 100644 index d7f3db30..00000000 --- a/src/Models/Parameters.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface IParameter { - Name: string - Value: string | number | boolean - GroupType?: string - GroupID?: string | number -} diff --git a/src/Models/Request.ts b/src/Models/Request.ts deleted file mode 100644 index f79e874c..00000000 --- a/src/Models/Request.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { ITransaction } from './ITransaction' -import { IServiceList, IServices } from './ServiceList' -import { IParameter } from './Parameters' -import { firstUpperCase } from '../Utils/Functions' -import { AdditionalParameter, ServiceParameters } from '../Utils/Types' -import { IPProtocolVersion } from '../Constants/IPProtocolVersion' - -export class Request { - protected _data: { [key: string]: any } = {} - get data(): object { - return this._data - } - public setRequestDataKey(key: string, data: any) { - this._data[key] = data - } - public filter(data: ITransaction | (ITransaction & ServiceParameters)) { - return Object.keys(data) - .filter((key) => this._data[key] === undefined && data[key] !== undefined) - .reduce((obj: ServiceParameters, key) => { - obj[key] = data[key] - return obj - }, {}) - } -} - -export class TransactionRequest extends Request { - get data(): ITransaction { - return this._data - } - public get services(): IServices | undefined { - return this._data['services'] - } - public set services(services: IServices | undefined) { - this._data['services'] = services - } - public setServices(services: IServiceList) { - this.services = { ServiceList: [services] } - } - public addServices(serviceList: IServiceList) { - if (this.services) { - this.services.ServiceList.push(serviceList) - } else { - this.setServices(serviceList) - } - } - - formatAdditionalParameters() { - if (this.data.additionalParameters) { - this.setRequestDataKey('additionalParameters', { - additionalParameter: this.formatParametersMap(this.data.additionalParameters) - }) - } - } - formatCustomParameters() { - if (this.data.customParameters) { - this.setRequestDataKey('customParameters', { - list: this.formatParametersMap(this.data.customParameters) - }) - } - } - protected formatParametersMap(value: AdditionalParameter): IParameter[] { - return Object.keys(value).map((key, value) => { - return { - Name: key, - Value: value || '' - } - }) - } - public basicParameters: Record = { - clientIP: true, - currency: true, - returnURL: true, - returnURLError: true, - returnURLCancel: true, - returnURLReject: true, - pushURL: true, - pushURLFailure: true, - invoice: true, - order: true, - amountDebit: true, - amountCredit: true, - description: true, - originalTransactionKey: true, - originalTransactionReference: true, - culture: true, - startRecurrent: true, - continueOnIncomplete: true, - servicesSelectableByClient: true, - servicesExcludedForClient: true, - customParameters: true, - additionalParameters: true - } - public setBasicParameters(data: ITransaction) { - for (const key in data) { - if (this.basicParameters[key]) { - this._data[key] = data[key] - } - } - this.formatAdditionalParameters() - this.formatCustomParameters() - this.setClientIp() - } - - public setClientIp() { - let ip = this.data.clientIP - if (ip && typeof ip === 'string') { - this.setRequestDataKey('clientIP', { - type: IPProtocolVersion.getVersion(ip), - address: ip - }) - } - } - public formatServiceParameters( - data: ServiceParameters, - groups: { GroupID?: number; GroupType: string } = { GroupType: '' }, - parentKey: string = '', - parameters: IParameter[] = [] - ): IParameter[] { - for (const key in data) { - let value = data[key] - if (typeof value !== 'undefined') { - let name: string | number = firstUpperCase(key) - - if (groups.GroupID === parseInt(key)) { - groups.GroupID++ - name = parseInt(key) - } - if (Array.isArray(value)) { - this.formatServiceParameters( - (value), - { - ...groups, - GroupID: 0 - }, - key, - parameters - ) - } else if (value instanceof Object) { - this.formatServiceParameters( - value, - { - ...groups, - GroupType: - typeof name === 'string' - ? name + groups.GroupType - : firstUpperCase(parentKey) + groups.GroupType - }, - key, - parameters - ) - } else { - parameters.push({ - Name: typeof name === 'string' ? name : firstUpperCase(parentKey), - Value: value, - ...groups - }) - } - } - } - return parameters - } -} diff --git a/src/Models/Response/BatchRequestResponse.ts b/src/Models/Response/BatchRequestResponse.ts new file mode 100644 index 00000000..5758d1b4 --- /dev/null +++ b/src/Models/Response/BatchRequestResponse.ts @@ -0,0 +1,15 @@ +import { HttpClientResponse } from './HttpClientResponse'; + +export class BatchRequestResponse extends HttpClientResponse { + get data(): BatchResponseData { + return this._data as any; + } +} + +export interface BatchResponseData { + message: string; + errors?: { + reference: string; + message: string; + }[]; +} diff --git a/src/Models/Response/HttpClientResponse.ts b/src/Models/Response/HttpClientResponse.ts new file mode 100644 index 00000000..8f9ef95f --- /dev/null +++ b/src/Models/Response/HttpClientResponse.ts @@ -0,0 +1,48 @@ +import { JsonModel } from '../Model'; +import { ReplyHandler } from '../../Handlers'; +import { ICredentials } from '../../Utils'; +import { AxiosResponse } from 'axios'; + +export interface HttpResponseConstructor { + new (httpResponse: AxiosResponse, data: object): IHttpClientResponse; +} + +export interface IHttpClientResponse { + httpResponse: AxiosResponse; +} + +export class HttpClientResponse implements IHttpClientResponse { + protected readonly _httpResponse: AxiosResponse; + protected readonly _data: object; + protected readonly _rawData: string; + + constructor(httpResponse: AxiosResponse) { + this._httpResponse = httpResponse; + this._rawData = httpResponse.data; + this._data = new JsonModel(httpResponse.data); + } + + get httpResponse(): AxiosResponse { + return this._httpResponse; + } + + get rawData(): string { + return this._rawData; + } + + get data() { + return this._data; + } + + validateResponse(credentials: ICredentials) { + return new ReplyHandler( + credentials, + JSON.parse(this._rawData ?? {}), + this.httpResponse.headers['authorization'], + this.httpResponse.request.url, + this.httpResponse.request.method + ) + .validate() + .isValid(); + } +} diff --git a/src/Models/Response/SpecificationRequestResponse.ts b/src/Models/Response/SpecificationRequestResponse.ts new file mode 100644 index 00000000..7a43dea9 --- /dev/null +++ b/src/Models/Response/SpecificationRequestResponse.ts @@ -0,0 +1,65 @@ +import { Str } from '../../Utils'; +import { HttpClientResponse } from './HttpClientResponse'; + +export class SpecificationRequestResponse extends HttpClientResponse { + get data(): ISpecificationRequestResponse { + return this._data as any; + } + + getActionRequestParameters(actionName: string): RequestParameter[] | undefined { + let actions = this.data.actions?.find((action) => { + if (Str.ciEquals(action.name, actionName)) { + return action; + } + })?.requestParameters; + if (actions) { + actions.sort((a, b) => a.name.localeCompare(b.name)); + } + return actions; + } +} + +type ListItemDescription = { + value: string; + description: string; + groupName: string; +}; +type SupportedCurrency = { + isoNumber: number; + code: string; + name: string; +}; + +type Action = { + name: string; + type: number; + default: boolean; + description: string; + requestParameters: RequestParameter[]; + responseParameters: RequestParameter[]; +}; +export type RequestParameter = { + listItemDescriptions?: ListItemDescription[]; + isRequestParameter: boolean; + name: string; + dataType: number; + maxLength: number; + maxOccurs: number; + required: boolean; + global: boolean; + group?: string; + description: string; + explanationHTML: string; + displayName: string; + inputPattern: string; + autoCompleteType: string; +}; + +export interface ISpecificationRequestResponse { + name: string; + version: number; + description: string; + actions?: Action[]; + supportedCurrencies?: SupportedCurrency[]; + customParameters?: Record; +} diff --git a/src/Models/Response/TransactionResponse.ts b/src/Models/Response/TransactionResponse.ts new file mode 100644 index 00000000..090f867f --- /dev/null +++ b/src/Models/Response/TransactionResponse.ts @@ -0,0 +1,225 @@ +import { ResponseStatus } from '../../Constants'; +import { DataFormatter } from '../../Utils'; +import { HttpClientResponse } from './HttpClientResponse'; + +import { IFormattedParameter } from '../IParameters'; + +export class TransactionResponse extends HttpClientResponse { + get data(): ITransactionResponse { + return this._data as any; + } + + getStatusCode() { + return this.data.status.code.code.toString(); + } + + getSubStatusCode() { + return this.data.status.subCode.code.toString(); + } + + isSuccess() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_SUCCESS; + } + + isFailed() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_FAILED; + } + + isCanceled() { + return ( + this.getStatusCode() === ResponseStatus.STATUSCODE_CANCELLED_BY_USER || + this.getStatusCode() === ResponseStatus.STATUSCODE_CANCELLED_BY_MERCHANT + ); + } + + isAwaitingConsumer() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_WAITING_ON_CONSUMER; + } + + isPendingProcessing() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_PENDING_PROCESSING; + } + + isWaitingOnUserInput() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_WAITING_ON_USER_INPUT; + } + + isRejected() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_REJECTED; + } + + isValidationFailure() { + return this.getStatusCode() === ResponseStatus.STATUSCODE_VALIDATION_FAILURE; + } + + hasRedirect() { + return this.data.requiredAction?.redirectURL.length > 0 && this.data.requiredAction?.name === 'Redirect'; + } + + getRedirectUrl() { + if (this.hasRedirect()) return this.data.requiredAction?.redirectURL; + return ''; + } + + getServices() { + return this.data.services; + } + + getMethod() { + return this.data.services?.[0].name; + } + + getServiceAction() { + return this.data.services?.[0].action; + } + + getCustomParameters() { + return DataFormatter.parametersReverseMap(this.data.customParameters?.list ?? []); + } + + getAdditionalParameters() { + return DataFormatter.parametersReverseMap( + this.data.additionalParameters?.additionalParameter ?? + (this.data.additionalParameters as Record)?.['list'] ?? + [] + ); + } + + getTransactionKey() { + return this.data.key; + } + + getPaymentKey() { + return this.data.paymentKey; + } + + getAmountDebit() { + return this.data.amountDebit; + } + + getAmountCredit() { + return this.data.amountCredit; + } + + hasError() { + return ( + this.data.requestErrors && + Object.keys(this.data.requestErrors).length > 0 && + ((this.data.requestErrors.channelErrors?.length ?? 0) > 0 || + (this.data.requestErrors.serviceErrors?.length ?? 0) > 0 || + (this.data.requestErrors.actionErrors?.length ?? 0) > 0 || + (this.data.requestErrors.parameterErrors?.length ?? 0) > 0 || + (this.data.requestErrors.customParameterErrors?.length ?? 0) > 0) + ); + } + + getErrorMessage() { + return this.data.status.code.description; + } +} + +export declare interface ITransactionResponse { + key: string; + name: string; + version: number; + description: string; + status: { + code: { + code: number | string; + description: string; + }; + subCode: { + code: number | string; + description: string; + }; + dateTime: string; + }; + requiredAction: { + redirectURL: string; + requestedInformation: { + name: string; + dataType: number; + maxLength: number; + required: boolean; + description: string; + }[]; + payRemainderDetails: { + remainderAmount: number; + currency: string; + groupTransaction: string; + }; + name: string; + typeDeprecated: number; + }; + services?: { + action: string; + name: string; + value: string; + versionAsProperty: number; + parameters: IFormattedParameter[]; + }[]; + customParameters?: { + list: IFormattedParameter[]; + }; + additionalParameters?: { + additionalParameter: IFormattedParameter[]; + }; + requestErrors?: { + channelErrors?: { + service: string; + action: string; + name: string; + error: string; + errorMessage: string; + }[]; + serviceErrors?: { + name: string; + error: string; + errorMessage: string; + }[]; + actionErrors?: { + service: string; + name: string; + error: string; + errorMessage: string; + }[]; + parameterErrors?: { + service: string; + action: string; + name: string; + error: string; + errorMessage: string; + }[]; + customParameterErrors?: { + name: string; + error: string; + errorMessage: string; + }[]; + }; + invoice: string; + serviceCode: string; + isTest: boolean; + currency: string; + amountDebit: number; + amountCredit: number; + transactionType: string; + mutationType: number; + relatedTransactions?: { + relationType: string; + relatedTransactionKey: string; + }[]; + consumerMessage?: { + mustRead: boolean; + cultureName: string; + title: string; + plainText: string; + htmlText: string; + }; + order: string; + issuingCountry: string; + startRecurrent: boolean; + recurring: boolean; + customerName: string; + payerHash: string; + paymentKey: string; +} diff --git a/src/Models/Response/index.ts b/src/Models/Response/index.ts new file mode 100644 index 00000000..54fd2701 --- /dev/null +++ b/src/Models/Response/index.ts @@ -0,0 +1,4 @@ +export * from './BatchRequestResponse'; +export * from './HttpClientResponse'; +export * from './SpecificationRequestResponse'; +export * from './TransactionResponse'; diff --git a/src/Models/ServiceList.ts b/src/Models/ServiceList.ts deleted file mode 100644 index c162823c..00000000 --- a/src/Models/ServiceList.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IParameter } from './Parameters' - -export declare interface IServices { - ServiceList: IServiceList[] -} -export declare interface IServiceList { - Name?: string - Action?: string - Version?: number - Parameters?: Array -} diff --git a/src/Models/ServiceParameters.ts b/src/Models/ServiceParameters.ts new file mode 100644 index 00000000..87957fc5 --- /dev/null +++ b/src/Models/ServiceParameters.ts @@ -0,0 +1,24 @@ +import { Model } from './Model'; +import { DataFormatter } from '../Utils'; +import { IParameter } from './IParameters'; + +export class ServiceParameter extends Model { + toParameterList(): IParameter[] { + return DataFormatter.serviceParametersMap(this.getData(), this.getGroups(), this.getCountable()); + } + + protected getGroups(groups: { [key: Capitalize]: Capitalize } = {}) { + return groups; + } + + protected getCountable(countable: Capitalize[] = []) { + return countable; + } + + protected getAllPropertyDescriptors( + descriptors = {}, + root: Model = ServiceParameter.prototype + ): { [p: string]: PropertyDescriptor } { + return super.getAllPropertyDescriptors(descriptors, root); + } +} diff --git a/src/Models/Services/IAddress.ts b/src/Models/Services/IAddress.ts deleted file mode 100644 index 020143ff..00000000 --- a/src/Models/Services/IAddress.ts +++ /dev/null @@ -1,10 +0,0 @@ -type IAddress = { - street: string - houseNumber?: string - houseNumberAdditional: string - zipcode: string - city: string - state?: string - country: string -} -export default IAddress diff --git a/src/Models/Services/IPhone.ts b/src/Models/Services/IPhone.ts deleted file mode 100644 index fab1400f..00000000 --- a/src/Models/Services/IPhone.ts +++ /dev/null @@ -1,8 +0,0 @@ - -type IPhone = { - landline: string - mobile: string - fax: string -} - -export default IPhone diff --git a/src/Models/Services/ITransactionResponse.ts b/src/Models/Services/ITransactionResponse.ts deleted file mode 100644 index 4d191ff5..00000000 --- a/src/Models/Services/ITransactionResponse.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { IServiceList } from '../ServiceList' - -export type AdditionalParameterResponse = { - Name: string - Value: string -} -export declare interface ITransactionResponse { - Key: string - Name: string - Version: number - Description: string - Status: { - Code: { - Code: number | string - Description: string - } - SubCode: { - Code: number | string - Description: string - } - DateTime: string - } - RequiredAction: { - RedirectURL: string - RequestedInformation: { - Name: string - DataType: number - MaxLength: number - Required: boolean - Description: string - }[] - PayRemainderDetails: { - RemainderAmount: number - Currency: string - GroupTransaction: string - } - Name: string - TypeDeprecated: number - } - Services: IServiceList[] - CustomParameters?: { - List: AdditionalParameterResponse[] - } - AdditionalParameters?: { - AdditionalParameter: AdditionalParameterResponse[] - } - RequestErrors: { - ChannelErrors: { - Service: string - Action: string - Name: string - Error: string - ErrorMessage: string - }[] - ServiceErrors: { - Name: string - Error: string - ErrorMessage: string - }[] - ActionErrors: { - Service: string - Name: string - Error: string - ErrorMessage: string - }[] - ParameterErrors: { - Service: string - Action: string - Name: string - Error: string - ErrorMessage: string - }[] - CustomParameterErrors: { - Name: string - Error: string - ErrorMessage: string - }[] - } - Invoice: string - ServiceCode: string - IsTest: boolean - Currency: string - AmountDebit: number - AmountCredit: number - TransactionType: string - MutationType: number - RelatedTransactions: { - RelationType: string - RelatedTransactionKey: string - }[] - ConsumerMessage: { - MustRead: boolean - CultureName: string - Title: string - PlainText: string - HtmlText: string - } - Order: string - IssuingCountry: string - StartRecurrent: boolean - Recurring: boolean - CustomerName: string - PayerHash: string - PaymentKey: string -} diff --git a/src/Models/TransactionResponse.ts b/src/Models/TransactionResponse.ts deleted file mode 100644 index 715d698b..00000000 --- a/src/Models/TransactionResponse.ts +++ /dev/null @@ -1,133 +0,0 @@ -import ResponseStatus from '../Constants/ResponseStatus' -import { ITransactionResponse } from './Services/ITransactionResponse' -import { firstLowerCase } from '../Utils/Functions' -import { Response } from '../Request/Response' -import { AxiosResponse } from 'axios' - -export class TransactionResponse extends Response { - get data(): ITransactionResponse { - return this._data - } - constructor(response: AxiosResponse) { - super(response) - } - getStatusCode() { - return this.data.Status.Code.Code.toString() - } - getSubStatusCode() { - return this.data.Status.SubCode.Code.toString() - } - isSuccess() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_SUCCESS - } - isFailed() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_FAILED - } - isCanceled() { - return ( - this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_CANCELLED_BY_USER || - this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_CANCELLED_BY_MERCHANT - ) - } - isAwaitingConsumer() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_WAITING_ON_CONSUMER - } - isPendingProcessing() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_PENDING_PROCESSING - } - isWaitingOnUserInput() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_WAITING_ON_USER_INPUT - } - isRejected() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_REJECTED - } - isValidationFailure() { - return this.getStatusCode() === ResponseStatus.BUCKAROO_STATUSCODE_VALIDATION_FAILURE - } - hasRedirect() { - return ( - this.data.RequiredAction?.RedirectURL.length > 0 && - this.data.RequiredAction?.Name === 'Redirect' - ) - } - getRedirectUrl() { - if (this.hasRedirect()) return this.data.RequiredAction?.RedirectURL - return '' - } - getServices() { - return this.data.Services - } - getMethod() { - return this.data.Services?.[0].Name - } - getServiceAction() { - return this.data.Services?.[0].Action - } - getServiceParameters() { - let parameters = this.data.Services?.[0].Parameters - let data: { [key: string]: any } = {} - if (parameters) { - parameters.forEach((param) => { - let current = param - - if (param.GroupType) { - data[firstLowerCase(param.GroupType)] = - data[firstLowerCase(param.GroupType)] || {} - data[firstLowerCase(param.GroupType)][firstLowerCase(param.Name)] = param.Value - } else { - data[firstLowerCase(current.Name)] = current.Value - } - }) - return data - } - } - getCustomParameters() { - let customParameters = this.data.CustomParameters?.List - let data: { [key: string]: any } = {} - if (customParameters) { - customParameters.forEach((param) => { - data[param.Name] = param.Value - }) - } - return data - } - getAdditionalParameters() { - let additionalParameters = this.data.AdditionalParameters?.AdditionalParameter - let data: { [key: string]: any } = {} - if (additionalParameters) { - additionalParameters.forEach((param) => { - data[param.Name] = param.Value - }) - } - return {} - } - getTransactionKey() { - return this.data.Key - } - getPaymentKey() { - return this.data.PaymentKey - } - hasError() { - return ( - this.data.RequestErrors && - Object.keys(this.data.RequestErrors).length > 0 && - (this.data.RequestErrors.ChannelErrors.length > 0 || - this.data.RequestErrors.ServiceErrors.length > 0 || - this.data.RequestErrors.ActionErrors.length > 0 || - this.data.RequestErrors.ParameterErrors.length > 0 || - this.data.RequestErrors.CustomParameterErrors.length > 0) - ) - } - getErrorMessages() { - const messages: { [errorType: string]: string } = {} - for (const [key, value] of Object.entries(this.data.RequestErrors)) { - if (value.length > 0) { - messages[key] = value.map((error) => error.ErrorMessage).join('') - } - } - return Object.entries(messages) - } - getErrorMessage() { - return this.data.Status.Code.Description - } -} diff --git a/src/Models/index.ts b/src/Models/index.ts new file mode 100644 index 00000000..69ee624b --- /dev/null +++ b/src/Models/index.ts @@ -0,0 +1,10 @@ +import IRequest, { IPaymentRequest, IRefundRequest } from './IRequest'; + +export * from './Model'; +export * from './Interfaces'; +export * from './Response'; +export * from './IParameters'; +export * from './IServiceList'; +export * from './ServiceParameters'; + +export { IRequest, IPaymentRequest, IRefundRequest }; \ No newline at end of file diff --git a/src/PaymentMethods/Afterpay/Model/Address.ts b/src/PaymentMethods/Afterpay/Model/Address.ts new file mode 100644 index 00000000..6bc27ee3 --- /dev/null +++ b/src/PaymentMethods/Afterpay/Model/Address.ts @@ -0,0 +1,27 @@ +import { Address as IAddress } from '../../../Models'; + +export default class Address extends IAddress { + get houseNumber(): string { + return this.get('streetNumber'); + } + + set houseNumber(phone: string) { + this.set('streetNumber', phone); + } + + get houseNumberAdditional(): string { + return this.get('streetNumberAdditional'); + } + + set houseNumberAdditional(phone: string) { + this.set('streetNumberAdditional', phone); + } + + get zipcode(): string { + return this.get('postalCode'); + } + + set zipcode(phone: string) { + this.set('postalCode', phone); + } +} diff --git a/src/PaymentMethods/Afterpay/Model/Article.ts b/src/PaymentMethods/Afterpay/Model/Article.ts index e2c3cfbc..2dfb9da8 100644 --- a/src/PaymentMethods/Afterpay/Model/Article.ts +++ b/src/PaymentMethods/Afterpay/Model/Article.ts @@ -1,21 +1,39 @@ -export type IAfterPayArticle = { - type?: - | 'PhysicalArticle' - | 'DigitalArticle' - | 'Giftcard' - | 'Discount' - | 'ShippingFee' - | 'Surcharge' - | 'Info' - | 'ShippingFees' - imageUrl?: string - url?: string - refundType?: 'Refund' | 'Return' - marketPlaceSellerId?: string - identifier: string - unitCode?: string - quantity: number - grossUnitPrice: number - vatPercentage: number - description: string +import { Article, IArticle } from '../../../Models'; + +export interface IAfterPayArticle extends Partial { + type?: string; + imageUrl?: string; + url?: string; + refundType?: 'Refund' | 'Return'; + marketPlaceSellerId?: string; +} + +export class AfterPayArticle extends Article { + constructor(article: Interface) { + super(article); + } + + get price(): number { + return this.get('grossUnitPrice'); + } + + set price(price: number) { + this.set('grossUnitPrice', price); + } + + set imageUrl(imageUrl: string) { + this.set('imageUrl', imageUrl); + } + + set url(url: string) { + this.set('url', url); + } + + set refundType(refundType: string) { + this.set('refundType', refundType); + } + + set marketPlaceSellerId(marketPlaceSellerId: string) { + this.set('marketPlaceSellerId', marketPlaceSellerId); + } } diff --git a/src/PaymentMethods/Afterpay/Model/Customer.ts b/src/PaymentMethods/Afterpay/Model/Customer.ts index 802f305e..0dec620c 100644 --- a/src/PaymentMethods/Afterpay/Model/Customer.ts +++ b/src/PaymentMethods/Afterpay/Model/Customer.ts @@ -1,49 +1,28 @@ -import RecipientCategory from '../../../Constants/RecipientCategory' +import { IAddress, ICompany, ICustomer, IPerson, IPhone, Model } from '../../../Models'; +import { RecipientCategory } from '../../../Constants'; +import Phone from './Phone'; +import Address from './Address'; +import { AfterPayCompany, AfterPayPerson } from './Recipient'; -type Salutation = 'Mr' | 'Mrs' | 'Miss' -type Customer = { - companyName?: string - firstName: string - lastName: string - birthDate?: string - street: string - streetNumber?: string - streetNumberAdditional?: string - postalCode?: string - city: string - country: string - email: string - careOf?: string - conversationLanguage?: 'NL' | 'FR' | 'DE' | 'FI' - identificationNumber?: string - customerNumber?: string - mobilePhone?: string - phone?: string - salutation?: Salutation -} -type Person = { - category: RecipientCategory.PERSON -} -type Company = { - category: RecipientCategory.COMPANY - companyName: string - identificationNumber: string -} -type countryNLBE = { - country: 'NL' | 'BE' - salutation: Salutation - birthDate: string - streetNumber: string - phone: string -} +export default class Customer extends Model implements ICustomer { + set recipient(recipient: IPerson | ICompany) { + this.set( + 'recipient', + recipient.category === RecipientCategory.COMPANY + ? new AfterPayCompany(recipient) + : new AfterPayPerson(recipient) + ); + } -type countryFI = { - country: 'FI' - identificationNumber: string -} -type countryDE = { - country: 'DE' -} + set address(address: IAddress) { + this.set('address', new Address(address)); + } -export type AfterPayCustomer = Customer & - ((Person | Company) & (countryNLBE | countryFI | countryDE)) + set email(email: string) { + this.set('email', email); + } + + set phone(phone: IPhone) { + this.set('phone', new Phone(phone)); + } +} diff --git a/src/PaymentMethods/Afterpay/Model/Pay.ts b/src/PaymentMethods/Afterpay/Model/Pay.ts index 8b133cec..95e54098 100644 --- a/src/PaymentMethods/Afterpay/Model/Pay.ts +++ b/src/PaymentMethods/Afterpay/Model/Pay.ts @@ -1,15 +1,68 @@ -import { IAfterPayArticle } from './Article' -import { Payload } from '../../../Models/ITransaction' -import { AfterPayCustomer } from './Customer' -export interface IPay extends Payload { - clientIP: string - billingCustomer: AfterPayCustomer - shippingCustomer?: AfterPayCustomer - article: IAfterPayArticle[] - bankAccount?: string - bankCode?: string - merchantImageUrl?: string - summaryImageUrl?: string - yourReference?: string - ourReference?: string +import { AfterPayArticle, IAfterPayArticle } from './Article'; +import Customer from './Customer'; +import { ICustomer, IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + clientIP: string; + billing: ICustomer; + shipping?: ICustomer; + articles: IAfterPayArticle[]; + bankAccount?: string; + bankCode?: string; + merchantImageUrl?: string; + summaryImageUrl?: string; + yourReference?: string; + ourReference?: string; +} + +export class Pay extends ServiceParameter { + set shipping(shipping: ICustomer) { + this.set('shipping', new Customer(shipping)); + } + + set billing(billing: ICustomer) { + this.set('billing', new Customer(billing)); + if (this.get('shipping') === undefined) { + this.shipping = billing; + } + } + + set articles(articles: IAfterPayArticle[]) { + this.set( + 'articles', + articles.map((article) => new AfterPayArticle(article)) + ); + } + + set bankAccount(bankAccount: string) { + this.set('bankAccount', bankAccount); + } + + set bankCode(bankCode: string) { + this.set('bankCode', bankCode); + } + + set merchantImageUrl(merchantImageUrl: string) { + this.set('merchantImageUrl', merchantImageUrl); + } + + set summaryImageUrl(summaryImageUrl: string) { + this.set('summaryImageUrl', summaryImageUrl); + } + + set ourReference(ourReference: string) { + this.set('ourReference', ourReference); + } + + protected getGroups() { + return super.getGroups({ + Billing: 'BillingCustomer', + Shipping: 'ShippingCustomer', + Articles: 'Article', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } } diff --git a/src/PaymentMethods/Afterpay/Model/Phone.ts b/src/PaymentMethods/Afterpay/Model/Phone.ts new file mode 100644 index 00000000..ba2be7a1 --- /dev/null +++ b/src/PaymentMethods/Afterpay/Model/Phone.ts @@ -0,0 +1,19 @@ +import { Phone as IPhone } from '../../../Models'; + +export default class Phone extends IPhone { + get mobile(): string { + return this.get('mobilePhone'); + } + + set mobile(phone: string) { + this.set('mobilePhone', phone); + } + + get landline(): string { + return this.get('phone'); + } + + set landline(phone: string) { + this.set('phone', phone); + } +} diff --git a/src/PaymentMethods/Afterpay/Model/Recipient.ts b/src/PaymentMethods/Afterpay/Model/Recipient.ts new file mode 100644 index 00000000..039787d4 --- /dev/null +++ b/src/PaymentMethods/Afterpay/Model/Recipient.ts @@ -0,0 +1,35 @@ +import { Company, IPerson, Person } from '../../../Models'; + +export class AfterPayCompany extends Company { + set title(title: string) { + this.set('salutation', title); + } + + set chamberOfCommerce(chamberOfCommerce: string) { + this.set('identificationNumber', chamberOfCommerce); + } +} + +export interface IAfterPayPerson extends IPerson { + customerNumber?: string; + identificationNumber?: string; + conversationLanguage?: string; +} + +export class AfterPayPerson extends Person { + constructor(data: IAfterPayPerson) { + super(data); + } + + set customerNumber(customerNumber: string) { + this.set('customerNumber', customerNumber); + } + + set identificationNumber(identificationNumber: string) { + this.set('identificationNumber', identificationNumber); + } + + set conversationLanguage(conversationLanguage: string) { + this.set('conversationLanguage', conversationLanguage); + } +} diff --git a/src/PaymentMethods/Afterpay/Model/Refund.ts b/src/PaymentMethods/Afterpay/Model/Refund.ts new file mode 100644 index 00000000..3ced4122 --- /dev/null +++ b/src/PaymentMethods/Afterpay/Model/Refund.ts @@ -0,0 +1,25 @@ +import { IRefundRequest, ServiceParameter } from '../../../Models'; +import { AfterPayArticle, IAfterPayArticle } from './Article'; + +export interface IRefund extends IRefundRequest { + articles?: IAfterPayArticle[]; +} + +export class Refund extends ServiceParameter { + set articles(articles: IAfterPayArticle[]) { + this.set( + 'articles', + articles.map((article) => new AfterPayArticle(article)) + ); + } + + protected getGroups() { + return super.getGroups({ + Articles: 'Article', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } +} diff --git a/src/PaymentMethods/Afterpay/index.ts b/src/PaymentMethods/Afterpay/index.ts index cf87e53e..8fdb0ec8 100644 --- a/src/PaymentMethods/Afterpay/index.ts +++ b/src/PaymentMethods/Afterpay/index.ts @@ -1,39 +1,45 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Model/Pay' -import { ICapture, RefundPayload } from '../../Models/ITransaction' -import { IAfterPayArticle } from './Model/Article' +import { IPay, Pay } from './Model/Pay'; +import { IRefund, Refund } from './Model/Refund'; +import { IPaymentRequest, IRefundRequest } from '../../Models'; +import { PayablePaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; export default class Afterpay extends PayablePaymentMethod { - protected _paymentName = 'afterpay' - protected _serviceVersion = 1 + protected _serviceVersion = 1; + + public defaultServiceCode(): ServiceCode { + return 'afterpay'; + } pay(payload: IPay) { - if (payload.billingCustomer) { - payload.shippingCustomer = payload.shippingCustomer || { ...payload.billingCustomer } - } - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload & { article?: IAfterPayArticle[] }) { - return super.refund(payload) + + refund(payload: IRefund) { + return super.refund(payload, new Refund(payload)); } + authorize(payload: IPay) { - this.action = 'Authorize' - return super.payTransaction(payload) + this.setServiceList('Authorize', new Pay(payload)); + return this.transactionRequest(payload); } - cancelAuthorize(payload: RefundPayload) { - this.action = 'CancelAuthorize' - return super.transactionRequest(payload) + + cancelAuthorize(payload: IRefundRequest) { + this.setServiceList('CancelAuthorize'); + return super.transactionRequest(payload); } - capture(payload: ICapture) { - this.action = 'Capture' - return super.transactionRequest(payload) + + capture(payload: IPaymentRequest) { + this.setServiceList('Capture', new Pay(payload)); + return super.transactionRequest(payload); } - payRemainder(payload:IPay) { - this.action = 'PayRemainder' - return super.transactionRequest(payload) + + payRemainder(payload: IPay) { + return super.payRemainder(payload, new Pay(payload)); } - authorizeRemainder(payload:IPay) { - this.action = 'AuthorizeRemainder' - return super.transactionRequest(payload) + + authorizeRemainder(payload: IPay) { + this.setServiceList('AuthorizeRemainder', new Pay(payload)); + return super.transactionRequest(payload); } } diff --git a/src/PaymentMethods/AfterpayDigiAccept/Model/Article.ts b/src/PaymentMethods/AfterpayDigiAccept/Model/Article.ts new file mode 100644 index 00000000..6dbb5972 --- /dev/null +++ b/src/PaymentMethods/AfterpayDigiAccept/Model/Article.ts @@ -0,0 +1,43 @@ +import { Article as ArticleClass } from '../../../Models'; + +export default class Article extends ArticleClass { + get identifier(): string { + return this.get('articleId'); + } + + set identifier(identifier: string) { + this.set('articleId', identifier); + } + + get quantity(): number { + return this.get('articleQuantity'); + } + + set quantity(quantity: number) { + this.set('articleQuantity', quantity); + } + + get price(): number { + return this.get('articleUnitprice'); + } + + set price(price: number) { + this.set('articleUnitprice', price); + } + + get vatCategory(): string { + return this.get('articleVatcategory'); + } + + set vatCategory(vatCategory: string) { + this.set('articleVatcategory', vatCategory); + } + + get description(): string { + return this.get('articleDescription'); + } + + set description(description: string) { + this.set('articleDescription', description); + } +} diff --git a/src/PaymentMethods/AfterpayDigiAccept/Model/Customer.ts b/src/PaymentMethods/AfterpayDigiAccept/Model/Customer.ts new file mode 100644 index 00000000..241983a9 --- /dev/null +++ b/src/PaymentMethods/AfterpayDigiAccept/Model/Customer.ts @@ -0,0 +1,26 @@ +import { Address } from '../Services/Address'; +import { ICustomer, Model } from '../../../Models'; +import { Phone } from '../Services/Phone'; +import { Recipient } from './Recipient'; + +export class Customer extends Model implements ICustomer { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set recipient(recipient: ICustomer['recipient']) { + this.set('recipient', new Recipient({ prefix: this.get('prefix'), ...recipient })); + } + + set address(address: ICustomer['address']) { + this.set('address', new Address({ prefix: this.get('prefix'), ...address })); + } + + set email(email: ICustomer['email']) { + this.set(`${this.get('prefix')}Email`, email); + } + + set phone(phone: ICustomer['phone']) { + this.set('phone', new Phone({ prefix: this.get('prefix'), ...phone })); + } +} diff --git a/src/PaymentMethods/AfterpayDigiAccept/Model/Pay.ts b/src/PaymentMethods/AfterpayDigiAccept/Model/Pay.ts new file mode 100644 index 00000000..5f5bea13 --- /dev/null +++ b/src/PaymentMethods/AfterpayDigiAccept/Model/Pay.ts @@ -0,0 +1,77 @@ +import { IArticle, ICustomer, IPaymentRequest, ServiceParameter } from '../../../Models'; +import Article from './Article'; +import { Customer } from './Customer'; + +export interface IPay extends IPaymentRequest { + b2b: boolean; + addressesDiffer: boolean; + customerIPAddress: string; + shippingCosts: number; + costCentre: string; + department: string; + establishmentNumber: number; + billing: ICustomer; + shipping?: ICustomer; + articles: Partial[]; +} + +export class Pay extends ServiceParameter implements Omit { + protected accept: boolean = true; + + set addressesDiffer(value: boolean) { + this.set('addressesDiffer', value); + } + + set articles(articles: IArticle[]) { + this.set( + 'articles', + articles.map((article) => new Article(article)) + ); + } + + set b2b(value: boolean) { + this.set('b2b', value); + } + + set billing(billing: ICustomer) { + this.set('billing', new Customer({ prefix: 'billing', ...billing })); + if (this.get('shipping') === undefined) { + this.shipping = new Customer({ prefix: 'shipping', ...billing }); + } + } + + set shipping(shipping: ICustomer) { + this.addressesDiffer = true; + this.set('shipping', new Customer({ prefix: 'shipping', ...shipping })); + } + + set costCentre(value: string) { + this.set('costCentre', value); + } + + set customerIPAddress(value: string) { + this.set('customerIPAddress', value); + } + + set department(value: string) { + this.set('department', value); + } + + set establishmentNumber(value: number) { + this.set('establishmentNumber', value); + } + + set shippingCosts(value: number) { + this.set('shippingCosts', value); + } + + protected getGroups() { + return super.getGroups({ + Articles: 'Article', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } +} diff --git a/src/PaymentMethods/AfterpayDigiAccept/Model/Recipient.ts b/src/PaymentMethods/AfterpayDigiAccept/Model/Recipient.ts new file mode 100644 index 00000000..9f9133e9 --- /dev/null +++ b/src/PaymentMethods/AfterpayDigiAccept/Model/Recipient.ts @@ -0,0 +1,39 @@ +import { Model } from '../../../Models'; + +export class Recipient extends Model { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set companyName(value: string) { + this.set('companyName', value); + } + + set vatNumber(value: string) { + this.set('vatNumber', value); + } + + set chamberOfCommerce(value: string) { + this.set('companyCOCRegistration', value); + } + + set initials(value: string) { + this.set(`${this.get('prefix')}Initials`, value); + } + + set birthDate(value: string) { + this.set(`${this.get('prefix')}BirthDate`, value); + } + + set gender(value: string) { + this.set(`${this.get('prefix')}Gender`, value); + } + + set firstName(value: string) { + this.set(`${this.get('prefix')}FirstName`, value); + } + + set lastName(value: string) { + this.set(`${this.get('prefix')}LastName`, value); + } +} diff --git a/src/PaymentMethods/AfterpayDigiAccept/Services/Address.ts b/src/PaymentMethods/AfterpayDigiAccept/Services/Address.ts new file mode 100644 index 00000000..765438fc --- /dev/null +++ b/src/PaymentMethods/AfterpayDigiAccept/Services/Address.ts @@ -0,0 +1,33 @@ +import { Model } from '../../../Models'; + +export class Address extends Model { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set street(value: string) { + this.set(`${this.get('prefix')}Street`, value); + } + + set houseNumber(value: string) { + this.set(`${this.get('prefix')}HouseNumber`, value); + } + + set city(value: string) { + this.set(`${this.get('prefix')}City`, value); + } + + set houseNumberAdditional(value: string) { + this.set(`${this.get('prefix')}HouseNumberSuffix`, value); + } + + set zipcode(value: string) { + this.set(`${this.get('prefix')}PostalCode`, value); + } + + set country(value: string) { + if (this.get('prefix') === 'shipping' && value === 'NL') { + this.set(`${this.get('prefix')}CountryCode`, value); + } else this.set(`${this.get('prefix')}Country`, value); + } +} diff --git a/src/PaymentMethods/AfterpayDigiAccept/Services/Phone.ts b/src/PaymentMethods/AfterpayDigiAccept/Services/Phone.ts new file mode 100644 index 00000000..a63d0cc1 --- /dev/null +++ b/src/PaymentMethods/AfterpayDigiAccept/Services/Phone.ts @@ -0,0 +1,11 @@ +import { Model } from '../../../Models'; + +export class Phone extends Model { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set mobile(value: string) { + this.set(`${this.get('prefix')}PhoneNumber`, value); + } +} diff --git a/src/PaymentMethods/AfterpayDigiAccept/index.ts b/src/PaymentMethods/AfterpayDigiAccept/index.ts index 1dfeb5f4..368e87dd 100644 --- a/src/PaymentMethods/AfterpayDigiAccept/index.ts +++ b/src/PaymentMethods/AfterpayDigiAccept/index.ts @@ -1,17 +1,45 @@ -import AfterpayClass from '../Afterpay' -import { Payload, RefundPayload } from '../../Models/ITransaction' -import { IPay } from '../Afterpay/Model/Pay' +import { IRefundRequest, IRequest } from '../../Models'; +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Model/Pay'; +import { ServiceCode } from '../../Utils'; -export default class AfterpayDigiAccept extends AfterpayClass { - protected _paymentName = 'afterpaydigiaccept' - protected _serviceVersion = 2 - pay(payload: Payload) { - return super.pay(payload) +export default class AfterpayDigiAccept extends PayablePaymentMethod { + protected _serviceVersion = 2; + + public defaultServiceCode(): ServiceCode { + return 'afterpaydigiaccept'; + } + + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } - authorize(payload: Payload) { - return super.authorize(payload) + + authorize(payload: IPay) { + this.setServiceList('Authorize', new Pay(payload)); + return super.transactionRequest(payload); + } + + cancelAuthorize(payload: IRefundRequest) { + this.setServiceList('CancelAuthorize'); + return super.transactionRequest(payload); + } + + capture(payload: IRequest) { + this.setServiceList('Capture'); + return super.transactionRequest(payload); + } + + payRemainder(payload: IPay) { + this.setServiceList('PayRemainder'); + return super.transactionRequest(payload); + } + + authorizeRemainder(payload: IPay) { + this.setServiceList('AuthorizeRemainder'); + return super.transactionRequest(payload); } } diff --git a/src/PaymentMethods/Alipay/index.ts b/src/PaymentMethods/Alipay/index.ts index 4c980c8a..395d78e7 100644 --- a/src/PaymentMethods/Alipay/index.ts +++ b/src/PaymentMethods/Alipay/index.ts @@ -1,14 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Payload, RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPaymentRequest, IRefundRequest, ServiceParameter } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class Alipay extends PayablePaymentMethod { - protected _paymentName = 'alipay' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'alipay'; + } - pay(payload: { useMobileView: boolean } & Payload) { - return super.pay(payload) + pay(payload: { useMobileView?: boolean } & IPaymentRequest) { + const serviceParameters = new ServiceParameter().set('useMobileView', payload.useMobileView); + return super.pay(payload, serviceParameters); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/ApplePay/Models/Pay.ts b/src/PaymentMethods/ApplePay/Models/Pay.ts index 09317ca4..30396b7a 100644 --- a/src/PaymentMethods/ApplePay/Models/Pay.ts +++ b/src/PaymentMethods/ApplePay/Models/Pay.ts @@ -1,6 +1,16 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, ServiceParameter } from '../../../Models'; -export interface IPay extends Payload { - paymentData: string - customerCardName: string +export interface IPay extends IPaymentRequest { + paymentData: string; + customerCardName: string; +} + +export class Pay extends ServiceParameter { + set paymentData(value: string) { + this.set('paymentData', value); + } + + set customerCardName(value: string) { + this.set('customerCardName', value); + } } diff --git a/src/PaymentMethods/ApplePay/index.ts b/src/PaymentMethods/ApplePay/index.ts index e1821ccd..9cba272c 100644 --- a/src/PaymentMethods/ApplePay/index.ts +++ b/src/PaymentMethods/ApplePay/index.ts @@ -1,15 +1,23 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { IPaymentRequest, IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class ApplePay extends PayablePaymentMethod { - protected _paymentName = 'applepay' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'applepay'; + } pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); + } + + refund(payload: IRefundRequest) { + return super.refund(payload); } - refund(payload: RefundPayload) { - return super.refund(payload) + + payRedirect(payload: IPaymentRequest) { + this.setPayPayload(payload); + return this.transactionRequest(); } } diff --git a/src/PaymentMethods/Bancontact/Models/Pay.ts b/src/PaymentMethods/Bancontact/Models/Pay.ts index c544299f..38f02d63 100644 --- a/src/PaymentMethods/Bancontact/Models/Pay.ts +++ b/src/PaymentMethods/Bancontact/Models/Pay.ts @@ -1,17 +1,29 @@ -import { ITransaction, Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, IRequest, ServiceParameter } from '../../../Models'; -export interface IPay extends Payload { - saveToken?: boolean +export interface IPay extends IPaymentRequest { + saveToken?: boolean; } -export interface IPayEncrypted extends Payload { - encryptedCardData: string + +export interface IPayEncrypted extends IPaymentRequest { + encryptedCardData: string; } -export interface IPayComplete extends ITransaction { - encryptedCardData: string - originalTransactionKey: string + +export interface IPayComplete extends IRequest { + encryptedCardData: string; + originalTransactionKey: string; } -export interface IPayOneClick extends ITransaction { - originalTransactionKey: string - amountDebit: number +export interface IPayOneClick extends IRequest { + originalTransactionKey: string; + amountDebit: number; +} + +export class Pay extends ServiceParameter { + set encryptedCardData(value: string) { + this.set('encryptedCardData', value); + } + + set saveToken(value: boolean) { + this.set('saveToken', value); + } } diff --git a/src/PaymentMethods/Bancontact/index.ts b/src/PaymentMethods/Bancontact/index.ts index 085a7653..02cbb37a 100644 --- a/src/PaymentMethods/Bancontact/index.ts +++ b/src/PaymentMethods/Bancontact/index.ts @@ -1,46 +1,43 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay, IPayComplete, IPayEncrypted, IPayOneClick } from './Models/Pay' -import {ICapture, RefundPayload} from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, IPayComplete, IPayEncrypted, IPayOneClick, Pay } from './Models/Pay'; +import { IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class Bancontact extends PayablePaymentMethod { - protected _paymentName = 'bancontactmrcash' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'bancontactmrcash'; + } pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } + authenticate(payload: IPay) { - return this.authorize(payload) - } - authorize(payload: IPay) { - this.action = 'Authorize' - return this.payTransaction(payload) + this.setServiceList('Authenticate', new Pay(payload)); + return this.transactionRequest(payload); } + payOneClick(payload: IPayOneClick) { - this.action = 'PayOneClick' - return this.transactionInvoice(payload) + this.setServiceList('PayOneClick', new Pay(payload)); + return this.transactionRequest(payload); } + payEncrypted(payload: IPayEncrypted) { - this.action = 'PayEncrypted' - return this.transactionInvoice(payload) + this.setServiceList('PayEncrypted', new Pay(payload)); + return this.transactionRequest(payload); } + completePayment(payload: IPayComplete) { - this.action = 'CompletePayment' - return this.dataRequest(payload) + this.setServiceList('CompletePayment', new Pay(payload)); + return this.dataRequest(payload); } + payRecurring(payload: IPayOneClick) { - this.action = 'PayRecurring' - return this.transactionInvoice(payload) - } - capture(payload:ICapture) { - this.action = 'Capture' - return this.transactionInvoice(payload) - } - cancelAuthorize(payload) { - this.action = 'CancelAuthorize' - return this.transactionRequest(payload) + this.setServiceList('PayRecurring', new Pay(payload)); + return this.transactionRequest(payload); } } diff --git a/src/PaymentMethods/BankTransfer/Models/Pay.ts b/src/PaymentMethods/BankTransfer/Models/Pay.ts index 48952681..b4e6bee8 100644 --- a/src/PaymentMethods/BankTransfer/Models/Pay.ts +++ b/src/PaymentMethods/BankTransfer/Models/Pay.ts @@ -1,12 +1,44 @@ -import Gender from '../../../Constants/Gender' -import { Payload } from '../../../Models/ITransaction' - -export interface IPay extends Payload { - customerFirstName: string - customerLastName: string - customerEmail: string - customerGender?: Gender - sendMail?: boolean - dateDue?: string - customerCountry?: string +import { IPaymentRequest, IPerson, Person, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + customer: Partial; + sendMail?: boolean; + dateDue?: string; + customerCountry?: string; +} + +class BankTransferPerson extends Person { + set firstName(value: string) { + this.set('customerFirstName', value); + } + + set lastName(value: string) { + this.set('customerLastName', value); + } + + set gender(value: string) { + this.set('customerGender', value); + } +} + +export class Pay extends ServiceParameter { + set sendMail(sendMail: boolean) { + this.set('sendMail', sendMail); + } + + set dateDue(dateDue: string) { + this.set('dateDue', dateDue); + } + + set country(country: string) { + this.set('customerCountry', country); + } + + set customer(person: IPerson) { + this.set('customer', new BankTransferPerson(person)); + } + + set email(email: string) { + this.set('customerEmail', email); + } } diff --git a/src/PaymentMethods/BankTransfer/index.ts b/src/PaymentMethods/BankTransfer/index.ts index 54f4bb2d..01c494b4 100644 --- a/src/PaymentMethods/BankTransfer/index.ts +++ b/src/PaymentMethods/BankTransfer/index.ts @@ -1,15 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; -export default class Banktransfer extends PayablePaymentMethod { - protected _paymentName = 'transfer' - protected _serviceVersion = 1 +export default class BankTransfer extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'transfer'; + } pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/Belfius/index.ts b/src/PaymentMethods/Belfius/index.ts index aad2e131..5dc756fb 100644 --- a/src/PaymentMethods/Belfius/index.ts +++ b/src/PaymentMethods/Belfius/index.ts @@ -1,14 +1,17 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Payload, RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPaymentRequest, IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class Belfius extends PayablePaymentMethod { - protected _paymentName = 'belfius' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'belfius'; + } - pay(payload: Payload) { - return super.pay(payload) + pay(payload: IPaymentRequest) { + return super.pay(payload); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/Billink/Models/Address.ts b/src/PaymentMethods/Billink/Models/Address.ts new file mode 100644 index 00000000..4bb28620 --- /dev/null +++ b/src/PaymentMethods/Billink/Models/Address.ts @@ -0,0 +1,15 @@ +import { Address as AddressClass } from '../../../Models'; + +export class Address extends AddressClass { + set houseNumber(houseNumber: string) { + this.set('streetNumber', houseNumber); + } + + set houseNumberAdditional(houseNumberAdditional: string) { + this.set('streetNumberAdditional', houseNumberAdditional); + } + + set zipcode(zipcode: string) { + this.set('postalCode', zipcode); + } +} diff --git a/src/PaymentMethods/Billink/Models/Article.ts b/src/PaymentMethods/Billink/Models/Article.ts index 86e1d683..cf4b5055 100644 --- a/src/PaymentMethods/Billink/Models/Article.ts +++ b/src/PaymentMethods/Billink/Models/Article.ts @@ -1,7 +1,15 @@ -export type IBillinkArticle = { - quantity: number - description: string - identifier: string - grossUnitPriceIncl: number - grossUnitPriceExcl: number +import { Article as ArticleClass, IArticle } from '../../../Models'; + +export interface IBillinkArticle extends Partial { + priceExcl: number; +} + +export class Article extends ArticleClass { + set priceExcl(priceExcl: number) { + this.set('grossUnitPriceExcl', priceExcl); + } + + set price(price: number) { + this.set('grossUnitPriceIncl', price); + } } diff --git a/src/PaymentMethods/Billink/Models/Capture.ts b/src/PaymentMethods/Billink/Models/Capture.ts new file mode 100644 index 00000000..3f381150 --- /dev/null +++ b/src/PaymentMethods/Billink/Models/Capture.ts @@ -0,0 +1,21 @@ +import { Article, IBillinkArticle } from './Article'; +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface ICapture extends IPaymentRequest { + articles?: IBillinkArticle[]; +} + +export class Capture extends ServiceParameter { + set articles(articels: IBillinkArticle[]) { + this.set( + 'articles', + articels.map((article) => new Article(article)) + ); + } + + protected getGroups() { + return super.getGroups({ + Articles: 'Article', + }); + } +} diff --git a/src/PaymentMethods/Billink/Models/Customer.ts b/src/PaymentMethods/Billink/Models/Customer.ts index 31182985..9caaf3f4 100644 --- a/src/PaymentMethods/Billink/Models/Customer.ts +++ b/src/PaymentMethods/Billink/Models/Customer.ts @@ -1,19 +1,42 @@ -type Salutation = 'Male' | 'Female' | 'Unknown' -export type Customer = { - chamberOfCommerce: string - initials: string - salutation?: Salutation - firstName: string - lastName: string - birthDate?: string - street: string - streetNumber: number - streetNumberAdditional?: string - postalCode: string - city: string - country?: 'NL' | 'BE' - email?: string - careOf?: string - mobilePhone?: string - phone?: string +import { Phone } from './Phone'; +import { Address } from './Address'; +import { Company, Customer, IAddress, ICompany, IPerson, IPhone, Person } from '../../../Models'; +import { RecipientCategory } from '../../../Constants'; + +export class BillinkCustomer extends Customer { + set address(address: IAddress) { + this.set('address', new Address(address)); + } + + set phone(phone: IPhone) { + this.set('phone', new Phone(phone)); + } + + set recipient(recipient: IPerson | ICompany) { + if (recipient.category === RecipientCategory.PERSON) { + this.set('recipient', new BillinkPerson(recipient)); + } else if (recipient.category === RecipientCategory.COMPANY) { + this.set('recipient', new BillinkCompany(recipient)); + } else throw new Error('Invalid recipient category'); + } +} + +export class BillinkPerson extends Person { + set category(category: RecipientCategory.PERSON) { + this.set('category', 'B2C'); + } + + set title(title: string) { + this.set('salutation', title); + } +} + +export class BillinkCompany extends Company { + set category(category: RecipientCategory.COMPANY) { + this.set('category', 'B2B'); + } + + set title(title: string) { + this.set('salutation', title); + } } diff --git a/src/PaymentMethods/Billink/Models/Pay.ts b/src/PaymentMethods/Billink/Models/Pay.ts index f61e34f7..8ad8e807 100644 --- a/src/PaymentMethods/Billink/Models/Pay.ts +++ b/src/PaymentMethods/Billink/Models/Pay.ts @@ -1,12 +1,56 @@ -import { Payload } from '../../../Models/ITransaction' -import { IBillinkArticle } from './Article' -import { Customer } from './Customer' - -export interface IPay extends Payload { - billingCustomer: Customer - shippingCustomer?: Customer - article: IBillinkArticle[] - trackandtrace?: string - VATNumber?: string - summaryImageUrl?: string +import { ICustomer, IPaymentRequest, ServiceParameter } from '../../../Models'; +import { Article, IBillinkArticle } from './Article'; +import { BillinkCustomer } from './Customer'; + +export interface IPay extends IPaymentRequest { + billing: ICustomer; + shipping?: ICustomer; + articles: IBillinkArticle[]; + trackandtrace?: string; + VATNumber?: string; + summaryImageUrl?: string; +} + +export class Pay extends ServiceParameter { + set billing(billing: ICustomer) { + this.set('billing', new BillinkCustomer(billing)); + if (this.get('shipping') === undefined) { + this.shipping = billing; + } + } + + set shipping(shipping: ICustomer) { + this.set('shipping', new BillinkCustomer(shipping)); + } + + set articles(articles: IBillinkArticle[]) { + this.set( + 'articles', + articles.map((article) => new Article(article)) + ); + } + + set trackandtrace(trackandtrace: string) { + this.set('trackandtrace', trackandtrace); + } + + set VATNumber(VATNumber: string) { + this.set('VATNumber', VATNumber); + } + + set summaryImageUrl(summaryImageUrl: string) { + this.set('summaryImageUrl', summaryImageUrl); + } + + protected getGroups() { + return super.getGroups({ + Billing: 'BillingCustomer', + Shipping: 'ShippingCustomer', + Articles: 'Article', + }); + } + + protected getCountable(countable: Capitalize[] = []): Capitalize[] { + return super.getCountable(['Articles']); + } } diff --git a/src/PaymentMethods/Billink/Models/Phone.ts b/src/PaymentMethods/Billink/Models/Phone.ts new file mode 100644 index 00000000..a3200b00 --- /dev/null +++ b/src/PaymentMethods/Billink/Models/Phone.ts @@ -0,0 +1,15 @@ +import { Phone as PhoneClass } from '../../../Models'; + +export class Phone extends PhoneClass { + set fax(fax: string) { + this.set('mobilePhone', fax); + } + + set landline(landline: string) { + this.set('mobilePhone', landline); + } + + set mobile(mobile: string) { + this.set('mobilePhone', mobile); + } +} diff --git a/src/PaymentMethods/Billink/Models/Refund.ts b/src/PaymentMethods/Billink/Models/Refund.ts new file mode 100644 index 00000000..b6b04cfd --- /dev/null +++ b/src/PaymentMethods/Billink/Models/Refund.ts @@ -0,0 +1,11 @@ +import { IRefundRequest, ServiceParameter } from '../../../Models'; + +export interface IRefund extends IRefundRequest { + refundReason?: string; +} + +export class Refund extends ServiceParameter { + set refundReason(value: string) { + this.set('refundreason', value); + } +} diff --git a/src/PaymentMethods/Billink/index.ts b/src/PaymentMethods/Billink/index.ts index 507037d1..521456b3 100644 --- a/src/PaymentMethods/Billink/index.ts +++ b/src/PaymentMethods/Billink/index.ts @@ -1,26 +1,37 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { ICapture, RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { IRefund, Refund } from './Models/Refund'; +import { Capture, ICapture } from './Models/Capture'; +import { ServiceCode } from '../../Utils'; export default class Billink extends PayablePaymentMethod { - protected _paymentName = 'Billink' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'billink'; + } + pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefund) { + return super.refund(payload, new Refund(payload)); } + authorize(payload: IPay) { - this.action = 'Authorize' - return super.transactionRequest(payload) + this.setPayPayload(payload); + this.setServiceList('Authorize', new Pay(payload)); + return super.transactionRequest(); } - cancelAuthorize(payload: RefundPayload) { - this.action = 'CancelAuthorize' - return super.transactionRequest(payload) + + cancelAuthorize(payload: IRefund) { + this.setPayload(payload); + this.setServiceList('CancelAuthorize', new Refund(payload)); + return super.transactionRequest(); } + capture(payload: ICapture) { - this.action = 'Capture' - return super.transactionRequest(payload) + this.setPayPayload(payload); + this.setServiceList('Capture', new Capture(payload)); + return super.transactionRequest(); } } diff --git a/src/PaymentMethods/BuckarooVoucher/Models/Create.ts b/src/PaymentMethods/BuckarooVoucher/Models/Create.ts index 55821836..b83c9c3e 100644 --- a/src/PaymentMethods/BuckarooVoucher/Models/Create.ts +++ b/src/PaymentMethods/BuckarooVoucher/Models/Create.ts @@ -1,13 +1,35 @@ -import { ITransaction } from '../../../Models/ITransaction' +import { IRequest, ServiceParameter } from '../../../Models'; -export interface ICreate extends ITransaction { - groupReference?: string +export interface ICreate extends IRequest { + groupReference?: string; /** * 1 = Single * 2 = Multiple */ - usageType: 1 | 2 - validFrom: string - validUntil?: string - creationBalance: number + usageType: 1 | 2; + validFrom: string; + validUntil?: string; + creationBalance: number; +} + +export class Create extends ServiceParameter { + set groupReference(value: string) { + this.set('groupReference', value); + } + + set usageType(value: 1 | 2) { + this.set('usageType', value); + } + + set validFrom(value: string) { + this.set('validFrom', value); + } + + set validUntil(value: string) { + this.set('validUntil', value); + } + + set creationBalance(value: number) { + this.set('creationBalance', value); + } } diff --git a/src/PaymentMethods/BuckarooVoucher/Models/Pay.ts b/src/PaymentMethods/BuckarooVoucher/Models/Pay.ts index c5fe50bb..043ab3d8 100644 --- a/src/PaymentMethods/BuckarooVoucher/Models/Pay.ts +++ b/src/PaymentMethods/BuckarooVoucher/Models/Pay.ts @@ -1,5 +1,11 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, ServiceParameter } from '../../../Models'; -export interface IPay extends Payload { - voucherCode: string +export interface IPay extends IPaymentRequest { + voucherCode: string; +} + +export class Pay extends ServiceParameter { + set voucherCode(voucherCode: string) { + this.set('voucherCode', voucherCode); + } } diff --git a/src/PaymentMethods/BuckarooVoucher/index.ts b/src/PaymentMethods/BuckarooVoucher/index.ts index c1be1ac5..10e48575 100644 --- a/src/PaymentMethods/BuckarooVoucher/index.ts +++ b/src/PaymentMethods/BuckarooVoucher/index.ts @@ -1,27 +1,30 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { RefundPayload } from '../../Models/ITransaction' -import { ICreate } from './Models/Create' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { IRequest } from '../../Models'; +import { Create, ICreate } from './Models/Create'; +import { ServiceCode } from '../../Utils'; -export default class Buckaroovoucher extends PayablePaymentMethod { - protected _paymentName = 'buckaroovoucher' +export default class BuckarooVoucher extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'buckaroovoucher'; + } pay(payload: IPay) { - return super.pay(payload) - } - refund(payload: RefundPayload) { - return super.refund(payload) + return super.pay(payload, new Pay(payload)); } - getBalance(payload: Pick) { - this.action = 'GetBalance' - return this.dataRequest(payload) + + getBalance(payload: IRequest & Pick) { + this.setServiceList('GetBalance', new Pay(payload)); + return this.dataRequest(payload); } - createApplication(payload: ICreate) { - this.action = 'CreateApplication' - return this.dataRequest(payload) + + create(payload: IRequest & ICreate) { + this.setServiceList('CreateApplication', new Create(payload)); + return this.dataRequest(payload); } - deactivateVoucher(payload: Pick) { - this.action = 'DeactivateVoucher' - return this.dataRequest(payload) + + deactivate(payload: IRequest & Pick) { + this.setServiceList('DeactivateVoucher', new Pay(payload)); + return this.dataRequest(payload); } } diff --git a/src/PaymentMethods/BuckarooWallet/Models/BankAccount.ts b/src/PaymentMethods/BuckarooWallet/Models/BankAccount.ts new file mode 100644 index 00000000..479db4b8 --- /dev/null +++ b/src/PaymentMethods/BuckarooWallet/Models/BankAccount.ts @@ -0,0 +1,7 @@ +import { BankAccount as BankAccountClass } from '../../../Models'; + +export class BankAccount extends BankAccountClass { + set iban(value: string) { + this.set('consumerIban', value); + } +} diff --git a/src/PaymentMethods/BuckarooWallet/Models/Customer.ts b/src/PaymentMethods/BuckarooWallet/Models/Customer.ts new file mode 100644 index 00000000..59f504b4 --- /dev/null +++ b/src/PaymentMethods/BuckarooWallet/Models/Customer.ts @@ -0,0 +1,14 @@ +import { Person } from '../../../Models'; +import { RecipientCategory } from '../../../Constants'; + +export class Customer extends Person { + set category(value: RecipientCategory.PERSON) {} + + set firstName(value: string) { + this.set('consumerFirstName', value); + } + + set lastName(value: string) { + this.set('consumerLastName', value); + } +} diff --git a/src/PaymentMethods/BuckarooWallet/Models/Wallet.ts b/src/PaymentMethods/BuckarooWallet/Models/Wallet.ts index 525def91..6603ca00 100644 --- a/src/PaymentMethods/BuckarooWallet/Models/Wallet.ts +++ b/src/PaymentMethods/BuckarooWallet/Models/Wallet.ts @@ -1,20 +1,38 @@ -import { ITransaction, Payload, RefundPayload } from '../../../Models/ITransaction' +import { IBankAccount, IPerson, IRequest, ServiceParameter } from '../../../Models'; +import { Customer } from './Customer'; +import { BankAccount } from './BankAccount'; -interface consumer { - consumerFirstName?: string - consumerLastName?: string - consumerEmail?: string - consumerIban?: string +export interface IWallet extends IRequest { + invoice?: string; + walletId?: string; + customer?: Partial; + bankAccount?: Partial; + walletMutationGuid?: string; + status?: string; } -export interface IWallet extends ITransaction, consumer { - invoice: string - walletId: string -} -export interface IWalletPay extends Payload, consumer { - invoice: string - walletId: string -} -export interface IWalletRefund extends RefundPayload { - invoice: string - walletId: string + +export class Wallet extends ServiceParameter { + set walletId(value: string) { + this.set('walletId', value); + } + + set customer(value: Partial) { + this.set('customer', new Customer(value)); + } + + set email(value: string) { + this.set('consumerEmail', value); + } + + set status(value: string) { + this.set('status', value); + } + + set walletMutationGuid(value: string) { + this.set('walletMutationGuid', value); + } + + set bankAccount(value: IBankAccount) { + this.set('bankAccount', new BankAccount(value)); + } } diff --git a/src/PaymentMethods/BuckarooWallet/index.ts b/src/PaymentMethods/BuckarooWallet/index.ts index a5b0f4f4..7257e0b4 100644 --- a/src/PaymentMethods/BuckarooWallet/index.ts +++ b/src/PaymentMethods/BuckarooWallet/index.ts @@ -1,46 +1,64 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IWallet, IWalletPay, IWalletRefund } from './Models/Wallet' -import { ITransaction } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IWallet, Wallet } from './Models/Wallet'; +import { IPaymentRequest, IRefundRequest, IRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class BuckarooWallet extends PayablePaymentMethod { - protected _paymentName = 'BuckarooWalletCollecting' - protected _serviceVersion = 1 - pay(payload: IWalletPay) { - return super.pay(payload) + public defaultServiceCode(): ServiceCode { + return 'BuckarooWalletCollecting'; } - refund(payload: IWalletRefund) { - return super.refund(payload) + + pay(payload: IWallet & IPaymentRequest) { + return super.pay(payload, new Wallet(payload)); } - deposit(payload: IWalletRefund) { - this.action = 'Deposit' - return super.transactionRequest(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } - reserve(payload: IWalletRefund) { - this.action = 'Reserve' - return super.transactionRequest(payload) + + create(payload: IWallet & IRequest) { + this._requiredFields = ['currency']; + this.setPayload(payload); + this.setServiceList('Create', new Wallet(payload)); + return this.dataRequest(); } - withdrawal(payload: IWalletPay) { - this.action = 'Withdrawal' - return super.transactionRequest(payload) + + deposit(payload: IWallet & IRefundRequest) { + this.setPayload(payload); + this.setServiceList('Deposit', new Wallet(payload)); + return super.transactionRequest(); } - cancel(payload: ITransaction & { walletMutationGuid: string }) { - this.action = 'CancelReservation' - return super.transactionRequest(payload) + + reserve(payload: IWallet & IRefundRequest) { + this.setPayload(payload); + this.setServiceList('Reserve', new Wallet(payload)); + return super.transactionRequest(); } - create(payload: IWallet) { - this.action = 'Create' - return this.dataRequest(payload) + + withdrawal(payload: IWallet & IPaymentRequest) { + this.setPayPayload(payload); + this.setServiceList('Withdrawal', new Wallet(payload)); + return super.transactionRequest(); } - update() { - this.action = 'Update' - return this.dataRequest() + + cancel(payload: IPaymentRequest & { walletMutationGuid: string }) { + this.setPayPayload(payload); + this.setServiceList('Cancel', new Wallet(payload)); + return super.transactionRequest(); } - getInfo() { - this.action = 'Getinfo' - return this.dataRequest() + + update(payload: IWallet) { + this.setServiceList('Update', new Wallet(payload)); + return this.dataRequest(payload); } - release() { - this.action = 'Release' - return this.dataRequest() + + getInfo(payload: IWallet) { + this.setServiceList('GetInfo', new Wallet(payload)); + return this.dataRequest(payload); + } + + release(payload: IWallet & IRefundRequest) { + this.setServiceList('Release', new Wallet(payload)); + return this.dataRequest(payload); } } diff --git a/src/PaymentMethods/CreditCard/Models/CardData.ts b/src/PaymentMethods/CreditCard/Models/CardData.ts new file mode 100644 index 00000000..36e60c67 --- /dev/null +++ b/src/PaymentMethods/CreditCard/Models/CardData.ts @@ -0,0 +1,11 @@ +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface ICardData extends IPaymentRequest { + encryptedCardData: string; +} + +export class CardData extends ServiceParameter { + set encryptedCardData(value: string) { + this.set('encryptedCardData', value); + } +} diff --git a/src/PaymentMethods/CreditCard/Models/Pay.ts b/src/PaymentMethods/CreditCard/Models/Pay.ts deleted file mode 100644 index 5d726071..00000000 --- a/src/PaymentMethods/CreditCard/Models/Pay.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Payload } from '../../../Models/ITransaction' - -export interface IEncrypted extends Payload { - encryptedCardData: string -} -export interface ISecurityCodePay extends Payload { - encryptedSecurityCode: string -} diff --git a/src/PaymentMethods/CreditCard/Models/SecurityCode.ts b/src/PaymentMethods/CreditCard/Models/SecurityCode.ts new file mode 100644 index 00000000..62acc9ed --- /dev/null +++ b/src/PaymentMethods/CreditCard/Models/SecurityCode.ts @@ -0,0 +1,11 @@ +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface ISecurityCode extends IPaymentRequest { + encryptedSecurityCode: string; +} + +export class SecurityCode extends ServiceParameter { + set encryptedSecurityCode(value: string) { + this.set('encryptedSecurityCode', value); + } +} diff --git a/src/PaymentMethods/CreditCard/index.ts b/src/PaymentMethods/CreditCard/index.ts index 3a705428..fcbcadf4 100644 --- a/src/PaymentMethods/CreditCard/index.ts +++ b/src/PaymentMethods/CreditCard/index.ts @@ -1,50 +1,64 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IEncrypted, ISecurityCodePay } from './Models/Pay' -import { ICapture, Payload, RefundPayload } from '../../Models/ITransaction' - -export type AddName = T & { name: string } -export default class Creditcard extends PayablePaymentMethod { - pay(payload: AddName) { - return super.pay(payload) - } - refund(payload: AddName) { - return super.refund(payload) - } - payEncrypted(payload: AddName) { - this.action = 'PayEncrypted' - return super.pay(payload) - } - payWithSecurityCode(payload: AddName) { - this.action = 'PayWithSecurityCode' - return super.pay(payload) - } - authorize(payload: AddName) { - this.action = 'Authorize' - return super.transactionRequest(payload) - } - authorizeWithSecurityCode(payload: AddName) { - this.action = 'AuthorizeWithSecurityCode' - return super.transactionRequest(payload) - } - authorizeEncrypted(payload: AddName) { - this.action = 'AuthorizeEncrypted' - return super.transactionRequest(payload) - } - cancelAuthorize(payload: AddName) { - this.action = 'CancelAuthorize' - return super.transactionRequest(payload) - } - capture(payload: AddName) { - this.action = 'Capture' - return super.transactionRequest(payload) - } - payRecurrent(payload: AddName) { - this.action = 'PayRecurrent' - return super.transactionRequest(payload) - } - setRequest(payload: any) { - this.paymentName = payload.name || this._paymentName - delete payload.name - super.setRequest(payload) +import { PayablePaymentMethod } from '../../Services'; +import { IPaymentRequest, IRefundRequest, IRequest } from '../../Models'; +import { CardData, ICardData } from './Models/CardData'; +import { ISecurityCode, SecurityCode } from './Models/SecurityCode'; +import { ServiceCode } from '../../Utils'; + +export default class CreditCard extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'CreditCard'; + } + + payEncrypted(payload: ICardData) { + this.setPayPayload(payload); + this.setServiceList('PayEncrypted', new CardData(payload)); + return super.transactionRequest(); + } + + payWithSecurityCode(payload: ISecurityCode) { + this.setPayPayload(payload); + this.setServiceList('PayWithSecurityCode', new SecurityCode(payload)); + return super.transactionRequest(); + } + + authorize(payload: IPaymentRequest) { + this.setPayPayload(payload); + this.setServiceList('Authorize'); + return super.transactionRequest(); + } + + authorizeWithSecurityCode(payload: ISecurityCode) { + this.setPayPayload(payload); + this.setServiceList('AuthorizeWithSecurityCode', new SecurityCode(payload)); + return super.transactionRequest(); + } + + authorizeEncrypted(payload: ICardData) { + this.setPayPayload(payload); + this.setServiceList('AuthorizeEncrypted', new CardData(payload)); + return super.transactionRequest(); + } + + cancelAuthorize(payload: IRefundRequest) { + this.setServiceList('CancelAuthorize'); + return super.transactionRequest(payload); + } + + capture(payload: IRequest) { + this.setPayPayload(payload); + this.setServiceList('Capture'); + return super.transactionRequest(); + } + + payRecurrent(payload: IRequest) { + this.setPayPayload(payload); + this.setServiceList('PayRecurrent'); + return super.transactionRequest(); + } + + payRemainderEncrypted(payload: ICardData) { + this.setPayPayload(payload); + this.setServiceList('PayRemainderEncrypted', new CardData(payload)); + return super.transactionRequest(); } } diff --git a/src/PaymentMethods/CreditClick/Models/Pay.ts b/src/PaymentMethods/CreditClick/Models/Pay.ts index c24528d7..f2afb8d4 100644 --- a/src/PaymentMethods/CreditClick/Models/Pay.ts +++ b/src/PaymentMethods/CreditClick/Models/Pay.ts @@ -1,7 +1,16 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, IPerson, ServiceParameter } from '../../../Models'; -export interface Pay extends Payload { - firstName?: string - lastName?: string - email?: string +export interface IPay extends IPaymentRequest { + person: Partial; + email?: string; +} + +export class Pay extends ServiceParameter { + set person(value: Partial) { + this.set('person', value); + } + + set email(value: string) { + this.set('email', value); + } } diff --git a/src/PaymentMethods/CreditClick/Models/Refund.ts b/src/PaymentMethods/CreditClick/Models/Refund.ts index 24301516..3b45743a 100644 --- a/src/PaymentMethods/CreditClick/Models/Refund.ts +++ b/src/PaymentMethods/CreditClick/Models/Refund.ts @@ -1,11 +1,16 @@ -import { RefundPayload } from '../../../Models/ITransaction' +import { IRefundRequest, ServiceParameter } from '../../../Models'; -export interface Refund extends RefundPayload { - description: string - refundReason: - | 'Duplicate' - | 'Fraudulent' - | 'GoodsNotDelivered' - | 'RequestedByCustomer' - | 'TechnicalError' +export interface IRefund extends IRefundRequest { + description?: string; + refundReason: 'Duplicate' | 'Fraudulent' | 'GoodsNotDelivered' | 'RequestedByCustomer' | 'TechnicalError'; +} + +export class Refund extends ServiceParameter { + set description(value: string) { + this.set('description', value); + } + + set refundReason(value: IRefund['refundReason']) { + this.set('refundreason', value); + } } diff --git a/src/PaymentMethods/CreditClick/index.ts b/src/PaymentMethods/CreditClick/index.ts index b1859815..f6b73705 100644 --- a/src/PaymentMethods/CreditClick/index.ts +++ b/src/PaymentMethods/CreditClick/index.ts @@ -1,14 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Pay } from './Models/Pay' -import { Refund } from './Models/Refund' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { IRefund, Refund } from './Models/Refund'; +import { ServiceCode } from '../../Utils'; export default class CreditClick extends PayablePaymentMethod { - protected _paymentName = 'creditclick' + public defaultServiceCode(): ServiceCode { + return 'creditclick'; + } - pay(payload: Pay) { - return super.pay(payload) + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); } - refund(payload: Refund) { - return super.refund(payload) + + refund(payload: IRefund) { + return super.refund(payload, new Refund(payload)); } } diff --git a/src/PaymentMethods/CreditManagement/Models/AddOrUpdateProductLines.ts b/src/PaymentMethods/CreditManagement/Models/AddOrUpdateProductLines.ts index 46ba36b5..3f9c0673 100644 --- a/src/PaymentMethods/CreditManagement/Models/AddOrUpdateProductLines.ts +++ b/src/PaymentMethods/CreditManagement/Models/AddOrUpdateProductLines.ts @@ -1,8 +1,30 @@ -import { ICreditArticle } from './Article' -import { ITransaction } from '../../../Models/ITransaction' +import { CreditArticle, ICreditArticle } from './Article'; +import { IRequest, ServiceParameter } from '../../../Models'; -export interface AddOrUpdateProductLines { - invoiceKey: string - article: ICreditArticle[] +export interface IAddOrUpdateProductLines extends IRequest { + invoiceKey: string; + articles: ICreditArticle[]; +} + +export class AddOrUpdateProductLines extends ServiceParameter { + set invoiceKey(value: string) { + this.set('invoiceKey', value); + } + + set articles(value: ICreditArticle[]) { + this.set( + 'articles', + value.map((article) => new CreditArticle(article)) + ); + } + + protected getGroups() { + return super.getGroups({ + Articles: 'ProductLine', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } } -export type IAddOrUpdateProductLines = AddOrUpdateProductLines & ITransaction diff --git a/src/PaymentMethods/CreditManagement/Models/Address.ts b/src/PaymentMethods/CreditManagement/Models/Address.ts new file mode 100644 index 00000000..03e9a23c --- /dev/null +++ b/src/PaymentMethods/CreditManagement/Models/Address.ts @@ -0,0 +1,7 @@ +import { Address as AddressClass } from '../../../Models'; + +export class Address extends AddressClass { + set houseNumberAdditional(value: string) { + this.set('houseNumberSuffix', value); + } +} diff --git a/src/PaymentMethods/CreditManagement/Models/Article.ts b/src/PaymentMethods/CreditManagement/Models/Article.ts index 99107c79..9c25a403 100644 --- a/src/PaymentMethods/CreditManagement/Models/Article.ts +++ b/src/PaymentMethods/CreditManagement/Models/Article.ts @@ -1,16 +1,68 @@ -export interface ICreditArticle { - type: 'Regular' | 'SubTotal' | 'Discount' | 'TotalAmountExVat' | 'TotalVat' | 'TotalAmount' - productName: string - quantity: number - pricePerUnit: number - totalVat: number - vatPercentage: number - productGroupName?: string - productGroupOrderIndex?: number - productOrderIndex?: number - unitOfMeasurement?: string - discountPercentage?: number - totalDiscount?: number - totalAmountExVat?: number - totalAmount?: number +import { Article, IArticle } from '../../../Models'; + +export interface ICreditArticle extends Partial { + totalVat: number; + productLine?: string; + productGroupName?: string; + productGroupOrderIndex?: number; + productOrderIndex?: number; + unitOfMeasurement?: string; + discountPercentage?: number; + totalDiscount?: number; + totalAmountExVat?: number; + totalAmount?: number; +} + +export class CreditArticle extends Article implements ICreditArticle { + set identifier(value: string) { + this.set('productId', value); + } + + set description(value: string) { + this.set('productName', value); + } + + set price(value: number) { + this.set('pricePerUnit', value); + } + + set productLine(value: string) { + this.set('productLine', value); + } + + set productGroupName(value: string) { + this.set('productGroupName', value); + } + + set productGroupOrderIndex(value: number) { + this.set('productGroupOrderIndex', value); + } + + set productOrderIndex(value: number) { + this.set('productOrderIndex', value); + } + + set unitOfMeasurement(value: string) { + this.set('unitOfMeasurement', value); + } + + set discountPercentage(value: number) { + this.set('discountPercentage', value); + } + + set totalDiscount(value: number) { + this.set('totalDiscount', value); + } + + set totalVat(value: number) { + this.set('totalVat', value); + } + + set totalAmountExVat(value: number) { + this.set('totalAmountExVat', value); + } + + set totalAmount(value: number) { + this.set('totalAmount', value); + } } diff --git a/src/PaymentMethods/CreditManagement/Models/CreditNote.ts b/src/PaymentMethods/CreditManagement/Models/CreditNote.ts index f4d83678..efc8b6d9 100644 --- a/src/PaymentMethods/CreditManagement/Models/CreditNote.ts +++ b/src/PaymentMethods/CreditManagement/Models/CreditNote.ts @@ -1,10 +1,31 @@ -import { ITransaction } from '../../../Models/ITransaction' - -export interface CreditNote { - originalInvoiceNumber: string - invoiceDate: string - invoiceAmount: string - invoiceAmountVAT: string - sendCreditNoteMessage: string +import { IRequest, ServiceParameter } from '../../../Models'; + +export interface ICreditNote extends IRequest { + originalInvoiceNumber: string; + invoiceDate: string; + invoiceAmount: string; + invoiceAmountVAT: string; + sendCreditNoteMessage: string; +} + +export class CreditNote extends ServiceParameter implements ICreditNote { + set originalInvoiceNumber(value: string) { + this.set('originalInvoiceNumber', value); + } + + set invoiceDate(value: string) { + this.set('invoiceDate', value); + } + + set invoiceAmount(value: string) { + this.set('invoiceAmount', value); + } + + set invoiceAmountVAT(value: string) { + this.set('invoiceAmountVAT', value); + } + + set sendCreditNoteMessage(value: string) { + this.set('sendCreditNoteMessage', value); + } } -export type ICreditNote = CreditNote & ITransaction diff --git a/src/PaymentMethods/CreditManagement/Models/Debtor.ts b/src/PaymentMethods/CreditManagement/Models/Debtor.ts index c9eeba95..ba26980d 100644 --- a/src/PaymentMethods/CreditManagement/Models/Debtor.ts +++ b/src/PaymentMethods/CreditManagement/Models/Debtor.ts @@ -1,14 +1,26 @@ -import { IInvoice } from './Invoice' +import { ServiceParameter } from '../../../Models'; +import { IDebtorInfo } from './DebtorInfo'; -export interface Debtor { - addressUnreachable?: boolean - - emailUnreachable?: boolean +export interface IDebtor extends IDebtorInfo { + person: { + culture: string; + lastName: string; + }; +} - mobileUnreachable?: boolean +export class Debtor extends ServiceParameter { + set debtor(value: string) { + this.set('debtor', value); + } - landlineUnreachable?: boolean + set person(value: string) { + this.set('person', value); + } - faxUnreachable?: boolean + protected getGroups() { + return super.getGroups({ + Debtor: 'Debtor', + Person: 'Person', + }); + } } -export type IDebtor = Debtor & IInvoice diff --git a/src/PaymentMethods/CreditManagement/Models/DebtorInfo.ts b/src/PaymentMethods/CreditManagement/Models/DebtorInfo.ts new file mode 100644 index 00000000..da1856b9 --- /dev/null +++ b/src/PaymentMethods/CreditManagement/Models/DebtorInfo.ts @@ -0,0 +1,23 @@ +import { Debtor as DebtorClass, IDebtor, IRequest, ServiceParameter } from '../../../Models'; + +export interface IDebtorInfo extends IRequest { + debtor: IDebtor; +} + +export class DebtorInfo extends ServiceParameter { + set debtor(debtor: IDebtor) { + this.set('debtor', new Debtor(debtor)); + } + + protected getGroups() { + return super.getGroups({ + Debtor: 'Debtor', + }); + } +} + +class Debtor extends DebtorClass { + set code(value: string) { + this.set('DebtorCode', value); + } +} diff --git a/src/PaymentMethods/CreditManagement/Models/Invoice.ts b/src/PaymentMethods/CreditManagement/Models/Invoice.ts index 58600cb3..551c29f0 100644 --- a/src/PaymentMethods/CreditManagement/Models/Invoice.ts +++ b/src/PaymentMethods/CreditManagement/Models/Invoice.ts @@ -1,49 +1,117 @@ -import IPhone from '../../../Models/Services/IPhone' -import IAddress from '../../../Models/Services/IAddress' -import { ICreditArticle } from './Article' -import { ITransaction } from '../../../Models/ITransaction' -import Gender from '../../../Constants/Gender' - -export interface Invoice { - invoiceAmount: number - invoiceAmountVAT?: number - invoiceDate: string - dueDate: string - schemeKey?: string - maxStepIndex?: Number - allowedServices?: string - allowedServicesAfterDueDate?: string - code: string - person: { - culture: string - title: string - initials: string - firstName: string - lastName: string - lastNamePrefix: string - gender: Gender - birthDate: string - placeOfBirth: string - } - company: { - culture: string - name: string - vatApplicable: boolean - vatNumber: string - chamberOfCommerce: string - } - address: Omit & { - houseNumberSuffix?: string - postalCode: string - } - debtor: { - code: string - } - email?: { email: string } - phone: IPhone - productLine?:ICreditArticle[] - invoiceNumber?: string - applyStartRecurrent?: boolean - [key: string]: any +import { IAddress, ICompany, IDebtor, IPerson, IPhone, IRequest, ServiceParameter } from '../../../Models'; +import { CreditArticle, ICreditArticle } from './Article'; +import { Address } from './Address'; + +export interface IInvoice extends IRequest { + invoiceAmount: number; + invoiceAmountVAT?: number; + invoiceDate: string; + dueDate: string; + schemeKey?: string; + maxStepIndex?: number; + allowedServices?: string; + allowedServicesAfterDueDate?: string; + code?: string; + person: Partial; + company: Partial; + address: Partial; + debtor: IDebtor; + email?: string; + phone: IPhone; + articles?: ICreditArticle[]; + invoiceNumber?: string; + applyStartRecurrent?: boolean; +} + +export class Invoice extends ServiceParameter implements IInvoice { + set invoiceAmount(value: number) { + this.set('invoiceAmount', value); + } + + set invoiceAmountVAT(value: number) { + this.set('invoiceAmountVAT', value); + } + + set invoiceDate(value: string) { + this.set('invoiceDate', value); + } + + set dueDate(value: string) { + this.set('dueDate', value); + } + + set schemeKey(value: string) { + this.set('schemeKey', value); + } + + set maxStepIndex(value: number) { + this.set('maxStepIndex', value); + } + + set allowedServices(value: string) { + this.set('allowedServices', value); + } + + set allowedServicesAfterDueDate(value: string) { + this.set('allowedServicesAfterDueDate', value); + } + + set code(value: string) { + this.set('code', value); + } + + set person(value: Partial) { + this.set('person', value); + } + + set company(value: Partial) { + this.set('company', value); + } + + set address(value: Partial) { + this.set('address', new Address(value)); + } + + set debtor(value: IDebtor) { + this.set('debtor', value); + } + + set email(value: string) { + this.set('email', value); + } + + set phone(value: IPhone) { + this.set('phone', value); + } + + set articles(value: ICreditArticle[]) { + this.set( + 'articles', + value.map((article) => new CreditArticle(article)) + ); + } + + set invoiceNumber(value: string) { + this.set('invoiceNumber', value); + } + + set applyStartRecurrent(value: boolean) { + this.set('applyStartRecurrent', value); + } + + protected getGroups() { + return super.getGroups({ + Articles: 'ProductLine', + Address: 'Address', + Company: 'Company', + Person: 'Person', + Debtor: 'Debtor', + Email: 'Email', + Phone: 'Phone', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } } -export type IInvoice = Invoice & ITransaction diff --git a/src/PaymentMethods/CreditManagement/Models/PaymentPlan.ts b/src/PaymentMethods/CreditManagement/Models/PaymentPlan.ts index 8eca7925..19badb97 100644 --- a/src/PaymentMethods/CreditManagement/Models/PaymentPlan.ts +++ b/src/PaymentMethods/CreditManagement/Models/PaymentPlan.ts @@ -1,15 +1,57 @@ -import { ITransaction } from '../../../Models/ITransaction' -import CreditManagementInstallmentInterval from '../../../Constants/CreditManagementInstallmentInterval' - -export interface IPaymentPlan extends ITransaction { - includedInvoiceKey: string - dossierNumber: string - installmentCount: number - installmentAmount: number - initialAmount?: number - startDate: string - interval: CreditManagementInstallmentInterval - paymentPlanCostAmount: number - paymentPlanCostAmountVat?: number - recipientEmail: string +import { CreditManagementInstallmentInterval } from '../../../Constants'; +import { IRequest, ServiceParameter } from '../../../Models'; + +export interface IPaymentPlan extends IRequest { + includedInvoiceKey?: string; + dossierNumber?: string; + installmentCount?: number; + installmentAmount?: number; + initialAmount?: number; + startDate?: string; + interval?: CreditManagementInstallmentInterval; + paymentPlanCostAmount?: number; + paymentPlanCostAmountVat?: number; + recipientEmail?: string; +} + +export class PaymentPlan extends ServiceParameter implements IPaymentPlan { + set includedInvoiceKey(value: string) { + this.set('includedInvoiceKey', value); + } + + set dossierNumber(value: string) { + this.set('dossierNumber', value); + } + + set installmentCount(value: number) { + this.set('installmentCount', value); + } + + set installmentAmount(value: number) { + this.set('installmentAmount', value); + } + + set initialAmount(value: number) { + this.set('initialAmount', value); + } + + set startDate(value: string) { + this.set('startDate', value); + } + + set interval(value: CreditManagementInstallmentInterval) { + this.set('interval', value); + } + + set paymentPlanCostAmount(value: number) { + this.set('paymentPlanCostAmount', value); + } + + set paymentPlanCostAmountVat(value: number) { + this.set('paymentPlanCostAmountVat', value); + } + + set recipientEmail(value: string) { + this.set('recipientEmail', value); + } } diff --git a/src/PaymentMethods/CreditManagement/Models/multiInfoInvoice.ts b/src/PaymentMethods/CreditManagement/Models/multiInfoInvoice.ts index f9b12c58..32acaaea 100644 --- a/src/PaymentMethods/CreditManagement/Models/multiInfoInvoice.ts +++ b/src/PaymentMethods/CreditManagement/Models/multiInfoInvoice.ts @@ -1,6 +1,16 @@ -import { ServiceParameters } from '../../../Utils/Types' +import { IRequest, ServiceParameter } from '../../../Models'; -export interface IMultiInfoInvoice extends ServiceParameters { - invoice: string - invoices?: { invoiceNumber: string }[] +export interface IMultiInfoInvoice extends IRequest { + invoice: string; + invoices?: { invoiceNumber: string }[]; +} + +export class MultiInfoInvoice extends ServiceParameter { + set invoices(value: { invoiceNumber: string }[]) { + this.set('invoices', value); + } + + protected getCountable() { + return super.getCountable(['Invoices']); + } } diff --git a/src/PaymentMethods/CreditManagement/index.ts b/src/PaymentMethods/CreditManagement/index.ts index 3dbd7ba5..e8cfc973 100644 --- a/src/PaymentMethods/CreditManagement/index.ts +++ b/src/PaymentMethods/CreditManagement/index.ts @@ -1,86 +1,86 @@ -import { IConfig } from '../../Utils/Types' -import PaymentMethod from '../PaymentMethod' -import { IInvoice } from './Models/Invoice' -import { ICreditNote } from './Models/CreditNote' -import { uniqid } from '../../Utils/Functions' -import { IDebtor } from './Models/Debtor' -import { IPaymentPlan } from './Models/PaymentPlan' -import { ITransaction } from '../../Models/ITransaction' -import { IMultiInfoInvoice } from './Models/multiInfoInvoice' -import { AddOrUpdateProductLines, IAddOrUpdateProductLines } from './Models/AddOrUpdateProductLines' +import { PaymentMethod } from '../../Services'; +import { IInvoice, Invoice } from './Models/Invoice'; +import { CreditNote, ICreditNote } from './Models/CreditNote'; +import { Debtor, IDebtor } from './Models/Debtor'; +import { IPaymentPlan, PaymentPlan } from './Models/PaymentPlan'; +import { IMultiInfoInvoice, MultiInfoInvoice } from './Models/multiInfoInvoice'; +import { AddOrUpdateProductLines, IAddOrUpdateProductLines } from './Models/AddOrUpdateProductLines'; +import { IRequest, ServiceParameter } from '../../Models'; +import { DebtorInfo, IDebtorInfo } from './Models/DebtorInfo'; +import { ServiceCode } from '../../Utils'; export default class CreditManagement extends PaymentMethod { - protected _paymentName = 'CreditManagement3' - protected _requiredFields: Array = ['currency'] + protected _serviceVersion = 1; + protected _requiredFields = ['currency']; - protected _serviceVersion = 1 - createInvoice(payload: IInvoice): Promise { - this.action = 'CreateInvoice' - payload.invoice = payload.invoice || uniqid() - return this.dataRequest(payload) + public defaultServiceCode(): ServiceCode { + return 'CreditManagement3'; } + + createInvoice(payload: IInvoice) { + this.setServiceList('CreateInvoice', new Invoice(payload)); + return this.dataRequest(payload); + } + createCombinedInvoice(payload: IInvoice) { - this.action = 'CreateCombinedInvoice' - payload.invoice = payload.invoice || uniqid() - this.setRequest(payload) - return this + this.setServiceList('CreateCombinedInvoice', new Invoice(payload)); + return this.transactionRequest(payload); } - createCreditNote(payload: ICreditNote) { - this.action = 'CreateCreditNote' - return this.dataRequest(payload) + createCreditNote(payload: ICreditNote) { + this.setServiceList('CreateCreditNote', new CreditNote(payload)); + return this.dataRequest(payload); } - addOrUpdateDebtor(payload: IDebtor) { - this.action = 'AddOrUpdateDebtor' - return this.dataRequest(payload) + addOrUpdateDebtor(payload: IDebtor) { + this.setServiceList('AddOrUpdateDebtor', new Debtor(payload)); + return this.dataRequest(payload); } - createPaymentPlan(payload: IPaymentPlan) { - this.action = 'CreatePaymentPlan' - return this.dataRequest(payload) + createPaymentPlan(payload: IPaymentPlan) { + this.setServiceList('CreatePaymentPlan', new PaymentPlan(payload)); + return this.dataRequest(payload); } - terminatePaymentPlan(payload: Required>) { - this.action = 'TerminatePaymentPlan' - return this.dataRequest(payload) + terminatePaymentPlan(payload: Required>) { + this.setServiceList('TerminatePaymentPlan', new PaymentPlan(payload)); + return this.dataRequest(payload); } - pauseInvoice(payload: Required>) { - this.action = 'PauseInvoice' - return this.dataRequest(payload) + pauseInvoice(payload: Required>) { + this.setServiceList('PauseInvoice'); + return this.dataRequest(payload); } - unpauseInvoice(payload: Required>) { - this.action = 'UnpauseInvoice' - return this.dataRequest(payload) + unpauseInvoice(payload: Required>) { + this.setServiceList('UnpauseInvoice'); + return this.dataRequest(payload); } invoiceInfo(payload: IMultiInfoInvoice) { - this.action = 'InvoiceInfo' - - return this.dataRequest(payload) + this.setServiceList('InvoiceInfo', new MultiInfoInvoice(payload)); + return this.dataRequest(payload); } - debtorInfo(payload: Required>) { - this.action = 'DebtorInfo' - return this.dataRequest(payload) + debtorInfo(payload: IDebtorInfo) { + this.setServiceList('DebtorInfo', new DebtorInfo(payload)); + return this.dataRequest(payload); } addOrUpdateProductLines(payload: IAddOrUpdateProductLines) { - this.action = 'AddOrUpdateProductLines' - return this.dataRequest(payload) + this.setServiceList('AddOrUpdateProductLines', new AddOrUpdateProductLines(payload)); + return this.dataRequest(payload); } resumeDebtorFile(payload: { debtorFileGuid: string }) { - this.action = 'ResumeDebtorFile' - - return this.dataRequest(payload) + let debtorFile = new ServiceParameter().set('debtorFileGuid', payload.debtorFileGuid); + this.setServiceList('ResumeDebtorFile', debtorFile); + return this.dataRequest(payload); } pauseDebtorFile(payload: { debtorFileGuid: string }) { - this.action = 'PauseDebtorFile' - - return this.dataRequest(payload) + let debtorFile = new ServiceParameter().set('debtorFileGuid', payload.debtorFileGuid); + this.setServiceList('PauseDebtorFile', debtorFile); + return this.dataRequest(payload); } } diff --git a/src/PaymentMethods/EPS/index.ts b/src/PaymentMethods/EPS/index.ts index 7347b1e9..23367174 100644 --- a/src/PaymentMethods/EPS/index.ts +++ b/src/PaymentMethods/EPS/index.ts @@ -1,10 +1,8 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; export default class EPS extends PayablePaymentMethod { - protected _paymentName = 'eps' - - refund(payload: RefundPayload) { - return super.refund(payload) + public defaultServiceCode(): ServiceCode { + return 'eps'; } } diff --git a/src/PaymentMethods/Emandates/Models/ICreate.ts b/src/PaymentMethods/Emandates/Models/ICreate.ts deleted file mode 100644 index cecae8e3..00000000 --- a/src/PaymentMethods/Emandates/Models/ICreate.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { ITransaction } from '../../../Models/ITransaction' - -interface Create extends ITransaction { - debtorReference: string - sequenceType: 0 | 1 - purchaseId: string - mandateId?: string - language: string - emandateReason?: string - maxAmount?: number -} -export type ICreate = Create & - ({ debtorBankId: string } | Required>) diff --git a/src/PaymentMethods/Emandates/Models/IModify.ts b/src/PaymentMethods/Emandates/Models/IModify.ts deleted file mode 100644 index 5c133af6..00000000 --- a/src/PaymentMethods/Emandates/Models/IModify.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ITransaction } from '../../../Models/ITransaction' - -interface Modify extends Omit { - originalMandateId: string - debtorBankId?: string -} -export type IModify = Modify & - ({ debtorBankId: string } | Required>) diff --git a/src/PaymentMethods/Emandates/Models/Mandate.ts b/src/PaymentMethods/Emandates/Models/Mandate.ts new file mode 100644 index 00000000..b8106a90 --- /dev/null +++ b/src/PaymentMethods/Emandates/Models/Mandate.ts @@ -0,0 +1,51 @@ +import { IRequest, ServiceParameter } from '../../../Models'; + +export interface IMandate extends IRequest { + mandateId?: string; + debtorBankId?: string; + debtorReference?: string; + sequenceType?: 0 | 1; + purchaseId?: string; + language?: string; + emandateReason?: string; + maxAmount?: number; + originalMandateId?: string; +} + +export class Mandate extends ServiceParameter { + set debtorBankId(value: string) { + this.set('debtorBankId', value); + } + + set debtorReference(value: string) { + this.set('debtorReference', value); + } + + set sequenceType(value: number) { + this.set('sequenceType', value); + } + + set purchaseId(value: string) { + this.set('purchaseId', value); + } + + set mandateId(value: string) { + this.set('mandateId', value); + } + + set language(value: string) { + this.set('language', value); + } + + set emandateReason(value: string) { + this.set('emandateReason', value); + } + + set maxAmount(value: number) { + this.set('maxAmount', value); + } + + set originalMandateId(value: string) { + this.set('originalMandateId', value); + } +} diff --git a/src/PaymentMethods/Emandates/index.ts b/src/PaymentMethods/Emandates/index.ts index 8649a10f..c9fe6548 100644 --- a/src/PaymentMethods/Emandates/index.ts +++ b/src/PaymentMethods/Emandates/index.ts @@ -1,31 +1,36 @@ -import PaymentMethod from '../PaymentMethod' -import { IConfig } from '../../Utils/Types' -import { ICreate } from './Models/ICreate' -import { IModify } from './Models/IModify' +import { PaymentMethod } from '../../Services'; +import { IConfig, ServiceCode } from '../../Utils'; +import { IMandate, Mandate } from './Models/Mandate'; export default class Emandates extends PaymentMethod { - protected _paymentName = 'emandate' + _requiredFields: Array = ['currency']; - _requiredFields: Array = ['currency'] + public defaultServiceCode(): ServiceCode { + return 'emandate'; + } issuerList() { - this.action = 'GetIssuerList' - return this.dataRequest() + this.setServiceList('GetIssuerList'); + return this.dataRequest(); } - createMandate(payload: ICreate) { - this.action = 'CreateMandate' - return this.dataRequest(payload) + + createMandate(payload: IMandate) { + this.setServiceList('CreateMandate', new Mandate(payload)); + return this.dataRequest(payload); } - status(payload: { mandateId: string }) { - this.action = 'GetStatus' - return this.dataRequest(payload) + + status(payload: IMandate) { + this.setServiceList('GetStatus', new Mandate(payload)); + return this.dataRequest(payload); } - modifyMandate(payload: IModify) { - this.action = 'ModifyMandate' - return this.dataRequest(payload) + + modifyMandate(payload: IMandate) { + this.setServiceList('ModifyMandate', new Mandate(payload)); + return this.dataRequest(payload); } - cancelMandate(payload: { mandateId: string; purchaseId: string }) { - this.action = 'CancelMandate' - return this.dataRequest(payload) + + cancelMandate(payload: IMandate) { + this.setServiceList('CancelMandate', new Mandate(payload)); + return this.dataRequest(payload); } } diff --git a/src/PaymentMethods/GiftCard/Models/Pay.ts b/src/PaymentMethods/GiftCard/Models/Pay.ts new file mode 100644 index 00000000..aa527904 --- /dev/null +++ b/src/PaymentMethods/GiftCard/Models/Pay.ts @@ -0,0 +1,60 @@ +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export default interface IPay extends IPaymentRequest { + fashionChequeCardNumber?: string; + fashionChequePin?: string; + intersolveCardnumber?: string; + intersolvePIN?: string; + tcsCardnumber?: string; + tcsValidationCode?: string; + lastName?: string; + email?: string; + cardNumber?: string; + pin?: string; +} + +export class Pay extends ServiceParameter { + set fashionChequeCardNumber(value: string) { + this.set('fashionChequeCardNumber', value); + } + + set fashionChequePin(value: string) { + this.set('fashionChequePin', value); + } + + set intersolveCardnumber(value: string) { + this.set('intersolveCardnumber', value); + } + + set intersolvePIN(value: string) { + this.set('intersolvePIN', value); + } + + set tcsCardnumber(value: string) { + this.set('tcsCardnumber', value); + } + + set tcsValidationCode(value: string) { + this.set('tcsValidationCode', value); + } + + set lastName(value: string) { + this.set('lastName', value); + } + + set email(value: string) { + this.set('email', value); + } + + set cardNumber(value: string) { + this.set('cardNumber', value); + } + + set pin(value: string) { + this.set('pin', value); + } + + set issuer(value: string) { + this.set('issuer', value); + } +} diff --git a/src/PaymentMethods/GiftCard/Models/Refund.ts b/src/PaymentMethods/GiftCard/Models/Refund.ts new file mode 100644 index 00000000..bead79bf --- /dev/null +++ b/src/PaymentMethods/GiftCard/Models/Refund.ts @@ -0,0 +1,16 @@ +import { IRefundRequest, ServiceParameter } from '../../../Models'; + +export interface IRefund extends IRefundRequest { + email?: string; + lastName?: string; +} + +export class Refund extends ServiceParameter { + set email(value: string) { + this.set('email', value); + } + + set lastName(value: string) { + this.set('lastName', value); + } +} diff --git a/src/PaymentMethods/GiftCard/index.ts b/src/PaymentMethods/GiftCard/index.ts index 0930c6b4..e903b967 100644 --- a/src/PaymentMethods/GiftCard/index.ts +++ b/src/PaymentMethods/GiftCard/index.ts @@ -1,16 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Payload, RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import IPay, { Pay } from './Models/Pay'; +import { IRefund, Refund } from './Models/Refund'; +import { ServiceCode } from '../../Utils'; export default class GiftCard extends PayablePaymentMethod { - pay(payload: Payload & { name: string }) { - return super.pay(payload) + public defaultServiceCode(): ServiceCode { + return 'giftcard'; } - refund(payload: RefundPayload & { name: string }) { - return super.refund(payload) + + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); } - setRequest(payload: any) { - this.paymentName = payload.name || this._paymentName - delete payload.name - super.setRequest(payload) + + refund(payload: IRefund) { + return super.refund(payload, new Refund(payload)); } } diff --git a/src/PaymentMethods/Giropay/Models/Pay.ts b/src/PaymentMethods/Giropay/Models/Pay.ts index 7d46e0f0..e1908ee4 100644 --- a/src/PaymentMethods/Giropay/Models/Pay.ts +++ b/src/PaymentMethods/Giropay/Models/Pay.ts @@ -1,6 +1,16 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, ServiceParameter } from '../../../Models'; -export interface Pay extends Payload { - bic: string - costumerIBAN: string +export interface IPay extends IPaymentRequest { + bic?: string; + costumerIBAN?: string; +} + +export class Pay extends ServiceParameter { + set bic(value: string) { + this.set('bic', value); + } + + set costumerIBAN(value: string) { + this.set('costumerIBAN', value); + } } diff --git a/src/PaymentMethods/Giropay/index.ts b/src/PaymentMethods/Giropay/index.ts index db1478d2..b5c1f1a4 100644 --- a/src/PaymentMethods/Giropay/index.ts +++ b/src/PaymentMethods/Giropay/index.ts @@ -1,15 +1,13 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Pay } from './Models/Pay' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; export default class Giropay extends PayablePaymentMethod { - protected _paymentName = 'giropay' - protected _serviceVersion = 1 - - pay(payload: Pay) { - return super.pay(payload) + public defaultServiceCode(): ServiceCode { + return 'giropay'; } - refund(payload: RefundPayload) { - return super.refund(payload) + + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); } } diff --git a/src/PaymentMethods/Ideal/Models/Pay.ts b/src/PaymentMethods/Ideal/Models/Pay.ts index 2c421ab5..f6919862 100644 --- a/src/PaymentMethods/Ideal/Models/Pay.ts +++ b/src/PaymentMethods/Ideal/Models/Pay.ts @@ -1,5 +1,11 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, ServiceParameter } from '../../../Models'; -export interface IPay extends Payload { - issuer: string +export interface IPay extends IPaymentRequest { + issuer?: string; +} + +export class Pay extends ServiceParameter { + set issuer(value: string) { + this.set('issuer', value); + } } diff --git a/src/PaymentMethods/Ideal/index.ts b/src/PaymentMethods/Ideal/index.ts index 4cafc5e6..9663a282 100644 --- a/src/PaymentMethods/Ideal/index.ts +++ b/src/PaymentMethods/Ideal/index.ts @@ -1,34 +1,42 @@ -import { IPay } from './Models/Pay' -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' +import { IPay, Pay } from './Models/Pay'; +import { PayablePaymentMethod } from '../../Services'; +import { RequestTypes } from '../../Constants'; +import { IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class Ideal extends PayablePaymentMethod { - protected _paymentName = 'ideal' - protected _serviceVersion = 2 - constructor(type?:'processing') { - super(); - if(type){ - this._paymentName = 'idealprocessing' - } + protected _serviceVersion = 2; + + constructor(serviceCode: 'ideal' | 'idealprocessing' = 'ideal') { + super(serviceCode); } - pay(payload: IPay) { - return super.pay(payload) + + public defaultServiceCode(): ServiceCode { + return 'ideal'; } - refund(payload: RefundPayload) { - return super.refund(payload) + + pay(data: IPay) { + return super.pay(data, new Pay(data)); } + + payRemainder(payload: IPay) { + return super.payRemainder(payload, new Pay(payload)); + } + issuers() { - return this.specification().then((response) => { - return response - .getActionRequestParameters('Pay') - ?.find((item) => item.Name === 'issuer') - ?.ListItemDescriptions.map((item) => { - return { [item.Value]: item.Description } - }) - }) + return this.specification(RequestTypes.Transaction) + .request() + .then((response) => { + return response + .getActionRequestParameters('Pay') + ?.find((item) => item.name === 'issuer') + ?.listItemDescriptions?.map((item) => { + return { [item.value]: item.description }; + }); + }); } - instantRefund(payload: RefundPayload){ - this.action = 'InstantRefund' - return super.refund(payload) + + instantRefund(data: IRefundRequest) { + return super.refund(data); } } diff --git a/src/PaymentMethods/IdealQR/Models/IGenerate.ts b/src/PaymentMethods/IdealQR/Models/IGenerate.ts new file mode 100644 index 00000000..4a11162e --- /dev/null +++ b/src/PaymentMethods/IdealQR/Models/IGenerate.ts @@ -0,0 +1,56 @@ +import { IRequest, ServiceParameter } from '../../../Models'; + +export interface IGenerate extends IRequest { + amount: number; + amountIsChangeable: boolean; + purchaseId: string; + description: string; + isOneOff: boolean; + expiration: string; + isProcessing?: boolean; + minAmount: number; + maxAmount: number; + imageSize: number; +} + +export class Generate extends ServiceParameter implements IGenerate { + set amount(value: number) { + this.set('amount', value); + } + + set amountIsChangeable(value: boolean) { + this.set('amountIsChangeable', value); + } + + set purchaseId(value: string) { + this.set('purchaseId', value); + } + + set description(value: string) { + this.set('description', value); + } + + set isOneOff(value: boolean) { + this.set('isOneOff', value); + } + + set expiration(value: string) { + this.set('expiration', value); + } + + set isProcessing(value: boolean) { + this.set('isProcessing', value); + } + + set minAmount(value: number) { + this.set('minAmount', value); + } + + set maxAmount(value: number) { + this.set('maxAmount', value); + } + + set imageSize(value: number) { + this.set('imageSize', value); + } +} diff --git a/src/PaymentMethods/IdealQR/index.ts b/src/PaymentMethods/IdealQR/index.ts new file mode 100644 index 00000000..22281d06 --- /dev/null +++ b/src/PaymentMethods/IdealQR/index.ts @@ -0,0 +1,14 @@ +import { Generate, IGenerate } from './Models/IGenerate'; +import { PaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; + +export default class IdealQR extends PaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'idealqr'; + } + + generate(payload: IGenerate) { + this.setServiceList('Generate', new Generate(payload)); + return this.dataRequest(); + } +} diff --git a/src/PaymentMethods/Idin/Models/Pay.ts b/src/PaymentMethods/Idin/Models/Pay.ts new file mode 100644 index 00000000..77eb2879 --- /dev/null +++ b/src/PaymentMethods/Idin/Models/Pay.ts @@ -0,0 +1,11 @@ +import { ServiceParameter } from '../../../Models'; + +export interface IPay { + issuer?: string; +} + +export class Pay extends ServiceParameter { + set issuer(value: string) { + this.set('issuerID', value); + } +} diff --git a/src/PaymentMethods/Idin/index.ts b/src/PaymentMethods/Idin/index.ts new file mode 100644 index 00000000..4f1552cd --- /dev/null +++ b/src/PaymentMethods/Idin/index.ts @@ -0,0 +1,24 @@ +import { PaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; + +export default class Idin extends PaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'idin'; + } + + identify(payload: IPay) { + this.setServiceList('Identify', new Pay(payload)); + return this.dataRequest(payload); + } + + verify(payload: IPay) { + this.setServiceList('Verify', new Pay(payload)); + return this.dataRequest(payload); + } + + login(payload: IPay) { + this.setServiceList('Login', new Pay(payload)); + return this.dataRequest(payload); + } +} diff --git a/src/PaymentMethods/In3/Models/Article.ts b/src/PaymentMethods/In3/Models/Article.ts index e69de29b..f645a66f 100644 --- a/src/PaymentMethods/In3/Models/Article.ts +++ b/src/PaymentMethods/In3/Models/Article.ts @@ -0,0 +1,29 @@ +import { Article, IArticle } from '../../../Models'; + +export interface IIn3Article extends IArticle { + category?: string; + url?: string; + quantityDescription?: string; +} + +export class In3Article extends Article implements In3Article { + set category(value: string) { + this.set('category', value); + } + + get price() { + return this.get('grossUnitPrice'); + } + + set price(value: number) { + this.set('grossUnitPrice', value); + } + + set url(value: string) { + this.set('url', value); + } + + set quantityDescription(value: string) { + this.set('quantityDescription', value); + } +} diff --git a/src/PaymentMethods/In3/Models/Pay.ts b/src/PaymentMethods/In3/Models/Pay.ts index 1053c309..dad3ed92 100644 --- a/src/PaymentMethods/In3/Models/Pay.ts +++ b/src/PaymentMethods/In3/Models/Pay.ts @@ -1,45 +1,55 @@ -import { Payload } from '../../../Models/ITransaction' -import Gender from '../../../Constants/Gender' -import RecipientCategory from '../../../Constants/RecipientCategory' - -type Article = { - code: string - name: string - quantity: number - price: number -} +import { IPaymentRequest, ServiceParameter } from '../../../Models'; +import { IIn3Article, In3Article } from './Article'; +import { IIn3Recipient, In3Recipient } from './Recipient'; -type Address = { - street: string - houseNumber: number - houseNumberSuffix: string - zipCode: string - city: string - country: string +export interface IPay extends IPaymentRequest { + invoiceDate?: string; + invoiceUrl?: string; + billing?: IIn3Recipient; + shipping?: Partial; + articles?: Partial[]; } -type Company = { - name: string - chamberOfCommerce: string -} -type Person = { - gender: Gender - culture: string - initials: string - lastName: string - birthDate: string -} +export default class Pay extends ServiceParameter { + set invoiceDate(value: string) { + this.set('invoiceDate', value); + } + + set invoiceUrl(value: string) { + this.set('invoiceUrl', value); + } + + get billing() { + return new In3Recipient(); + } + + set billing(billing: IIn3Recipient) { + this.set('billing', new In3Recipient(billing)); + if (this.get('shipping') === undefined) { + this.shipping = billing; + } + } + + set shipping(shipping: IIn3Recipient) { + this.set('shipping', new In3Recipient(shipping)); + } + + set articles(articles: In3Article[]) { + this.set( + 'articles', + articles.map((article) => new In3Article(article)) + ); + } + + protected getGroups(): {} { + return super.getGroups({ + Billing: 'BillingCustomer', + Shipping: 'ShippingCustomer', + Articles: 'Article', + }); + } -export interface IPay extends Payload { - description: string - clientIP: string - customerType: RecipientCategory.PERSON | RecipientCategory.COMPANY - invoiceDate: string - email: { email: string } - phone: { phone?: string; fax?: string } - company: Company - person: Person - address: Address - productLine: Article[] - subtotalLine: { name: string; value: number }[] + protected getCountable() { + return super.getCountable(['Articles']); + } } diff --git a/src/PaymentMethods/In3/Models/Phone.ts b/src/PaymentMethods/In3/Models/Phone.ts new file mode 100644 index 00000000..34c63b6c --- /dev/null +++ b/src/PaymentMethods/In3/Models/Phone.ts @@ -0,0 +1,15 @@ +import { Phone } from '../../../Models'; + +export class In3Phone extends Phone { + set landline(value: string) { + this.set('phone', value); + } + + set mobile(value: string) { + this.set('phone', value); + } + + set fax(value: string) { + this.set('phone', value); + } +} diff --git a/src/PaymentMethods/In3/Models/Recipient.ts b/src/PaymentMethods/In3/Models/Recipient.ts new file mode 100644 index 00000000..49aae8bc --- /dev/null +++ b/src/PaymentMethods/In3/Models/Recipient.ts @@ -0,0 +1,135 @@ +import { Address, Company, IAddress, ICompany, ICustomer, IPerson, IPhone, Model, Person } from '../../../Models'; +import { In3Phone } from './Phone'; +import { RecipientCategory } from '../../../Constants'; + +export interface IIn3Recipient extends ICustomer { + recipient: Partial; + phone: IPhone; +} + +export class In3Recipient extends Model implements In3Recipient { + get recipient(): In3Company | IIn3Person { + return new In3Person({}); + } + + set recipient(value: In3Company | IIn3Person) { + if (value.category === RecipientCategory.COMPANY) { + this.set('recipient', new In3Company(value)); + } else if (value.category === RecipientCategory.PERSON) { + this.set('recipient', new In3Person(value)); + } else throw new Error('Invalid recipient category'); + } + + get address(): IAddress { + return new In3Address(); + } + + set address(value: IAddress) { + this.set('address', new In3Address(value)); + } + + get email(): string { + return ''; + } + + set email(value: string) { + this.set('email', value); + } + + get phone(): IPhone { + return new In3Phone(); + } + + set phone(value: IPhone) { + this.set('phone', new In3Phone(value)); + } +} + +export interface IIn3Person extends IPerson { + customerNumber: string; + identificationNumber: string; + conversationLanguage: string; + lastName: string; +} + +export interface IIn3Company extends ICompany { + customerNumber: string; +} + +export class In3Person extends Person implements IIn3Person { + set category(value: RecipientCategory.PERSON) { + this.set('category', 'B2C'); + } + + set customerNumber(value: string) { + this.set('customerNumber', value); + } + + set identificationNumber(value: string) { + this.set('identificationNumber', value); + } + + set conversationLanguage(value: string) { + this.set('conversationLanguage', value); + } +} + +export class In3Company extends Company implements IIn3Company { + set category(value: RecipientCategory.COMPANY) { + this.set('category', 'B2B'); + } + + set customerNumber(value: string) { + this.set('customerNumber', value); + } + + get title() { + return this.get('salutation'); + } + + set title(value: string) { + this.set('salutation', value); + } + + get chamberOfCommerce() { + return this.get('cocNumber'); + } + + set chamberOfCommerce(value: string) { + this.set('cocNumber', value); + } +} + +export class In3Address extends Address { + get houseNumber() { + return this.get('streetNumber'); + } + + set houseNumber(value: string) { + this.set('streetNumber', value); + } + + get houseNumberAdditional() { + return this.get('streetNumberSuffix'); + } + + set houseNumberAdditional(value: string) { + this.set('streetNumberSuffix', value); + } + + get zipcode() { + return this.get('postalCode'); + } + + set zipcode(value: string) { + this.set('postalCode', value); + } + + get country() { + return this.get('countryCode'); + } + + set country(value: string) { + this.set('countryCode', value); + } +} diff --git a/src/PaymentMethods/In3/Models/Refund.ts b/src/PaymentMethods/In3/Models/Refund.ts new file mode 100644 index 00000000..bbf6ac41 --- /dev/null +++ b/src/PaymentMethods/In3/Models/Refund.ts @@ -0,0 +1,16 @@ +import { IIn3Article } from './Article'; +import { ServiceParameter } from '../../../Models'; + +export class Refund extends ServiceParameter { + set merchantImageUrl(value: string) { + this.set('merchantImageUrl', value); + } + + set summaryImageUrl(value: string) { + this.set('summaryImageUrl', value); + } + + set articles(value: IIn3Article[]) { + this.set('article', value); + } +} diff --git a/src/PaymentMethods/In3/index.ts b/src/PaymentMethods/In3/index.ts index c7ea9a0a..270e6b98 100644 --- a/src/PaymentMethods/In3/index.ts +++ b/src/PaymentMethods/In3/index.ts @@ -1,17 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPaymentRequest, IRefundRequest } from '../../Models'; +import Pay from './Models/Pay'; +import { ServiceCode } from '../../Utils'; export default class In3 extends PayablePaymentMethod { - protected _paymentName = 'capayable' - pay(payload: IPay) { - return super.pay(payload) + public defaultServiceCode(): ServiceCode { + return 'In3'; } - payInInstallments(payload: IPay) { - this.action = 'PayInInstallments' - return super.payTransaction(payload) + + pay(payload: IPaymentRequest) { + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/In3Old/Models/Address.ts b/src/PaymentMethods/In3Old/Models/Address.ts new file mode 100644 index 00000000..c8b0332b --- /dev/null +++ b/src/PaymentMethods/In3Old/Models/Address.ts @@ -0,0 +1,7 @@ +import { Address } from '../../../Models'; + +export class In3OldAddress extends Address { + set houseNumberAddition(houseNumberAddition: string) { + this.set('houseNumberSuffix', houseNumberAddition); + } +} diff --git a/src/PaymentMethods/In3Old/Models/Article.ts b/src/PaymentMethods/In3Old/Models/Article.ts new file mode 100644 index 00000000..0bdd84d9 --- /dev/null +++ b/src/PaymentMethods/In3Old/Models/Article.ts @@ -0,0 +1,11 @@ +import { Article } from '../../../Models'; + +export class In3OldArticle extends Article { + set identifier(identifier: string) { + this.set('code', identifier); + } + + set description(description: string) { + this.set('name', description); + } +} diff --git a/src/PaymentMethods/In3Old/Models/Company.ts b/src/PaymentMethods/In3Old/Models/Company.ts new file mode 100644 index 00000000..decad29d --- /dev/null +++ b/src/PaymentMethods/In3Old/Models/Company.ts @@ -0,0 +1,7 @@ +import { Company } from '../../../Models'; + +export class In3OldCompany extends Company { + set companyName(companyName: string) { + this.set('name', companyName); + } +} diff --git a/src/PaymentMethods/In3Old/Models/Pay.ts b/src/PaymentMethods/In3Old/Models/Pay.ts new file mode 100644 index 00000000..a13e5690 --- /dev/null +++ b/src/PaymentMethods/In3Old/Models/Pay.ts @@ -0,0 +1,90 @@ +import { + IAddress, + IArticle, + ICompany, + IPaymentRequest, + IPerson, + IPhone, + Person, + ServiceParameter, +} from '../../../Models'; +import { RecipientCategory } from '../../../Constants'; +import { In3OldArticle } from './Article'; +import { ISubtotal, Subtotal } from './Subtotal'; +import { In3OldCompany } from './Company'; +import { In3OldAddress } from './Address'; +import { In3OldPhone } from './Phone'; + +export interface IPay extends IPaymentRequest { + description: string; + clientIP: string; + customerType: RecipientCategory.PERSON | RecipientCategory.COMPANY; + invoiceDate: string; + email: string; + phone: Partial; + company: Partial; + customer: Partial; + address: Partial; + articles: Partial[]; + subtotals: ISubtotal[]; +} + +export class Pay extends ServiceParameter { + set customerType(value: RecipientCategory) { + this.set('customerType', value); + } + + set invoiceDate(value: string) { + this.set('invoiceDate', value); + } + + set email(value: string) { + this.set('email', value); + } + + set phone(value: Partial) { + this.set('phone', new In3OldPhone(value)); + } + + set company(value: Partial) { + this.set('company', new In3OldCompany(value)); + } + + set customer(value: Partial) { + this.set('customer', new Person(value)); + } + + set address(value: Partial) { + this.set('address', new In3OldAddress(value)); + } + + set articles(value: Partial[]) { + this.set( + 'articles', + value.map((article) => new In3OldArticle(article)) + ); + } + + set subtotals(value: ISubtotal[]) { + this.set( + 'subtotals', + value.map((subtotal) => new Subtotal(subtotal)) + ); + } + + protected getGroups() { + return super.getGroups({ + Articles: 'ProductLine', + Subtotals: 'SubtotalLine', + Address: 'Address', + Customer: 'Person', + Company: 'Company', + Phone: 'Phone', + Email: 'Email', + }); + } + + protected getCountable() { + return super.getCountable(['Articles', 'Subtotals']); + } +} diff --git a/src/PaymentMethods/In3Old/Models/Phone.ts b/src/PaymentMethods/In3Old/Models/Phone.ts new file mode 100644 index 00000000..0cd27bed --- /dev/null +++ b/src/PaymentMethods/In3Old/Models/Phone.ts @@ -0,0 +1,7 @@ +import { Phone } from '../../../Models'; + +export class In3OldPhone extends Phone { + set mobile(number: string) { + this.set('phone', number); + } +} diff --git a/src/PaymentMethods/In3Old/Models/Subtotal.ts b/src/PaymentMethods/In3Old/Models/Subtotal.ts new file mode 100644 index 00000000..57235b5f --- /dev/null +++ b/src/PaymentMethods/In3Old/Models/Subtotal.ts @@ -0,0 +1,16 @@ +import { Model } from '../../../Models'; + +export interface ISubtotal { + name: string; + value: number; +} + +export class Subtotal extends Model implements ISubtotal { + set name(name: string) { + this.set('name', name); + } + + set value(value: number) { + this.set('value', value); + } +} diff --git a/src/PaymentMethods/In3Old/index.ts b/src/PaymentMethods/In3Old/index.ts new file mode 100644 index 00000000..1dd95d22 --- /dev/null +++ b/src/PaymentMethods/In3Old/index.ts @@ -0,0 +1,19 @@ +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; + +export default class In3Old extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'capayable'; + } + + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); + } + + payInInstallments(payload: IPay) { + this.setPayPayload(payload); + this.setServiceList('PayInInstallments', new Pay(payload)); + return super.transactionRequest(); + } +} diff --git a/src/PaymentMethods/KBC/index.ts b/src/PaymentMethods/KBC/index.ts index 07b9258b..fe9aef87 100644 --- a/src/PaymentMethods/KBC/index.ts +++ b/src/PaymentMethods/KBC/index.ts @@ -1,11 +1,13 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class KBC extends PayablePaymentMethod { - protected _paymentName = 'kbcpaymentbutton' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'KBCPaymentButton'; + } - refund(payload: RefundPayload) { - return super.refund(payload) + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/Klarna/Models/Article.ts b/src/PaymentMethods/Klarna/Models/Article.ts index 3e68c08c..d7a3837a 100644 --- a/src/PaymentMethods/Klarna/Models/Article.ts +++ b/src/PaymentMethods/Klarna/Models/Article.ts @@ -1,9 +1,11 @@ -export type IKlarnaArticle = { - description: string - grossUnitPrice: number - identifier: string - imageUrl?: string - quantity: string - uRL?: string - vatPercentage: string +import { Article } from '../../../Models'; + +export class KlarnaArticle extends Article { + get price() { + return this.get('grossUnitPrice'); + } + + set price(price: number) { + this.set('grossUnitPrice', price); + } } diff --git a/src/PaymentMethods/Klarna/Models/Pay.ts b/src/PaymentMethods/Klarna/Models/Pay.ts index 805370b2..f2fca527 100644 --- a/src/PaymentMethods/Klarna/Models/Pay.ts +++ b/src/PaymentMethods/Klarna/Models/Pay.ts @@ -1,9 +1,41 @@ -import { IKlarnaArticle } from './Article' -import { IBilling, IShipping } from './Recipient' -import { Payload } from '../../../Models/ITransaction' - -export interface IPay extends Payload { - billingCustomer: IBilling - shippingCustomer?: IShipping - article: IKlarnaArticle[] +import { KlarnaRecipient } from './Recipient'; +import { Article, IArticle, ICustomer, IPaymentRequest, ServiceParameter } from '../../../Models'; +import { KlarnaArticle } from './Article'; + +export interface IPay extends IPaymentRequest { + billing: ICustomer; + shipping?: ICustomer; + articles: Partial[]; +} + +export class Pay extends ServiceParameter { + set billing(billing: ICustomer) { + this.set('billing', new KlarnaRecipient(billing)); + if (this.get('shipping') === undefined) { + this.shipping = billing; + } + } + + set shipping(shipping: ICustomer) { + this.set('shipping', new KlarnaRecipient(shipping)); + } + + set articles(articles: IArticle[]) { + this.set( + 'articles', + articles.map((article) => new KlarnaArticle(article)) + ); + } + + protected getGroups() { + return super.getGroups({ + Billing: 'BillingCustomer', + Shipping: 'ShippingCustomer', + Articles: 'Article', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } } diff --git a/src/PaymentMethods/Klarna/Models/Recipient.ts b/src/PaymentMethods/Klarna/Models/Recipient.ts index d63e9c71..4bce0e31 100644 --- a/src/PaymentMethods/Klarna/Models/Recipient.ts +++ b/src/PaymentMethods/Klarna/Models/Recipient.ts @@ -1,24 +1,28 @@ -export type IBilling = { - city: string - country: string - email: string - firstName: string - lastName: string - phone?: string - postalCode: string - street: string - streetNumber: string - streetNumberAdditional?: string -} -export type IShipping = { - city: string - country: string - email: string - firstName: string - lastName: string - phone?: string - postalCode: string - street: string - streetNumber: string - streetNumberAdditional?: string +import { Company, IAddress, ICompany, ICustomer, IPerson, IPhone, Model, Person } from '../../../Models'; +import { KlarnaAddress } from '../Services/KlarnaAddress'; +import { KlarnaPhone } from '../Services/KlarnaPhone'; +import { RecipientCategory } from '../../../Constants'; + +export class KlarnaRecipient extends Model implements ICustomer { + set email(email: string) { + this.set('email', email); + } + + set address(address: IAddress) { + this.set('address', new KlarnaAddress(address)); + } + + set recipient(recipient: Partial) { + if (recipient.category === RecipientCategory.PERSON) { + // @ts-ignore + this.set('recipient', new Person({ ...recipient, category: 'B2C' })); + } else if (recipient.category === RecipientCategory.COMPANY) { + // @ts-ignore + this.set('recipient', new Company({ ...recipient, category: 'B2B' })); + } + } + + set phone(phone: IPhone) { + this.set('phone', new KlarnaPhone(phone)); + } } diff --git a/src/PaymentMethods/Klarna/Services/KlarnaAddress.ts b/src/PaymentMethods/Klarna/Services/KlarnaAddress.ts new file mode 100644 index 00000000..3bfbf459 --- /dev/null +++ b/src/PaymentMethods/Klarna/Services/KlarnaAddress.ts @@ -0,0 +1,27 @@ +import { Address, IAddress } from '../../../Models'; + +export class KlarnaAddress extends Address implements IAddress { + get houseNumber(): string { + return this.get('streetNumber'); + } + + set houseNumber(houseNumber: string) { + this.set('streetNumber', houseNumber); + } + + get houseNumberAdditional(): string { + return this.get('streetNumberAdditional'); + } + + set houseNumberAdditional(houseNumberAdditional: string) { + this.set('streetNumberAdditional', houseNumberAdditional); + } + + get zipcode(): string { + return this.get('postalCode'); + } + + set zipcode(zipcode: string) { + this.set('postalCode', zipcode); + } +} diff --git a/src/PaymentMethods/Klarna/Services/KlarnaPhone.ts b/src/PaymentMethods/Klarna/Services/KlarnaPhone.ts new file mode 100644 index 00000000..10e8907f --- /dev/null +++ b/src/PaymentMethods/Klarna/Services/KlarnaPhone.ts @@ -0,0 +1,11 @@ +import { Phone } from '../../../Models'; + +export class KlarnaPhone extends Phone { + get mobile(): string { + return this.get('phone'); + } + + set mobile(mobile: string) { + this.set('phone', mobile); + } +} diff --git a/src/PaymentMethods/Klarna/index.ts b/src/PaymentMethods/Klarna/index.ts index 48ad736e..609aee49 100644 --- a/src/PaymentMethods/Klarna/index.ts +++ b/src/PaymentMethods/Klarna/index.ts @@ -1,20 +1,23 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { IConfig } from '../../Utils/Types' -import { RefundPayload } from '../../Models/ITransaction' +import { IPay, Pay } from './Models/Pay'; +import { PayablePaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; export default class Klarna extends PayablePaymentMethod { - protected _paymentName = 'klarna' - protected _serviceVersion = 1 - protected _requiredFields: Array = ['currency', 'pushURL'] - pay(payload: IPay) { - return super.pay(payload) + public defaultServiceCode(): ServiceCode { + return 'klarna'; } - refund(payload: RefundPayload) { - return super.refund(payload) + + pay(data: IPay) { + return super.pay(data, new Pay(data)); + } + + payInInstallments(data: IPay) { + this.setPayPayload(data); + this.setServiceList('PayInInstallments', new Pay(data)); + return super.transactionRequest(); } - payInInstallments(payload: IPay) { - this.action = 'PayInInstallments' - return super.transactionRequest(payload) + + payRemainder(payload: IPay) { + return super.payRemainder(payload, new Pay(payload)); } } diff --git a/src/PaymentMethods/KlarnaKP/Models/Address.ts b/src/PaymentMethods/KlarnaKP/Models/Address.ts new file mode 100644 index 00000000..635e1469 --- /dev/null +++ b/src/PaymentMethods/KlarnaKP/Models/Address.ts @@ -0,0 +1,27 @@ +import { Model } from '../../../Models'; + +export class Address extends Model { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set street(value: string) { + this.set(`${this.get('prefix')}Street`, value); + } + + set street2(value: string) { + this.set(`${this.get('prefix')}Street2`, value); + } + + set zipcode(value: string) { + this.set(`${this.get('prefix')}PostalCode`, value); + } + + set city(value: string) { + this.set(`${this.get('prefix')}City`, value); + } + + set country(value: string) { + this.set(`${this.get('prefix')}Country`, value); + } +} diff --git a/src/PaymentMethods/KlarnaKP/Models/Article.ts b/src/PaymentMethods/KlarnaKP/Models/Article.ts new file mode 100644 index 00000000..c733df8a --- /dev/null +++ b/src/PaymentMethods/KlarnaKP/Models/Article.ts @@ -0,0 +1,32 @@ +import { Article as ArticleClass } from '../../../Models'; + +export default class Article extends ArticleClass { + get description(): string { + return this.get('title'); + } + + set description(description: string) { + this.set('title', description); + } + + get vatPercentage(): number { + return this.get('vat'); + } + + set vatPercentage(value: number) { + this.set('vat', value); + } + + get identifier(): string { + return this.get('number'); + } + + set identifier(identifier: string) { + this.set('number', identifier); + } + + set(name: string, value: any, hidden: boolean = false): this { + this.defineProperty(`article${name.charAt(0).toUpperCase() + name.slice(1)}`, value, hidden); + return this; + } +} diff --git a/src/PaymentMethods/KlarnaKP/Models/Customer.ts b/src/PaymentMethods/KlarnaKP/Models/Customer.ts new file mode 100644 index 00000000..bbee8612 --- /dev/null +++ b/src/PaymentMethods/KlarnaKP/Models/Customer.ts @@ -0,0 +1,21 @@ +import { IAddress, IRecipient, Model } from '../../../Models'; +import { Address } from './Address'; +import { Recipient } from './Recipient'; + +export class Customer extends Model { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set email(value: string) { + this.set(`${this.get('prefix')}Email`, value); + } + + set address(address: Partial) { + this.set('address', new Address({ prefix: this.get('prefix'), ...address })); + } + + set recipient(recipient: Partial) { + this.set('recipient', new Recipient({ prefix: this.get('prefix'), ...recipient })); + } +} diff --git a/src/PaymentMethods/KlarnaKP/Models/IPay.ts b/src/PaymentMethods/KlarnaKP/Models/IPay.ts index b0509206..51239284 100644 --- a/src/PaymentMethods/KlarnaKP/Models/IPay.ts +++ b/src/PaymentMethods/KlarnaKP/Models/IPay.ts @@ -1,5 +1,21 @@ -import { ITransaction } from '../../../Models/ITransaction' +import { IPaymentRequest, Person, ServiceParameter } from '../../../Models'; -export interface IPay extends ITransaction { - reservationNumber?: string +export interface IPay extends IPaymentRequest { + reservationNumber?: string; +} + +export class Pay extends ServiceParameter { + set reservationNumber(value: string) { + this.set('reservationNumber', value); + } +} + +export class Customer extends Person { + set firstName(email: string) { + this.set('customerFirstName', email); + } + + set lastName(email: string) { + this.set('customerLastName', email); + } } diff --git a/src/PaymentMethods/KlarnaKP/Models/IReserve.ts b/src/PaymentMethods/KlarnaKP/Models/IReserve.ts new file mode 100644 index 00000000..64e3a112 --- /dev/null +++ b/src/PaymentMethods/KlarnaKP/Models/IReserve.ts @@ -0,0 +1,60 @@ +import { Gender } from '../../../Constants'; +import { IArticle, ICustomer, IRequest, ServiceParameter } from '../../../Models'; +import { Customer } from './Customer'; +import Article from './Article'; + +export interface IReserve extends IRequest { + gender?: Gender.MALE | Gender.FEMALE; + billing?: ICustomer; + shipping?: ICustomer; + articles?: Partial[]; + operatingCountry?: string; + reservationNumber?: string; + shippingSameAsBilling?: boolean; + pno?: string; +} + +export class Reserve extends ServiceParameter implements IReserve { + set reservationNumber(value: string) { + this.set('reservationNumber', value); + } + + set gender(value: Gender.MALE | Gender.FEMALE) { + this.set('gender', value); + } + + set operatingCountry(value: string) { + this.set('operatingCountry', value); + } + + set pno(value: string) { + this.set('pno', value); + } + + set billing(value: ICustomer) { + this.set('billing', new Customer({ prefix: 'billing', ...value })); + } + + set shipping(value: ICustomer) { + this.set('shipping', new Customer({ prefix: 'shipping', ...value })); + } + + set articles(value: IArticle[]) { + this.set( + 'articles', + value.map((article) => new Article(article)) + ); + } + + protected getGroups(): {} { + return super.getGroups({ + Billing: 'BillingCustomer', + Shipping: 'ShippingCustomer', + Articles: 'Article', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } +} diff --git a/src/PaymentMethods/KlarnaKP/Models/Phone.ts b/src/PaymentMethods/KlarnaKP/Models/Phone.ts new file mode 100644 index 00000000..4874b5c5 --- /dev/null +++ b/src/PaymentMethods/KlarnaKP/Models/Phone.ts @@ -0,0 +1,11 @@ +import { Person } from '../../../Models'; + +export class Phone extends Person { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set mobile(value: string) { + this.set(`${this.get('prefix')}CellPhoneNumber`, value); + } +} diff --git a/src/PaymentMethods/KlarnaKP/Models/Recipient.ts b/src/PaymentMethods/KlarnaKP/Models/Recipient.ts new file mode 100644 index 00000000..e911e2d5 --- /dev/null +++ b/src/PaymentMethods/KlarnaKP/Models/Recipient.ts @@ -0,0 +1,15 @@ +import { Model } from '../../../Models'; + +export class Recipient extends Model { + set prefix(value: string) { + this.set('prefix', value, true); + } + + set firstName(value: string) { + this.set(`${this.get('prefix')}FirstName`, value); + } + + set lastName(value: string) { + this.set(`${this.get('prefix')}LastName`, value); + } +} diff --git a/src/PaymentMethods/KlarnaKP/index.ts b/src/PaymentMethods/KlarnaKP/index.ts index 6ac9175b..50336fae 100644 --- a/src/PaymentMethods/KlarnaKP/index.ts +++ b/src/PaymentMethods/KlarnaKP/index.ts @@ -1,34 +1,42 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/IPay' -import { ICapture, Payload, RefundPayload } from '../../Models/ITransaction' - -export default class KlarnaKp extends PayablePaymentMethod { - protected _paymentName = 'KlarnaKp' - _serviceVersion = 1 - pay(payload: IPay & Payload) { - return super.pay(payload) +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/IPay'; +import { IRequest } from '../../Models'; +import { IReserve, Reserve } from './Models/IReserve'; +import { ServiceCode } from '../../Utils'; + +export default class KlarnaKP extends PayablePaymentMethod { + protected _serviceVersion = 1; + + public defaultServiceCode(): ServiceCode { + return 'klarnakp'; } - refund(payload: RefundPayload) { - return super.refund(payload) + + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); } - reserve(payload: IPay) { - this.action = 'Reserve' - return this.dataRequest(payload) + + reserve(payload: IReserve) { + this.setServiceList('Reserve', new Reserve(payload)); + return this.dataRequest(payload); } - cancel(payload: IPay) { - this.action = 'CancelReservation' - return this.dataRequest(payload) + + cancel(payload: IRequest) { + this.setServiceList('CancelReservation', new Pay(payload)); + return this.dataRequest(payload); } - update(payload: IPay) { - this.action = 'UpdateReservation' - return this.dataRequest(payload) + + update(payload: IRequest) { + this.setServiceList('UpdateReservation'); + return this.dataRequest(payload); } - extend(payload: IPay) { - this.action = 'ExtendReservation' - return this.dataRequest(payload) + + extend(payload: IRequest) { + this.setServiceList('ExtendReservation'); + return this.dataRequest(payload); } - addShippingInfo(payload: ICapture) { - this.action = 'AddShippingInfo' - return this.dataRequest(payload) + + addShippingInfo(payload: IRequest) { + this.setServiceList('AddShippingInfo'); + return this.dataRequest(payload); } } diff --git a/src/PaymentMethods/Marketplaces/Models/ISplit.ts b/src/PaymentMethods/Marketplaces/Models/ISplit.ts deleted file mode 100644 index 80a7ff9f..00000000 --- a/src/PaymentMethods/Marketplaces/Models/ISplit.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { ITransaction } from '../../../Models/ITransaction' - -type Seller = { - accountId?: string - amount?: number - description?: string -} -type Marketplace = { - amount?: number - description?: string -} -export interface ISplit extends ITransaction { - seller?: Seller[] - marketplace?: Marketplace - daysUntilTransfer?: number -} -export interface ITransfer extends ITransaction { - seller?: Seller[] - marketplace?: Marketplace - daysUntilTransfer?: number - originalTransactionKey: string -} diff --git a/src/PaymentMethods/Marketplaces/Models/Marketplace.ts b/src/PaymentMethods/Marketplaces/Models/Marketplace.ts new file mode 100644 index 00000000..ab3000d2 --- /dev/null +++ b/src/PaymentMethods/Marketplaces/Models/Marketplace.ts @@ -0,0 +1,16 @@ +import { Model } from '../../../Models'; + +export interface IMarketplace { + amount: number; + description: string; +} + +export class Marketplace extends Model implements IMarketplace { + set amount(value: number) { + this.set('amount', value); + } + + set description(value: string) { + this.set('description', value); + } +} diff --git a/src/PaymentMethods/Marketplaces/Models/Seller.ts b/src/PaymentMethods/Marketplaces/Models/Seller.ts new file mode 100644 index 00000000..aabc6703 --- /dev/null +++ b/src/PaymentMethods/Marketplaces/Models/Seller.ts @@ -0,0 +1,21 @@ +import { Model } from '../../../Models'; + +export interface ISeller { + accountId?: string; + amount?: number; + description?: string; +} + +export class Seller extends Model implements ISeller { + set accountId(value: string) { + this.set('accountId', value); + } + + set amount(value: number) { + this.set('amount', value); + } + + set description(value: string) { + this.set('description', value); + } +} diff --git a/src/PaymentMethods/Marketplaces/Models/Split.ts b/src/PaymentMethods/Marketplaces/Models/Split.ts new file mode 100644 index 00000000..ced98610 --- /dev/null +++ b/src/PaymentMethods/Marketplaces/Models/Split.ts @@ -0,0 +1,37 @@ +import { IRequest, ServiceParameter } from '../../../Models'; +import { IMarketplace, Marketplace } from './Marketplace'; +import { ISeller, Seller } from './Seller'; + +export interface ISplit extends IRequest { + sellers?: ISeller[]; + marketplace?: IMarketplace; + daysUntilTransfer?: number; +} + +export class Split extends ServiceParameter { + set seller(value: ISeller[]) { + this.set( + 'sellers', + value.map((seller: ISeller) => new Seller(seller)) + ); + } + + set marketplace(value: IMarketplace) { + this.set('marketplace', new Marketplace(value)); + } + + set daysUntilTransfer(value: number) { + this.set('daysUntilTransfer', value); + } + + protected getCountable() { + return super.getCountable(['Sellers']); + } + + protected getGroups() { + return super.getGroups({ + Sellers: 'Seller', + Marketplace: 'Marketplace', + }); + } +} diff --git a/src/PaymentMethods/Marketplaces/Models/Transfer.ts b/src/PaymentMethods/Marketplaces/Models/Transfer.ts new file mode 100644 index 00000000..82df5874 --- /dev/null +++ b/src/PaymentMethods/Marketplaces/Models/Transfer.ts @@ -0,0 +1,9 @@ +import { IRequest } from '../../../Models'; +import { ISeller } from './Seller'; +import { IMarketplace } from './Marketplace'; + +export interface ITransfer extends IRequest { + seller?: ISeller[]; + marketplace?: IMarketplace; + originalTransactionKey: string; +} diff --git a/src/PaymentMethods/Marketplaces/index.ts b/src/PaymentMethods/Marketplaces/index.ts index 3c40fa0f..636fdec9 100644 --- a/src/PaymentMethods/Marketplaces/index.ts +++ b/src/PaymentMethods/Marketplaces/index.ts @@ -1,21 +1,25 @@ -import PaymentMethod from '../PaymentMethod' -import { ISplit, ITransfer } from './Models/ISplit' +import { PaymentMethod } from '../../Services'; +import { ISplit, Split } from './Models/Split'; +import { ITransfer } from './Models/Transfer'; +import { ServiceCode } from '../../Utils'; export default class Marketplaces extends PaymentMethod { - protected _paymentName = 'Marketplaces' + public defaultServiceCode(): ServiceCode { + return 'marketplaces'; + } split(payload: ISplit) { - this.action = 'Split' - this.setRequest(payload) - return this + this.setServiceList('Split', new Split(payload)); + return this.dataRequest(payload); } + transfer(payload: ITransfer) { - this.action = 'Transfer' - return this.dataRequest(payload) + this.setServiceList('Transfer', new Split(payload)); + return this.dataRequest(payload); } - refundSupplementary(payload: ISplit = {}) { - this.action = 'RefundSupplementary' - this.setRequest(payload) - return this + + refundSupplementary(payload: ISplit) { + this.setServiceList('RefundSupplementary', new Split(payload)); + return this.dataRequest(payload); } } diff --git a/src/PaymentMethods/Mbway/index.ts b/src/PaymentMethods/Mbway/index.ts new file mode 100644 index 00000000..a9f291fc --- /dev/null +++ b/src/PaymentMethods/Mbway/index.ts @@ -0,0 +1,8 @@ +import { PayablePaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; + +export default class Mbway extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'MBWay'; + } +} diff --git a/src/PaymentMethods/Multibanco/index.ts b/src/PaymentMethods/Multibanco/index.ts new file mode 100644 index 00000000..cd7c4f9b --- /dev/null +++ b/src/PaymentMethods/Multibanco/index.ts @@ -0,0 +1,8 @@ +import { PayablePaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; + +export default class MultiBanco extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'multibanco'; + } +} diff --git a/src/PaymentMethods/NoService/index.ts b/src/PaymentMethods/NoService/index.ts new file mode 100644 index 00000000..392be8bc --- /dev/null +++ b/src/PaymentMethods/NoService/index.ts @@ -0,0 +1,12 @@ +import { PayablePaymentMethod } from '../../Services'; +import { ServiceCode } from '../../Utils'; + +export default class NoService extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'noservice'; + } + + protected setServiceList(): this { + return this; + } +} diff --git a/src/PaymentMethods/PayByBank/Models/IPay.ts b/src/PaymentMethods/PayByBank/Models/IPay.ts new file mode 100644 index 00000000..019b03df --- /dev/null +++ b/src/PaymentMethods/PayByBank/Models/IPay.ts @@ -0,0 +1,16 @@ +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export default interface IPay extends IPaymentRequest { + issuer: string; + countryCode: string; +} + +export class Pay extends ServiceParameter { + set issuer(value: string) { + this.set('issuer', value); + } + + set countryCode(value: string) { + this.set('countryCode', value); + } +} diff --git a/src/PaymentMethods/PayByBank/index.ts b/src/PaymentMethods/PayByBank/index.ts new file mode 100644 index 00000000..f429fc75 --- /dev/null +++ b/src/PaymentMethods/PayByBank/index.ts @@ -0,0 +1,35 @@ +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import IPay, { Pay } from './Models/IPay'; +import { ServiceCode } from '../../Utils'; +import { RequestTypes } from '../../Constants'; + +export default class PayByBank extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'PayByBank'; + } + + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); + } + + refund(payload: IRefundRequest) { + return super.refund(payload); + } + + issuers() { + return this.specification(RequestTypes.Transaction, 1) + .request() + .then((response) => { + return response + .getActionRequestParameters('Pay') + ?.find((item) => item.name === 'Issuer') + ?.listItemDescriptions!.map((item) => { + return { [item.value]: item.description }; + }); + }) + .catch((err) => { + console.log(err); + }); + } +} diff --git a/src/PaymentMethods/PayPerEmail/Models/Attachments.ts b/src/PaymentMethods/PayPerEmail/Models/Attachments.ts new file mode 100644 index 00000000..58972a73 --- /dev/null +++ b/src/PaymentMethods/PayPerEmail/Models/Attachments.ts @@ -0,0 +1,11 @@ +import { Model } from '../../../Models'; + +export interface IAttachments { + name: string; +} + +export class Attachments extends Model implements IAttachments { + set name(value: string) { + this.set('attachment', value); + } +} diff --git a/src/PaymentMethods/PayPerEmail/Models/Invitation.ts b/src/PaymentMethods/PayPerEmail/Models/Invitation.ts new file mode 100644 index 00000000..b41274d2 --- /dev/null +++ b/src/PaymentMethods/PayPerEmail/Models/Invitation.ts @@ -0,0 +1,64 @@ +import { IPerson, IRequest, Person, ServiceParameter } from '../../../Models'; +import { Attachments, IAttachments } from './Attachments'; + +export interface IInvitation extends IRequest { + currency: string; + customer: Partial; + email: string; + merchantSendsEmail?: boolean; + expirationDate?: string; + paymentMethodsAllowed?: string; + attachments?: IAttachments[]; + attachment?: string; +} + +export class Invitation extends ServiceParameter { + set attachment(value: string) { + this.set('attachment', value); + } + + set customer(value: Partial) { + this.set('customer', new Customer(value)); + } + + set merchantSendsEmail(value: boolean) { + this.set('merchantSendsEmail', value); + } + + set attachments(value: IAttachments[]) { + this.set( + 'attachments', + value.map((attachment: IAttachments) => new Attachments(attachment)) + ); + } + + set email(value: string) { + this.set('customerEmail', value); + } + + set paymentMethodsAllowed(value: string) { + this.set('paymentMethodsAllowed', value); + } + + set expirationDate(value: string) { + this.set('expirationDate', value); + } + + protected getCountable() { + return super.getCountable(['Attachments']); + } +} + +class Customer extends Person { + set gender(value: string) { + this.set('customergender', value); + } + + set firstName(value: string) { + this.set('customerFirstName', value); + } + + set lastName(value: string) { + this.set('customerLastName', value); + } +} diff --git a/src/PaymentMethods/PayPerEmail/Models/invitation.ts b/src/PaymentMethods/PayPerEmail/Models/invitation.ts deleted file mode 100644 index b409126c..00000000 --- a/src/PaymentMethods/PayPerEmail/Models/invitation.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Payload } from '../../../Models/ITransaction' -import gender from '../../../Constants/Gender' - -export interface IInvitation extends Payload { - customerGender: gender - customerFirstName: string - customerLastName: string - customerEmail: string - merchantSendsEmail?: boolean - email: string - expirationDate?: string - paymentMethodsAllowed?: string - attachment?: string -} diff --git a/src/PaymentMethods/PayPerEmail/index.ts b/src/PaymentMethods/PayPerEmail/index.ts index b4803f86..a0d1b114 100644 --- a/src/PaymentMethods/PayPerEmail/index.ts +++ b/src/PaymentMethods/PayPerEmail/index.ts @@ -1,13 +1,14 @@ -import PaymentMethod from '../PaymentMethod' -import { IInvitation } from './Models/invitation' -import { uniqid } from '../../Utils/Functions' +import { PaymentMethod } from '../../Services'; +import { IInvitation, Invitation } from './Models/Invitation'; +import { ServiceCode } from '../../Utils'; export default class PayPerEmail extends PaymentMethod { - protected _paymentName = 'payperemail' + public defaultServiceCode(): ServiceCode { + return 'payperemail'; + } paymentInvitation(payload: IInvitation) { - this.action = 'paymentInvitation' - payload.invoice = payload.invoice || uniqid() - return super.transactionRequest(payload) + this.setServiceList('paymentInvitation', new Invitation(payload)); + return super.transactionRequest(payload); } } diff --git a/src/PaymentMethods/PayablePaymentMethod.ts b/src/PaymentMethods/PayablePaymentMethod.ts deleted file mode 100644 index 0d786978..00000000 --- a/src/PaymentMethods/PayablePaymentMethod.ts +++ /dev/null @@ -1,33 +0,0 @@ -import PaymentMethod from './PaymentMethod' -import { uniqid } from '../Utils/Functions' -import { ITransaction, Payload, RefundPayload } from '../Models/ITransaction' -import { TransactionResponse } from '../Models/TransactionResponse' -import { IConfig } from '../Utils/Types' - -export abstract class PayablePaymentMethod extends PaymentMethod { - protected _requiredFields: Array = [ - 'currency', - 'returnURL', - 'returnURLCancel', - 'pushURL' - ] - protected payTransaction(payload: ITransaction): Promise { - payload.invoice = payload.invoice || uniqid() - payload.order = payload.order || uniqid() - - return this.transactionRequest(payload) - } - pay(payload: Payload) { - this.action = 'Pay' - return this.payTransaction(payload) - } - - protected refund(payload: RefundPayload) { - this.action = 'Refund' - return this.payTransaction(payload) - } - protected transactionInvoice(payload: ITransaction): Promise { - payload.invoice = payload.invoice || uniqid() - return this.transactionRequest(payload) - } -} diff --git a/src/PaymentMethods/Payconiq/index.ts b/src/PaymentMethods/Payconiq/index.ts index fb420eff..3daa55b8 100644 --- a/src/PaymentMethods/Payconiq/index.ts +++ b/src/PaymentMethods/Payconiq/index.ts @@ -1,14 +1,14 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class Payconiq extends PayablePaymentMethod { - protected _paymentName = 'payconiq' - - refund(payload: RefundPayload) { - return super.refund(payload) + public defaultServiceCode(): ServiceCode { + return 'payconiq'; } - instantRefund(payload: RefundPayload){ - this.action = 'InstantRefund' - return super.refund(payload) + + instantRefund(payload: IRefundRequest) { + this.setServiceList('InstantRefund'); + return this.transactionRequest(payload); } } diff --git a/src/PaymentMethods/PaymentInitiation/Models/IPay.ts b/src/PaymentMethods/PaymentInitiation/Models/IPay.ts deleted file mode 100644 index d5349cc0..00000000 --- a/src/PaymentMethods/PaymentInitiation/Models/IPay.ts +++ /dev/null @@ -1,6 +0,0 @@ -import {Payload} from "../../../Models/ITransaction"; - -export default interface IPay extends Payload { - issuer: string - countryCode: string -} \ No newline at end of file diff --git a/src/PaymentMethods/PaymentInitiation/index.ts b/src/PaymentMethods/PaymentInitiation/index.ts deleted file mode 100644 index 11d71ac3..00000000 --- a/src/PaymentMethods/PaymentInitiation/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' -import IPay from "./Models/IPay"; - -export default class PaymentInitiation extends PayablePaymentMethod { - protected _paymentName = 'PayByBank' - _serviceVersion = 1 - pay(payload: IPay) { - return super.pay(payload) - } - refund(payload: RefundPayload) { - return super.refund(payload) - } -} diff --git a/src/PaymentMethods/PaymentMethod.ts b/src/PaymentMethods/PaymentMethod.ts deleted file mode 100644 index 2e948318..00000000 --- a/src/PaymentMethods/PaymentMethod.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { TransactionRequest } from '../Models/Request' -import { IConfig, ServiceParameters } from '../Utils/Types' -import { RequestType } from '../Constants/Endpoints' -import { ITransaction } from '../Models/ITransaction' -import buckarooClient from '../BuckarooClient' -import { IServiceList } from '../Models/ServiceList' -export default abstract class PaymentMethod { - protected readonly _requiredFields: Array = ['currency', 'pushURL'] - protected _paymentName = '' - protected _serviceVersion = 0 - protected _request: TransactionRequest = new TransactionRequest() - private _action = '' - protected _serviceCodes:Array = [] - get paymentName(): string { - return this._paymentName - } - get request(): ITransaction { - return this._request.data - } - protected set paymentName(value: string) { - this._paymentName = value - } - get serviceVersion(): number { - return this._serviceVersion - } - protected get action(): string { - return this._action - } - protected set action(value: string) { - this._action = value - } - public setRequestAction(action:string) { - this._request.services?.ServiceList.forEach((service) => { - service.Action = action - }) - } - - public setRequest(data: ITransaction | (ITransaction & ServiceParameters) ) { - this._request.setBasicParameters(data) - - this.setRequiredFields() - - this.setServiceParameters(this._request.filter(data)) - } - - protected setServiceParameters(serviceParameters: ServiceParameters) { - let serviceList: IServiceList = { - Action: this.action, - Name: this.paymentName, - Version: this.serviceVersion - } - if (Object.keys(serviceParameters).length > 0) { - serviceList.Parameters = this._request.formatServiceParameters(serviceParameters) - } - this._request.addServices(serviceList) - } - - protected setRequiredFields() { - for (const requiredField of this._requiredFields) { - if (!this._request.data[requiredField]) - this._request.data[requiredField] = buckarooClient().getConfig()[requiredField] - } - } - protected transactionRequest(requestData: ITransaction | (ITransaction & ServiceParameters) ){ - this.setRequest(requestData) - - return buckarooClient().transactionRequest(this._request.data) - } - protected dataRequest(requestData: ITransaction | (ITransaction & ServiceParameters) = {}) { - this.setRequest(requestData) - - return buckarooClient().dataRequest(this._request.data) - } - public combine(method: PaymentMethod) { - if (Object.keys(method._request.data).length > 0) { - let services = this._request.services - if (services && method._request.services) { - method._request.services.ServiceList = services.ServiceList.concat( - method._request.services.ServiceList - ) - } - Object.assign(this._request.data, method._request.data) - } - return this - } - public specification(type?: RequestType) { - return buckarooClient().specification(this.paymentName, this.serviceVersion, type) - } -} diff --git a/src/PaymentMethods/Paypal/Models/Address.ts b/src/PaymentMethods/Paypal/Models/Address.ts new file mode 100644 index 00000000..ceb64659 --- /dev/null +++ b/src/PaymentMethods/Paypal/Models/Address.ts @@ -0,0 +1,44 @@ +import { Address as AddressClass, IAddress as IAddressGlobal } from '../../../Models'; + +export interface IAddress extends Partial { + street: string; + street2?: string; +} + +export class Address extends AddressClass { + set street2(value: string) { + this.set('street2', value); + } + + get street() { + return this.get('street1'); + } + + set street(value: string) { + this.set('street1', value); + } + + get city() { + return this.get('cityName'); + } + + set city(value: string) { + this.set('cityName', value); + } + + get state() { + return this.get('stateOrProvince'); + } + + set state(value: string) { + this.set('stateOrProvince', value); + } + + get zipcode() { + return this.get('postalCode'); + } + + set zipcode(value: string) { + this.set('postalCode', value); + } +} diff --git a/src/PaymentMethods/Paypal/Models/ExtraInfo.ts b/src/PaymentMethods/Paypal/Models/ExtraInfo.ts index b6c1ba71..1da7e288 100644 --- a/src/PaymentMethods/Paypal/Models/ExtraInfo.ts +++ b/src/PaymentMethods/Paypal/Models/ExtraInfo.ts @@ -1,3 +1,33 @@ -import { ServiceParameters } from '../../../Utils/Types' +import { IPaymentRequest, IPerson, IPhone, Person, ServiceParameter } from '../../../Models'; +import { Phone } from './Phone'; +import { Address, IAddress } from './Address'; -export interface IExtraInfo extends ServiceParameters {} +export interface IExtraInfo extends IPaymentRequest { + address?: IAddress; + customer?: Partial; + phone?: IPhone; + noShipping?: string; + addressOverride?: boolean; +} + +export class ExtraInfo extends ServiceParameter { + set address(value: IAddress) { + this.set('address', new Address(value)); + } + + set customer(value: IPerson) { + this.set('customer', new Person(value)); + } + + set phone(value: IPhone) { + this.set('phone', new Phone(value)); + } + + set noShipping(value: string) { + this.set('noShipping', value); + } + + set addressOverride(value: boolean) { + this.set('addressOverride', value); + } +} diff --git a/src/PaymentMethods/Paypal/Models/Pay.ts b/src/PaymentMethods/Paypal/Models/Pay.ts index 4211a012..ee555c6c 100644 --- a/src/PaymentMethods/Paypal/Models/Pay.ts +++ b/src/PaymentMethods/Paypal/Models/Pay.ts @@ -1,9 +1,31 @@ -import { Payload } from '../../../Models/ITransaction' - -export interface IPay extends Payload { - buyerEmail?: string - productName?: string - billingAgreementDescription?: string - pageStyle?: string - payPalOrderId?: string +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + buyerEmail?: string; + productName?: string; + billingAgreementDescription?: string; + pageStyle?: string; + payPalOrderId?: string; +} + +export class Pay extends ServiceParameter { + set buyerEmail(value: string) { + this.set('buyerEmail', value); + } + + set productName(value: string) { + this.set('productName', value); + } + + set billingAgreementDescription(value: string) { + this.set('billingAgreementDescription', value); + } + + set pageStyle(value: string) { + this.set('pageStyle', value); + } + + set payPalOrderId(value: string) { + this.set('payPalOrderId', value); + } } diff --git a/src/PaymentMethods/Paypal/Models/Phone.ts b/src/PaymentMethods/Paypal/Models/Phone.ts new file mode 100644 index 00000000..09de9088 --- /dev/null +++ b/src/PaymentMethods/Paypal/Models/Phone.ts @@ -0,0 +1,7 @@ +import { Phone as PhoneClass } from '../../../Models'; + +export class Phone extends PhoneClass { + set mobile(value: string) { + this.set('phone', value); + } +} diff --git a/src/PaymentMethods/Paypal/index.ts b/src/PaymentMethods/Paypal/index.ts index 26bd0386..e0b20ad7 100644 --- a/src/PaymentMethods/Paypal/index.ts +++ b/src/PaymentMethods/Paypal/index.ts @@ -1,22 +1,31 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { ICapture, RefundPayload } from '../../Models/ITransaction' -import { IPay } from './Models/Pay' -import { IExtraInfo } from './Models/ExtraInfo' +import { PayablePaymentMethod } from '../../Services'; +import { IPaymentRequest, IRefundRequest } from '../../Models'; +import { IPay, Pay } from './Models/Pay'; +import { ExtraInfo, IExtraInfo } from './Models/ExtraInfo'; +import { ServiceCode } from '../../Utils'; export default class Paypal extends PayablePaymentMethod { - protected _paymentName = 'paypal' + public defaultServiceCode(): ServiceCode { + return 'paypal'; + } + pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } - payRecurring(payload: ICapture) { - this.action = 'PayRecurring' - return super.transactionRequest(payload) + + payRecurrent(payload: IPaymentRequest) { + this.setPayPayload(payload); + this.setServiceList('PayRecurring'); + return super.transactionRequest(payload); } + extraInfo(payload: IExtraInfo) { - this.action = 'Pay,ExtraInfo' - return super.transactionRequest(payload) + this.setPayPayload(payload); + this.setServiceList('Pay,ExtraInfo', new ExtraInfo(payload)); + return super.transactionRequest(payload); } } diff --git a/src/PaymentMethods/PiM/Models/Generate.ts b/src/PaymentMethods/PiM/Models/Generate.ts new file mode 100644 index 00000000..74c91e64 --- /dev/null +++ b/src/PaymentMethods/PiM/Models/Generate.ts @@ -0,0 +1,45 @@ +import { IPaymentRequest, IPerson, ServiceParameter } from '../../../Models'; + +export interface IGenerate extends IPaymentRequest { + description: string; + title: string; + return: Partial & { + nickname?: string; + birthNamePrefix?: string; + birthName?: string; + email: string; + }; + result: { + title: string; + text: string; + }; +} + +export class Generate extends ServiceParameter { + set description(value: string) { + this.set('description', value); + } + + set title(value: string) { + this.set('title', value); + } + + set return(value: IGenerate['return']) { + this.set('returnNickname', value.nickname); + this.set('returnInitials', value.initials); + this.set('returnFirstname', value.firstName); + this.set('returnLastnamePrefix', value.lastNamePrefix); + this.set('returnLastname', value.lastName); + this.set('returnBirthnamePrefix', value.birthNamePrefix); + this.set('returnBirthname', value.birthName); + this.set('returnDateOfBirth', value.birthDate); + this.set('returnGender', value.gender); + this.set('returnEmail', value.email); + } + + set result(value: IGenerate['result']) { + this.set('resultTitle', value.title); + this.set('resultText', value.text); + } +} + diff --git a/src/PaymentMethods/PiM/index.ts b/src/PaymentMethods/PiM/index.ts index 3132fb96..a5f92f89 100644 --- a/src/PaymentMethods/PiM/index.ts +++ b/src/PaymentMethods/PiM/index.ts @@ -1,11 +1,16 @@ -import PaymentMethod from "../PaymentMethod"; -import { IConfig } from "../../Utils/Types"; +import { PaymentMethod } from '../../Services'; +import { Generate, IGenerate } from './Models/Generate'; +import { ServiceCode } from '../../Utils'; export default class PiM extends PaymentMethod { - _paymentName = "pim"; - _requiredFields:Array = ["currency"]; - generate(){ - this.action = 'generate' - return this.dataRequest() - } -} \ No newline at end of file + protected _requiredFields = ['currency']; + + public defaultServiceCode(): ServiceCode { + return 'pim'; + } + + generate(payload: IGenerate) { + this.setServiceList('Generate', new Generate(payload)); + return this.dataRequest(); + } +} diff --git a/src/PaymentMethods/PointOfSale/Models/Pay.ts b/src/PaymentMethods/PointOfSale/Models/Pay.ts new file mode 100644 index 00000000..8d1a50ea --- /dev/null +++ b/src/PaymentMethods/PointOfSale/Models/Pay.ts @@ -0,0 +1,11 @@ +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + terminalId: string; +} + +export class Pay extends ServiceParameter { + set terminalId(value: string) { + this.set('terminalID', value); + } +} diff --git a/src/PaymentMethods/PointOfSale/index.ts b/src/PaymentMethods/PointOfSale/index.ts index 2a4a4ffc..eb80ee6a 100644 --- a/src/PaymentMethods/PointOfSale/index.ts +++ b/src/PaymentMethods/PointOfSale/index.ts @@ -1,13 +1,13 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; -class Pointofsale extends PayablePaymentMethod { - protected _paymentName = 'pospayment' -} +export default class PointOfSale extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'pospayment'; + } -let _pointofsale: Pointofsale -const pointofsale: () => Pointofsale = () => { - if (!_pointofsale) _pointofsale = new Pointofsale() - return _pointofsale + pay(payload: IPay) { + return super.pay(payload, new Pay(payload)); + } } -export default pointofsale -export { Pointofsale as PointofsaleClass } diff --git a/src/PaymentMethods/Przelewy24/Models/Pay.ts b/src/PaymentMethods/Przelewy24/Models/Pay.ts index 57bfebaa..02e3b15d 100644 --- a/src/PaymentMethods/Przelewy24/Models/Pay.ts +++ b/src/PaymentMethods/Przelewy24/Models/Pay.ts @@ -1,7 +1,26 @@ -import { Payload } from '../../../Models/ITransaction' -export interface IPay extends Payload { - customerFirstName: string - customerLastName: string - customerEmail: string - email: string +import { IPaymentRequest, IPerson, Person, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + email: string; + customer: Partial; +} + +export class Pay extends ServiceParameter { + set email(email: string) { + this.set('customerEmail', email); + } + + set customer(customer: Partial) { + this.set('customer', new Customer(customer)); + } +} + +export class Customer extends Person { + set firstName(email: string) { + this.set('customerFirstName', email); + } + + set lastName(email: string) { + this.set('customerLastName', email); + } } diff --git a/src/PaymentMethods/Przelewy24/index.ts b/src/PaymentMethods/Przelewy24/index.ts index eaf95969..70a6dd36 100644 --- a/src/PaymentMethods/Przelewy24/index.ts +++ b/src/PaymentMethods/Przelewy24/index.ts @@ -1,14 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' -import { IPay } from './Models/Pay' +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; export default class Przelewy24 extends PayablePaymentMethod { - protected _paymentName = 'Przelewy24' + public defaultServiceCode(): ServiceCode { + return 'przelewy24'; + } pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/SEPA/Models/Emandate.ts b/src/PaymentMethods/SEPA/Models/Emandate.ts index 840cbd74..2f4ad602 100644 --- a/src/PaymentMethods/SEPA/Models/Emandate.ts +++ b/src/PaymentMethods/SEPA/Models/Emandate.ts @@ -1,6 +1,6 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest } from '../../../Models'; -export interface IEmandate extends Payload { - mandateReference: string - collectdate?: string +export interface IEmandate extends IPaymentRequest { + mandateReference: string; + collectdate?: string; } diff --git a/src/PaymentMethods/SEPA/Models/ExtraInfo.ts b/src/PaymentMethods/SEPA/Models/ExtraInfo.ts index 8c564c33..be3d5881 100644 --- a/src/PaymentMethods/SEPA/Models/ExtraInfo.ts +++ b/src/PaymentMethods/SEPA/Models/ExtraInfo.ts @@ -1,19 +1,16 @@ -import IAddress from '../../../Models/Services/IAddress' -import { Payload } from '../../../Models/ITransaction' +import { IAddress, IPaymentRequest } from '../../../Models'; -export type ExtraInfo = { - customeraccountname: string - customerBIC?: string - customerIBAN: string - collectDate: string - mandateReference?: string - mandateDate?: string - customerName?: string - customerCode?: string - customerReferencePartyCode?: string - customerReferencePartyName?: string - houseNumberSuffix: string - contractID: string -} & Omit - -export type IExtraInfo = ExtraInfo & Payload +export interface IExtraInfo extends IPaymentRequest { + bic?: string; + iban: string; + collectDate?: string; + mandateReference?: string; + mandateDate?: string; + customerReferencePartyCode?: string; + customerReferencePartyName?: string; + contractID: string; + customer: { + name: string; + }; + address: IAddress; +} diff --git a/src/PaymentMethods/SEPA/Models/Pay.ts b/src/PaymentMethods/SEPA/Models/Pay.ts index ebbec1d2..ac933c7a 100644 --- a/src/PaymentMethods/SEPA/Models/Pay.ts +++ b/src/PaymentMethods/SEPA/Models/Pay.ts @@ -1,10 +1,62 @@ -import { Payload } from '../../../Models/ITransaction' - -export interface IPay extends Payload { - customeraccountname: string - customerBIC?: string - customerIBAN: string - collectDate: string - mandateReference?: string - mandateDate?: string +import { IPaymentRequest, IPerson, Person, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + customer?: Partial; + bic?: string; + iban?: string; + collectDate?: string; + mandateReference?: string; + mandateDate?: string; +} + +export class Pay extends ServiceParameter { + get bic(): string { + return this.get('customerbic'); + } + + set bic(value: string) { + this.set('customerbic', value); + } + + get iban(): string { + return this.get('customerIBAN'); + } + + set iban(value: string) { + this.set('customerIBAN', value); + } + + set collectDate(value: string) { + this.set('collectDate', value); + } + + set mandateReference(value: string) { + this.set('mandateReference', value); + } + + set mandateDate(value: string) { + this.set('mandateDate', value); + } + + set customer(value: Partial) { + this.set('customer', new Customer(value)); + } +} + +export class Customer extends Person { + get name(): string { + return this.get('customeraccountname'); + } + + set name(value: string) { + this.set('customeraccountname', value); + } + + get firstName(): string { + return this.get('customeraccountname'); + } + + set firstName(value: string) { + this.set('customeraccountname', value); + } } diff --git a/src/PaymentMethods/SEPA/index.ts b/src/PaymentMethods/SEPA/index.ts index 62b01f7a..ab0f8927 100644 --- a/src/PaymentMethods/SEPA/index.ts +++ b/src/PaymentMethods/SEPA/index.ts @@ -1,43 +1,41 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { IPay } from './Models/Pay' -import { ICapture, RefundPayload } from '../../Models/ITransaction' -import { IExtraInfo } from './Models/ExtraInfo' -import { IEmandate } from './Models/Emandate' -import { uniqid } from '../../Utils/Functions' +import { PayablePaymentMethod } from '../../Services'; +import { IPay, Pay } from './Models/Pay'; +import { IExtraInfo } from './Models/ExtraInfo'; +import { IEmandate } from './Models/Emandate'; +import { ServiceCode, uniqid } from '../../Utils'; +import { IPaymentRequest } from '../../Models'; export default class SEPA extends PayablePaymentMethod { - - protected _paymentName = 'sepadirectdebit' - protected _serviceVersion = 1 - - constructor(type?:'B2B') { - super(); - if(type){ - this._paymentName = 'sepadirectdebitb2b' - } + public defaultServiceCode(): ServiceCode { + return 'sepadirectdebit'; } pay(payload: IPay) { - return super.pay(payload) - } - refund(payload: RefundPayload) { - return super.refund(payload) + return super.pay(payload, new Pay(payload)); } + authorize(payload: IPay) { - this.action = 'Authorize' - return super.transactionRequest(payload) + this.setPayPayload(payload); + this.setServiceList('Authorize', new Pay(payload)); + return this.transactionRequest(); } - payRecurrent(payload: Pick & ICapture) { - this.action = 'PayRecurrent' - return super.transactionRequest(payload) + + payRecurrent(payload: Pick & IPaymentRequest) { + this.setPayPayload(payload); + this.setServiceList('PayRecurrent', new Pay(payload)); + return this.transactionRequest(); } + extraInfo(payload: IExtraInfo) { - this.action = 'Pay,ExtraInfo' - return super.transactionRequest(payload) + this.setPayPayload(payload); + this.setServiceList('Pay,ExtraInfo', new Pay(payload)); + return this.transactionRequest(); } + payWithEmandate(payload: IEmandate) { - this.action = 'PayWithEmandate' - payload.invoice = payload.invoice || uniqid() - return super.transactionRequest(payload) + payload.invoice = payload.invoice || uniqid(); + this.setPayPayload(payload); + this.setServiceList('PayWithEmandate', new Pay(payload)); + return this.transactionRequest(); } } diff --git a/src/PaymentMethods/Sofort/index.ts b/src/PaymentMethods/Sofort/index.ts index 101e4677..aae1ded4 100644 --- a/src/PaymentMethods/Sofort/index.ts +++ b/src/PaymentMethods/Sofort/index.ts @@ -1,18 +1,24 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Payload, RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IPaymentRequest, IRefundRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; export default class Sofort extends PayablePaymentMethod { - protected _paymentName = 'sofortueberweisung' - protected _serviceVersion = 1 + protected _serviceVersion = 1; - pay(payload: Payload) { - return super.pay(payload) + public defaultServiceCode(): ServiceCode { + return 'sofortueberweisung'; } - refund(payload: RefundPayload) { - return super.refund(payload) + + pay(payload: IPaymentRequest) { + return super.pay(payload); + } + + refund(payload: IRefundRequest) { + return super.refund(payload); } - instantRefund(payload: RefundPayload){ - this.action = 'InstantRefund' - return super.refund(payload) + + instantRefund(payload: IRefundRequest) { + this.setServiceList('InstantRefund'); + return this.transactionRequest(payload); } } diff --git a/src/PaymentMethods/Subscriptions/Models/Company.ts b/src/PaymentMethods/Subscriptions/Models/Company.ts new file mode 100644 index 00000000..90f0c9cb --- /dev/null +++ b/src/PaymentMethods/Subscriptions/Models/Company.ts @@ -0,0 +1,7 @@ +import { Company as CompanyClass } from '../../../Models'; + +export default class Company extends CompanyClass { + set companyName(companyName: string) { + this.set('name', companyName); + } +} diff --git a/src/PaymentMethods/Subscriptions/Models/Configuration.ts b/src/PaymentMethods/Subscriptions/Models/Configuration.ts index 1d7b56d3..9f7f877d 100644 --- a/src/PaymentMethods/Subscriptions/Models/Configuration.ts +++ b/src/PaymentMethods/Subscriptions/Models/Configuration.ts @@ -1,10 +1,46 @@ +import { Model } from '../../../Models'; + export type IConfiguration = { - name?: string - schemeKey?: string - invoiceNumberPrefix?: string - invoiceDescriptionFormat?: string - dueDateDays?: number - allowedServices?: string - generateInvoiceSpecification?: boolean - skipPayPerEmail?: boolean + name?: string; + schemeKey?: string; + invoiceNumberPrefix?: string; + invoiceDescriptionFormat?: string; + dueDateDays?: number; + allowedServices?: string; + generateInvoiceSpecification?: boolean; + skipPayPerEmail?: boolean; +}; + +export class Configuration extends Model implements IConfiguration { + set name(value: string) { + this.set('name', value); + } + + set schemeKey(value: string) { + this.set('schemeKey', value); + } + + set invoiceNumberPrefix(value: string) { + this.set('invoiceNumberPrefix', value); + } + + set invoiceDescriptionFormat(value: string) { + this.set('invoiceDescriptionFormat', value); + } + + set dueDateDays(value: number) { + this.set('dueDateDays', value); + } + + set allowedServices(value: string) { + this.set('allowedServices', value); + } + + set generateInvoiceSpecification(value: boolean) { + this.set('generateInvoiceSpecification', value); + } + + set skipPayPerEmail(value: boolean) { + this.set('skipPayPerEmail', value); + } } diff --git a/src/PaymentMethods/Subscriptions/Models/ISubscription.ts b/src/PaymentMethods/Subscriptions/Models/ISubscription.ts index 42eab0ed..cfa52ee3 100644 --- a/src/PaymentMethods/Subscriptions/Models/ISubscription.ts +++ b/src/PaymentMethods/Subscriptions/Models/ISubscription.ts @@ -1,53 +1,183 @@ -import IPhone from '../../../Models/Services/IPhone' -import IAddress from '../../../Models/Services/IAddress' -import { IRatePlan, IRatePlanCharge } from './RatePlan' -import { IConfiguration } from './Configuration' -import { ServiceParameters } from '../../../Utils/Types' - -type Person = { - firstName: string - lastName: string - birthDate: string - gender: string - culture?: string -} -type Company = { - name: string - culture?: string - vatApplicable: boolean - vatNumber: string - chamberOfCommerce: string +import { + Address, + BankAccount, + IAddress, + IBankAccount, + ICompany, + IDebtor, + IPerson, + IPhone, + IRequest, + Person, + Phone, + ServiceParameter, +} from '../../../Models'; +import { IRatePlan, IRatePlans, RatePlan } from './RatePlan'; +import { IRatePlanCharge, IRatePlanCharges, RatePlanCharge } from './RatePlanCharge'; +import { Configuration, IConfiguration } from './Configuration'; +import Company from './Company'; + +export interface ISubscription extends IRequest { + address?: Partial; + allowedServices?: string; + b2b?: string; + billingTiming?: number; + company?: Partial; + configuration?: IConfiguration; + configurationCode?: string; + customerAccountName?: string; + customerBIC?: string; + customerIBAN?: string; + debtor?: IDebtor; + email?: string; + includeTransaction?: boolean; + mandateReference?: string; + person?: Partial; + phone?: Partial; + subscriptionGuid?: string; + termStartDay?: number; + termStartMonth?: number; + termStartWeek?: string; + transactionVatPercentage?: number; + ratePlans?: IRatePlans; + ratePlanCharges?: IRatePlanCharges; + bankAccount?: IBankAccount; } -export interface ISubscription extends ServiceParameters { - address?: IAddress - allowedServices?: string - b2b?: string - billingTiming?: number - company?:Company - addConfiguration?: IConfiguration - configurationCode?: string - customerAccountName?: string - customerBIC?: string - customerIBAN?: string - customerNumberOfDays?: string - debtor?: { - code: string - } - email?: { - email: string - } - includeTransaction?: boolean - fieldName?: string - mandateReference?: string - person?: Person - phone?: Partial - ratePlan?: IRatePlan - ratePlanCharge?: IRatePlanCharge - subscriptionGuid?: string - termStartDay?: number - termStartMonth?: number - termStartWeek?: string - transactionVatPercentage?: number - tokenPaymentMethod?: string +export class Subscription extends ServiceParameter implements ISubscription { + set configurationCode(configurationCode: string) { + this.set('configurationCode', configurationCode); + } + + set includeTransaction(includeTransaction: boolean) { + this.set('includeTransaction', includeTransaction); + } + + set transactionVatPercentage(transactionVatPercentage: number) { + this.set('transactionVatPercentage', transactionVatPercentage); + } + + set subscriptionGuid(value: string) { + this.set('subscriptionGuid', value); + } + + set termStartDay(value: number) { + this.set('termStartDay', value); + } + + set termStartMonth(value: number) { + this.set('termStartMonth', value); + } + + set billingTiming(value: number) { + this.set('billingTiming', value); + } + + set termStartWeek(value: string) { + this.set('termStartWeek', value); + } + + set b2b(value: string) { + this.set('b2b', value); + } + + set mandateReference(value: string) { + this.set('mandateReference', value); + } + + set allowedServices(value: string) { + this.set('allowedServices', value); + } + + set debtor(value: IDebtor) { + this.set('debtor', value); + } + + set bankAccount(value: IBankAccount) { + this.set('bankAccount', new BankAccount(value)); + } + + set email(value: string) { + this.set('email', value); + } + + set phone(value: IPhone) { + this.set('phone', new Phone(value)); + } + + set address(value: IAddress) { + this.set('address', new Address(value)); + } + + set person(value: IPerson) { + this.set('person', new Person(value)); + } + + set company(value: ICompany) { + this.set('company', new Company(value)); + } + + set configuration(value: Configuration) { + this.set('configuration', new Configuration(value)); + } + + set ratePlans(value: IRatePlans) { + Object.entries(value).forEach(([key, val]) => { + if (this.has(key + 'RatePlan')) { + this.set(key + 'RatePlan', val); + } + }); + } + + set ratePlanCharges(value: IRatePlanCharges) { + Object.entries(value).forEach(([key, val]) => { + if (this.has(key + 'RatePlanCharge')) { + this.set(key + 'RatePlanCharge', val); + } + }); + } + + set customerIBAN(value: string) { + this.set('customerIBAN', value); + } + + set customerAccountName(value: string) { + this.set('customerAccountName', value); + } + + set customerBIC(value: string) { + this.set('customerBIC', value); + } + + protected set addRatePlan(value: IRatePlan) { + this.set('addRatePlan', new RatePlan(value)); + } + + protected set updateRatePlan(value: IRatePlan) { + this.set('updateRatePlan', new RatePlan(value)); + } + + protected set disableRatePlan(value: IRatePlan) { + this.set('disableRatePlan', new RatePlan(value)); + } + + protected set addRatePlanCharge(value: IRatePlanCharge) { + this.set('addRatePlanCharge', new RatePlanCharge(value)); + } + + getGroups() { + return super.getGroups({ + Debtor: 'Debtor', + Person: 'Person', + Email: 'Email', + Address: 'Address', + AddRatePlan: 'AddRatePlan', + Configuration: 'AddConfiguration', + UpdateRatePlan: 'UpdateRatePlan', + DisableRatePlan: 'DisableRatePlan', + AddRatePlanCharge: 'AddRatePlanCharge', + UpdateRatePlanCharge: 'UpdateRatePlanCharge', + DisableRatePlanCharge: 'DisableRatePlanCharge', + }); + } } diff --git a/src/PaymentMethods/Subscriptions/Models/RatePlan.ts b/src/PaymentMethods/Subscriptions/Models/RatePlan.ts index 5a7b5c6c..2988fff2 100644 --- a/src/PaymentMethods/Subscriptions/Models/RatePlan.ts +++ b/src/PaymentMethods/Subscriptions/Models/RatePlan.ts @@ -1,68 +1,102 @@ -type update = { - update: { - startDate: string - endDate?: string - ratePlanGuid: string - } +import { Model } from '../../../Models'; + +export interface IRatePlans { + add?: IRatePlan; + update?: IRatePlan; + disable?: IRatePlan; } -type disable = { - disable: { - ratePlanGuid: string - } + +export interface IRatePlan { + type?: string; + ratePlanGuid?: string; + ratePlanCode?: string; + startDate?: string; + endDate?: string; + ratePlanName?: string; + ratePlanDescription?: string; + currency?: string; + billingTiming?: number; + automaticTerm?: boolean; + billingInterval?: string; + customNumberOfDays?: number; + termStartDay?: number; + termStartWeek?: string; + termStartMonth?: string; + trialPeriodDays?: number; + trialPeriodMonth?: string; + inheritPaymentMethod?: boolean; } -type add = { - add: { - startDate: string - ratePlanCode?: string - endDate?: string - ratePlanName?: string - ratePlanDescription?: string - currency?: string - billingTiming?: number - automaticTerm?: boolean - billingInterval?: string - customNumberOfDays?: number - termStartDay?: number - termStartWeek?: number - termStartMonth?: number - trialPeriodDays?: number - trialPeriodMonths?: number - inheritPaymentMethod?: boolean + +export class RatePlan extends Model implements IRatePlan { + set type(value: string) { + this.set('type', value); } -} -export type IRatePlan = add | update | disable - -type addCharge = { - add: { - ratePlanChargeCode?: string - ratePlanChargeName?: string - ratePlanChargeProductId?: string - ratePlanChargeDescription?: string - unitOfMeasure?: string - ratePlanChargeType?: string - baseNumberOfUnits?: number - partialBilling?: string - pricePerUnit?: number - priceIncludesVat?: boolean - vatPercentage?: number - b2B?: boolean + set ratePlanGuid(value: string) { + this.set('ratePlanGuid', value); } -} -type updateCharge = { - update: { - ratePlanChargeCode?: string - vatPercentage?: number - ratePlanChargeGuid?: string - baseNumberOfUnits?: string | number - pricePerUnit?: number - priceIncludesVat?: boolean + + set ratePlanCode(value: string) { + this.set('ratePlanCode', value); } -} -type disableCharge = { - disable: { - ratePlanChargeGuid?: string + + set startDate(value: string) { + this.set('startDate', value); + } + + set endDate(value: string) { + this.set('endDate', value); + } + + set ratePlanName(value: string) { + this.set('ratePlanName', value); } -} -export type IRatePlanCharge = addCharge | updateCharge | disableCharge + set ratePlanDescription(value: string) { + this.set('ratePlanDescription', value); + } + + set currency(value: string) { + this.set('currency', value); + } + + set billingTiming(value: number) { + this.set('billingTiming', value); + } + + set automaticTerm(value: boolean) { + this.set('automaticTerm', value); + } + + set billingInterval(value: string) { + this.set('billingInterval', value); + } + + set customNumberOfDays(value: number) { + this.set('customNumberOfDays', value); + } + + set termStartDay(value: number) { + this.set('termStartDay', value); + } + + set termStartWeek(value: string) { + this.set('termStartWeek', value); + } + + set termStartMonth(value: string) { + this.set('termStartMonth', value); + } + + set trialPeriodDays(value: number) { + this.set('trialPeriodDays', value); + } + + set trialPeriodMonth(value: string) { + this.set('trialPeriodMonth', value); + } + + set inheritPaymentMethod(value: boolean) { + this.set('inheritPaymentMethod', value); + } +} diff --git a/src/PaymentMethods/Subscriptions/Models/RatePlanCharge.ts b/src/PaymentMethods/Subscriptions/Models/RatePlanCharge.ts new file mode 100644 index 00000000..4b6e53a4 --- /dev/null +++ b/src/PaymentMethods/Subscriptions/Models/RatePlanCharge.ts @@ -0,0 +1,72 @@ +import { Model } from '../../../Models'; + +export interface IRatePlanCharge { + ratePlanChargeCode?: string; + ratePlanChargeName?: string; + ratePlanChargeProductId?: string; + ratePlanChargeDescription?: string; + unitOfMeasure?: string; + baseNumberOfUnits?: number; + partialBilling?: string; + pricePerUnit?: number; + priceIncludesVat?: boolean; + vatPercentage?: number; + b2b?: string; + ratePlanChargeType?: string; +} + +export interface IRatePlanCharges { + add?: IRatePlanCharge; + update?: IRatePlanCharge; + disable?: IRatePlanCharge; +} + +export class RatePlanCharge extends Model implements IRatePlanCharge { + set ratePlanChargeCode(value: string) { + this.set('ratePlanChargeCode', value); + } + + set ratePlanChargeName(value: string) { + this.set('ratePlanChargeName', value); + } + + set ratePlanChargeProductId(value: string) { + this.set('rateplanChargeProductId', value); + } + + set ratePlanChargeDescription(value: string) { + this.set('rateplanChargeDescription', value); + } + + set unitOfMeasure(value: string) { + this.set('unitOfMeasure', value); + } + + set baseNumberOfUnits(value: number) { + this.set('baseNumberOfUnits', value); + } + + set partialBilling(value: string) { + this.set('partialBilling', value); + } + + set pricePerUnit(value: number) { + this.set('pricePerUnit', value); + } + + set priceIncludesVat(value: boolean) { + this.set('priceIncludesVat', value); + } + + set vatPercentage(value: number) { + this.set('vatPercentage', value); + } + + set b2b(value: string) { + this.set('b2B', value); + } + + set ratePlanChargeType(value: string) { + this.set('ratePlanChargeType', value); + } +} diff --git a/src/PaymentMethods/Subscriptions/Models/ResumeSubscription.ts b/src/PaymentMethods/Subscriptions/Models/ResumeSubscription.ts new file mode 100644 index 00000000..bc348ca7 --- /dev/null +++ b/src/PaymentMethods/Subscriptions/Models/ResumeSubscription.ts @@ -0,0 +1,7 @@ +import { Subscription } from './ISubscription'; + +export class ResumeSubscription extends Subscription { + set resumeDate(resumeDate: string) { + this.set('resumeDate', resumeDate); + } +} diff --git a/src/PaymentMethods/Subscriptions/index.ts b/src/PaymentMethods/Subscriptions/index.ts index 53524d9e..3a6c7dcb 100644 --- a/src/PaymentMethods/Subscriptions/index.ts +++ b/src/PaymentMethods/Subscriptions/index.ts @@ -1,54 +1,63 @@ -import { ISubscription } from './Models/ISubscription' -import { IConfig } from '../../Utils/Types' -import PaymentMethod from '../PaymentMethod' +import { ISubscription, Subscription } from './Models/ISubscription'; +import { PaymentMethod } from '../../Services'; +import { IRequest } from '../../Models'; +import { ResumeSubscription } from './Models/ResumeSubscription'; +import { ServiceCode } from '../../Utils'; export default class Subscriptions extends PaymentMethod { - protected _paymentName = 'Subscriptions' - protected _requiredFields: Array = ['currency'] + protected _serviceVersion = 1; + protected _requiredFields: Array = ['currency']; - _serviceVersion = 1 - create(payload: ISubscription): Promise { - this.action = 'CreateSubscription' - return this.dataRequest(payload) + public defaultServiceCode(): ServiceCode { + return 'subscriptions'; } + + create(payload: ISubscription) { + this.setPayload(payload); + this.setServiceList('CreateSubscription', new Subscription(payload)); + return this.dataRequest(); + } + update(payload: ISubscription) { - this.action = 'UpdateSubscription' - return this.dataRequest(payload) + this.setPayload(payload); + this.setServiceList('UpdateSubscription', new Subscription(payload)); + return this.dataRequest(); } + createCombined(payload: ISubscription) { - this.action = 'CreateCombinedSubscription' - this.setRequest(payload) - return this + this.setPayload(payload); + this.setServiceList('CreateCombinedSubscription', new Subscription(payload)); + return this.dataRequest(); } + updateCombined(payload: ISubscription) { - this.action = 'UpdateCombinedSubscription' - this._request.data.startRecurrent = true - this.setRequest(payload) - return this + this.setPayload(payload); + this.setServiceList('UpdateCombinedSubscription', new Subscription(payload)); + return this.dataRequest(); } + stop(payload: { subscriptionGuid: string }) { - this.action = 'StopSubscription' - return this.dataRequest(payload) + this.setServiceList('StopSubscription', new Subscription(payload)); + return this.dataRequest(); } - info(payload: { subscriptionGuid: string }) { - this.action = 'SubscriptionInfo' - return this.dataRequest(payload) + info(payload: { subscriptionGuid: string }) { + this.setServiceList('StopSubscription', new Subscription(payload)); + return this.dataRequest(); } - deletePaymentConfig(payload: { subscriptionGuid: string }) { - this.action = 'DeletePaymentConfiguration' - return this.dataRequest(payload) + deletePaymentConfig(payload: { subscriptionGuid: string }) { + this.setServiceList('DeletePaymentConfiguration', new Subscription(payload)); + return this.dataRequest(); } pause(payload: { subscriptionGuid: string; resumeDate: string }) { - this.action = 'PauseSubscription' - - return this.dataRequest(payload) + this.setServiceList('PauseSubscription', new ResumeSubscription(payload)); + return this.dataRequest(); } - resume(payload: { subscriptionGuid: string; resumeDate: string }) { - this.action = 'ResumeSubscription' - return this.dataRequest(payload) + resume(payload: { subscriptionGuid: string; resumeDate: string }) { + this.setServiceList('ResumeSubscription', new ResumeSubscription(payload)); + return this.dataRequest(); } } diff --git a/src/PaymentMethods/Surepay/Models/BankAccount.ts b/src/PaymentMethods/Surepay/Models/BankAccount.ts new file mode 100644 index 00000000..1179cbc6 --- /dev/null +++ b/src/PaymentMethods/Surepay/Models/BankAccount.ts @@ -0,0 +1,16 @@ +import { Model } from '../../../Models'; + +export interface IBankAccount { + iban: string; + accountName: string; +} + +export class BankAccount extends Model implements IBankAccount { + set accountName(value: string) { + this.set('customeraccountname', value); + } + + set iban(iban: string) { + this.set('iban', iban); + } +} diff --git a/src/PaymentMethods/Surepay/Models/Verify.ts b/src/PaymentMethods/Surepay/Models/Verify.ts index cd34962c..89da27fb 100644 --- a/src/PaymentMethods/Surepay/Models/Verify.ts +++ b/src/PaymentMethods/Surepay/Models/Verify.ts @@ -1,5 +1,12 @@ -import { ITransaction } from '../../../Models/ITransaction' +import { IPaymentRequest, ServiceParameter } from '../../../Models'; +import { BankAccount, IBankAccount } from './BankAccount'; -export interface IVerify extends ITransaction { - customeraccountname: 'string' +export interface IVerify extends IPaymentRequest { + bankAccount: Partial; +} + +export class Verify extends ServiceParameter { + set bankAccount(value: IBankAccount) { + this.set('bankAccount', new BankAccount(value)); + } } diff --git a/src/PaymentMethods/Surepay/index.ts b/src/PaymentMethods/Surepay/index.ts index 0368e1d5..40969745 100644 --- a/src/PaymentMethods/Surepay/index.ts +++ b/src/PaymentMethods/Surepay/index.ts @@ -1,11 +1,14 @@ -import PaymentMethod from '../PaymentMethod' -import { IVerify } from './Models/Verify' +import { PaymentMethod } from '../../Services'; +import { IVerify, Verify } from './Models/Verify'; +import { ServiceCode } from '../../Utils'; export default class Surepay extends PaymentMethod { - protected _paymentName = 'surepay' - _requiredFields = [] + public defaultServiceCode(): ServiceCode { + return 'surepay'; + } + verify(payload: IVerify) { - this.action = 'verify' - return this.dataRequest(payload) + this.setServiceList('Verify', new Verify(payload)); + return super.dataRequest(payload); } } diff --git a/src/PaymentMethods/Thunes/index.ts b/src/PaymentMethods/Thunes/index.ts index d92c5ba3..187ee5ed 100644 --- a/src/PaymentMethods/Thunes/index.ts +++ b/src/PaymentMethods/Thunes/index.ts @@ -1,23 +1,31 @@ -import PaymentMethod from "../PaymentMethod"; -import { ICapture, ITransaction, Payload } from "../../Models/ITransaction"; +import { PaymentMethod } from '../../Services'; +import { IRequest } from '../../Models'; +import { ServiceCode } from '../../Utils'; + +type key = Required>; export default class Thunes extends PaymentMethod { - protected _paymentName = "thunes"; + public defaultServiceCode(): ServiceCode { + return 'thunes'; + } - getStatus(payload: Required>) { - this.action = 'getStatus' - return this.dataRequest(payload) + getStatus(payload: key) { + this.setServiceList('getStatus'); + return this.dataRequest(payload); } - capture(payload:ICapture) { - this.action = 'capture' - return this.transactionRequest(payload) + + capture(payload: IRequest & key) { + this.setServiceList('Capture'); + return this.transactionRequest(payload); } - authorize(payload:Payload) { - this.action = 'authorize' - return this.dataRequest(payload) + + authorize(payload: IRequest) { + this.setServiceList('Authorize'); + return this.dataRequest(payload); } - cancel(payload:Pick) { - this.action = 'cancel' - return this.dataRequest(payload) + + cancel(payload: key) { + this.setServiceList('Cancel'); + return this.dataRequest(payload); } -} \ No newline at end of file +} diff --git a/src/PaymentMethods/Tinka/Models/Address.ts b/src/PaymentMethods/Tinka/Models/Address.ts index 000207a7..2fe31d7a 100644 --- a/src/PaymentMethods/Tinka/Models/Address.ts +++ b/src/PaymentMethods/Tinka/Models/Address.ts @@ -1,8 +1,15 @@ -export type ITinkaAddress = { - street: string - streetNumber: string - streetNumberAdditional?: string - postalCode: string - city: string - country?: string +import { Address } from '../../../Models'; + +export class TinkaAddress extends Address { + set houseNumber(value: string) { + this.set('streetNumber', value); + } + + set houseNumberAdditional(value: string) { + this.set('streetNumberAdditional', value); + } + + set zipcode(value: string) { + this.set('postalCode', value); + } } diff --git a/src/PaymentMethods/Tinka/Models/Article.ts b/src/PaymentMethods/Tinka/Models/Article.ts index e3aaa304..f2a70b09 100644 --- a/src/PaymentMethods/Tinka/Models/Article.ts +++ b/src/PaymentMethods/Tinka/Models/Article.ts @@ -1,18 +1,20 @@ -export enum ArticleType { - Unknown = 0, - Article = 1, - GiftCard = 2, - Discount = 3 +import { Article, IArticle } from '../../../Models'; + +export interface ITinkaArticle extends IArticle { + color?: string; + size?: string; } -export type ITinkaArticle = { - type?: ArticleType - quantity: number - unitCode: string - description: string - brand?: string - manufacturer?: string - unitGrossPrice: number - color?: string - size?: string +export class TinkaArticle extends Article { + set color(value: string) { + this.set('color', value); + } + + set price(value: number) { + this.set('unitGrossPrice', value); + } + + set size(value: string) { + this.set('size', value); + } } diff --git a/src/PaymentMethods/Tinka/Models/Pay.ts b/src/PaymentMethods/Tinka/Models/Pay.ts index f5293b2f..8f92909b 100644 --- a/src/PaymentMethods/Tinka/Models/Pay.ts +++ b/src/PaymentMethods/Tinka/Models/Pay.ts @@ -1,23 +1,62 @@ -import { Payload } from '../../../Models/ITransaction' -import { ITinkaArticle } from './Article' -import { ITinkaAddress } from './Address' -import Gender from '../../../Constants/Gender' -export interface IPay extends Payload { - paymentMethod: string - deliveryMethod: string - deliveryDate?: string - article: ITinkaArticle[] - billingCustomer: { - email: string - phone?: string - prefixLastName?: string - } & ITinkaAddress - shippingCustomer?: { - externalName: false - } & ITinkaAddress - dateOfBirth?: string - firstName?: string - gender?: Gender - initials?: string - lastName?: string +import { ICustomer, IPaymentRequest, ServiceParameter } from '../../../Models'; +import { ITinkaArticle, TinkaArticle } from './Article'; +import { ITinkaPerson, TinkaPerson } from './Person'; +import { Recipient } from './Recipient'; + +export interface IPay extends IPaymentRequest { + paymentMethod: string; + deliveryMethod: string; + deliveryDate?: string; + articles: Partial[]; + customer: ITinkaPerson; + shipping?: ICustomer; + billing: ICustomer; +} + +export class Pay extends ServiceParameter { + set paymentMethod(value: string) { + this.set('paymentMethod', value); + } + + set deliveryMethod(value: string) { + this.set('deliveryMethod', value); + } + + set deliveryDate(value: string) { + this.set('deliveryDate', value); + } + + set articles(value: ITinkaArticle[]) { + this.set( + 'articles', + value.map((article) => new TinkaArticle(article)) + ); + } + + set customer(value: ITinkaPerson) { + this.set('customer', new TinkaPerson(value)); + } + + set shipping(value: ICustomer) { + this.set('shipping', new Recipient(value)); + } + + set billing(value: ICustomer) { + this.set('billing', new Recipient(value)); + if (this.shipping === undefined) { + this.shipping = value; + } + } + + protected getGroups() { + return super.getGroups({ + Articles: 'Article', + Shipping: 'ShippingCustomer', + Billing: 'BillingCustomer', + }); + } + + protected getCountable() { + return super.getCountable(['Articles']); + } } diff --git a/src/PaymentMethods/Tinka/Models/Person.ts b/src/PaymentMethods/Tinka/Models/Person.ts new file mode 100644 index 00000000..aedd6667 --- /dev/null +++ b/src/PaymentMethods/Tinka/Models/Person.ts @@ -0,0 +1,20 @@ +import { Person } from '../../../Models'; +import { Gender } from '../../../Constants'; + +export interface ITinkaPerson { + gender: Gender; + firstName: string; + lastName: string; + initials: string; + birthDate: string; +} + +export class TinkaPerson extends Person { + set lastNamePrefix(value: string) { + this.set('prefixLastName', value); + } + + set birthDate(value: string) { + this.set('dateOfBirth', value); + } +} diff --git a/src/PaymentMethods/Tinka/Models/Phone.ts b/src/PaymentMethods/Tinka/Models/Phone.ts new file mode 100644 index 00000000..def298e4 --- /dev/null +++ b/src/PaymentMethods/Tinka/Models/Phone.ts @@ -0,0 +1,7 @@ +import { Phone } from '../../../Models'; + +export class TinkaPhone extends Phone { + set mobile(value: string) { + this.set('phone', value); + } +} diff --git a/src/PaymentMethods/Tinka/Models/Recipient.ts b/src/PaymentMethods/Tinka/Models/Recipient.ts new file mode 100644 index 00000000..a2ea1618 --- /dev/null +++ b/src/PaymentMethods/Tinka/Models/Recipient.ts @@ -0,0 +1,18 @@ +import { Customer, IAddress, IPerson, IPhone } from '../../../Models'; +import { TinkaAddress } from './Address'; +import { TinkaPhone } from './Phone'; +import { TinkaPerson } from './Person'; + +export class Recipient extends Customer { + set address(value: IAddress) { + this.set('address', new TinkaAddress(value)); + } + + set phone(value: IPhone) { + this.set('phone', new TinkaPhone(value)); + } + + set recipient(value: IPerson) { + this.set('recipient', new TinkaPerson(value)); + } +} diff --git a/src/PaymentMethods/Tinka/index.ts b/src/PaymentMethods/Tinka/index.ts index d29260a0..6a3961c5 100644 --- a/src/PaymentMethods/Tinka/index.ts +++ b/src/PaymentMethods/Tinka/index.ts @@ -1,18 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' -import { IPay } from './Models/Pay' +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; export default class Tinka extends PayablePaymentMethod { - protected _paymentName = 'tinka' - _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'tinka'; + } + pay(payload: IPay) { - if (payload.billingCustomer) { - // @ts-ignore - payload.shippingCustomer = payload.shippingCustomer || payload.billingCustomer - } - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/Trustly/Models/Customer.ts b/src/PaymentMethods/Trustly/Models/Customer.ts new file mode 100644 index 00000000..3fd8a54e --- /dev/null +++ b/src/PaymentMethods/Trustly/Models/Customer.ts @@ -0,0 +1,15 @@ +import { Model } from '../../../Models'; + +export class Customer extends Model { + set firstName(value: string) { + this.set('CustomerFirstName', value); + } + + set lastName(value: string) { + this.set('customerLastName', value); + } + + set countryCode(value: string) { + this.set('customerCountryCode', value); + } +} diff --git a/src/PaymentMethods/Trustly/Models/Pay.ts b/src/PaymentMethods/Trustly/Models/Pay.ts index e8668393..e7005b0d 100644 --- a/src/PaymentMethods/Trustly/Models/Pay.ts +++ b/src/PaymentMethods/Trustly/Models/Pay.ts @@ -1,7 +1,16 @@ -import { Payload } from '../../../Models/ITransaction' +import { IPaymentRequest, IPerson, ServiceParameter } from '../../../Models'; +import { Customer } from './Customer'; -export interface IPay extends Payload { - customerCountryCode: 'DE' | 'DK' | 'EE' | 'ES' | 'FI' | 'NL' | 'NO' | 'PL' | 'SE' | 'GB' - customerFirstName: string - customerLastName: string +export interface IPay extends IPaymentRequest { + customer: Partial & { country?: 'DE' | 'DK' | 'EE' | 'ES' | 'FI' | 'NL' | 'NO' | 'PL' | 'SE' | 'GB' }; +} + +export class Pay extends ServiceParameter { + set customer(value: Partial) { + this.set('customer', new Customer(value)); + } + + set country(value: string) { + this.set('country', value); + } } diff --git a/src/PaymentMethods/Trustly/index.ts b/src/PaymentMethods/Trustly/index.ts index 95199de1..333f21b5 100644 --- a/src/PaymentMethods/Trustly/index.ts +++ b/src/PaymentMethods/Trustly/index.ts @@ -1,15 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { RefundPayload } from '../../Models/ITransaction' -import { IPay } from './Models/Pay' +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; export default class Trustly extends PayablePaymentMethod { - protected _paymentName = 'Trustly' - protected _serviceVersion = 1 + public defaultServiceCode(): ServiceCode { + return 'trustly'; + } pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/WeChatPay/Models/Pay.ts b/src/PaymentMethods/WeChatPay/Models/Pay.ts new file mode 100644 index 00000000..9607d1a4 --- /dev/null +++ b/src/PaymentMethods/WeChatPay/Models/Pay.ts @@ -0,0 +1,11 @@ +import { IPaymentRequest, ServiceParameter } from '../../../Models'; + +export interface IPay extends IPaymentRequest { + locale?: string; +} + +export class Pay extends ServiceParameter { + set locale(value: string) { + this.set('locale', value); + } +} diff --git a/src/PaymentMethods/WeChatPay/index.ts b/src/PaymentMethods/WeChatPay/index.ts index 80bbf0ca..b08c4465 100644 --- a/src/PaymentMethods/WeChatPay/index.ts +++ b/src/PaymentMethods/WeChatPay/index.ts @@ -1,16 +1,18 @@ -import { PayablePaymentMethod } from '../PayablePaymentMethod' -import { Payload, RefundPayload } from '../../Models/ITransaction' +import { PayablePaymentMethod } from '../../Services'; +import { IRefundRequest } from '../../Models'; +import { IPay, Pay } from './Models/Pay'; +import { ServiceCode } from '../../Utils'; -interface IPay extends Payload { - locale: 'en-US' | 'zh-CN' | 'zh-TW' -} -export default class Wechatpay extends PayablePaymentMethod { - protected _paymentName = 'wechatpay' +export default class WeChatPay extends PayablePaymentMethod { + public defaultServiceCode(): ServiceCode { + return 'wechatpay'; + } pay(payload: IPay) { - return super.pay(payload) + return super.pay(payload, new Pay(payload)); } - refund(payload: RefundPayload) { - return super.refund(payload) + + refund(payload: IRefundRequest) { + return super.refund(payload); } } diff --git a/src/PaymentMethods/iDealQR/Models/Generate.ts b/src/PaymentMethods/iDealQR/Models/Generate.ts deleted file mode 100644 index 7dcd28d7..00000000 --- a/src/PaymentMethods/iDealQR/Models/Generate.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Payload } from '../../../Models/ITransaction' - -export interface Generate extends Payload { - amount: number - amountIsChangeable: boolean - purchaseId: string - Description: string - isOneOff: boolean - expiration: string - isProcessing?: boolean - minAmount: number - maxAmount: number - imageSize: number -} diff --git a/src/PaymentMethods/iDealQR/index.ts b/src/PaymentMethods/iDealQR/index.ts deleted file mode 100644 index b1033c54..00000000 --- a/src/PaymentMethods/iDealQR/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Generate } from './Models/Generate' -import PaymentMethod from '../PaymentMethod' - -export default class IdealQr extends PaymentMethod { - protected _paymentName = 'IdealQr' - generate(payload: Generate) { - this.action = 'generate' - - return this.dataRequest(payload) - } -} diff --git a/src/PaymentMethods/iDin/index.ts b/src/PaymentMethods/iDin/index.ts deleted file mode 100644 index d05403b3..00000000 --- a/src/PaymentMethods/iDin/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -import PaymentMethod from '../PaymentMethod' -import { IPay } from '../Ideal/Models/Pay' -export default class Idin extends PaymentMethod { - protected _paymentName = 'Idin' - identify(payload: IPay) { - return this.dataRequest(payload) - } - verify(payload: IPay) { - return this.dataRequest(payload) - } - login(payload: IPay) { - return this.dataRequest(payload) - } -} diff --git a/src/PaymentMethods/index.ts b/src/PaymentMethods/index.ts new file mode 100644 index 00000000..8e85fdd2 --- /dev/null +++ b/src/PaymentMethods/index.ts @@ -0,0 +1,86 @@ +export { default as ideal } from './Ideal'; +export { default as idealprocessing } from './Ideal'; +export { default as afterpay } from './Afterpay'; +export { default as afterpaydigiaccept } from './AfterpayDigiAccept'; +export { default as applepay } from './ApplePay'; +export { default as bancontactmrcash } from './Bancontact'; +export { default as transfer } from './BankTransfer'; +export { default as belfius } from './Belfius'; +export { default as billink } from './Billink'; +export { default as buckaroovoucher } from './BuckarooVoucher'; +export { default as BuckarooWalletCollecting } from './BuckarooWallet'; +export { default as CreditCard } from './CreditCard'; + +// Credit Cards +export { default as creditcard } from './CreditCard'; +export { default as mastercard } from './CreditCard'; +export { default as visa } from './CreditCard'; +export { default as amex } from './CreditCard'; +export { default as vpay } from './CreditCard'; +export { default as maestro } from './CreditCard'; +export { default as visaelectron } from './CreditCard'; +export { default as cartebleuevisa } from './CreditCard'; +export { default as cartebancaire } from './CreditCard'; +export { default as dankort } from './CreditCard'; +export { default as nexi } from './CreditCard'; +export { default as postepay } from './CreditCard'; + +export { default as creditclick } from './CreditClick'; +export { default as CreditManagement3 } from './CreditManagement'; +export { default as emandate } from './Emandates'; +export { default as eps } from './EPS'; + +// Gift Cards +export { default as giftcard } from './GiftCard'; +export { default as westlandbon } from './GiftCard'; +export { default as babygiftcard } from './GiftCard'; +export { default as babyparkgiftcard } from './GiftCard'; +export { default as beautywellness } from './GiftCard'; +export { default as boekenbon } from './GiftCard'; +export { default as boekenvoordeel } from './GiftCard'; +export { default as designshopsgiftcard } from './GiftCard'; +export { default as fashioncheque } from './GiftCard'; +export { default as fashionucadeaukaart } from './GiftCard'; +export { default as fijncadeau } from './GiftCard'; +export { default as koffiecadeau } from './GiftCard'; +export { default as kokenzo } from './GiftCard'; +export { default as kookcadeau } from './GiftCard'; +export { default as nationaleentertainmentcard } from './GiftCard'; +export { default as naturesgift } from './GiftCard'; +export { default as podiumcadeaukaart } from './GiftCard'; +export { default as shoesaccessories } from './GiftCard'; +export { default as webshopgiftcard } from './GiftCard'; +export { default as wijncadeau } from './GiftCard'; +export { default as wonenzo } from './GiftCard'; +export { default as yourgift } from './GiftCard'; +export { default as vvvgiftcard } from './GiftCard'; +export { default as parfumcadeaukaart } from './GiftCard'; + +export { default as giropay } from './Giropay'; +export { default as idealqr } from './IdealQR'; +export { default as idin } from './Idin'; +export { default as capayable } from './In3Old'; +export { default as KBCPaymentButton } from './KBC'; +export { default as klarna } from './Klarna'; +export { default as klarnakp } from './KlarnaKP'; +export { default as marketplaces } from './Marketplaces'; +export { default as MBWay } from './Mbway'; +export { default as multibanco } from './Multibanco'; +export { default as payconiq } from './Payconiq'; +export { default as PayByBank } from './PayByBank'; +export { default as paypal } from './Paypal'; +export { default as payperemail } from './PayPerEmail'; +export { default as pim } from './PiM'; +export { default as pospayment } from './PointOfSale'; +export { default as przelewy24 } from './Przelewy24'; +export { default as sepadirectdebit } from './SEPA'; +export { default as sofortueberweisung } from './Sofort'; +export { default as subscriptions } from './Subscriptions'; +export { default as surepay } from './Surepay'; +export { default as thunes } from './Thunes'; +export { default as tinka } from './Tinka'; +export { default as alipay } from './Alipay'; +export { default as trustly } from './Trustly'; +export { default as wechatpay } from './WeChatPay'; +export { default as In3 } from './In3'; +export { default as noservice } from './NoService'; \ No newline at end of file diff --git a/src/Request/Client.ts b/src/Request/Client.ts deleted file mode 100644 index 3c7c552e..00000000 --- a/src/Request/Client.ts +++ /dev/null @@ -1,149 +0,0 @@ -import Endpoints, { RequestType } from '../Constants/Endpoints' -import PaymentMethod from '../PaymentMethods/PaymentMethod' -import { ITransaction } from '../Models/ITransaction' -import { IConfig, ICredentials } from '../Utils/Types' -import {DataRequestResponse} from '../Models/DataRequestResponse' -import axios, { AxiosInstance } from 'axios' -import { TransactionResponse } from '../Models/TransactionResponse' -import RequestHeaders from './Headers' -import HttpMethods from '../Constants/HttpMethods' -import httpMethods from '../Constants/HttpMethods' -import {Response} from "./Response"; - -export class Client { - private static _credentials: ICredentials - private static _config: IConfig - public axios: AxiosInstance = axios.create() - private headers: RequestHeaders = new RequestHeaders() - private constructor() {} - static initialize(credentials?: ICredentials, config?: IConfig) { - if (!credentials || !credentials.websiteKey || !credentials.secretKey) - throw new Error('Initialize Buckaroo Client with credentials!!') - - this._credentials = { - secretKey: credentials.secretKey, - websiteKey: credentials.websiteKey - } - - this._config = { - mode: config?.mode || 'test', - currency: config?.currency || 'EUR', - returnURL: config?.returnURL || '', - returnURLCancel: config?.returnURLCancel || '', - pushURL: config?.pushURL || '', - baseUrl: config?.baseUrl || '' - } - return new Client() - } - getCredentials = (): ICredentials => { - return Client._credentials - } - getConfig = (): IConfig => { - return Client._config - } - private getEndpoint(path: string) { - const baseUrl = this.getConfig().mode === 'live' ? Endpoints.LIVE : Endpoints.TEST - return baseUrl + path - } - - private getTransactionUrl(path: string = ''): string { - return this.getEndpoint('json/Transaction') + path - } - - private getDataRequestUrl(path: string = ''): string { - return this.getEndpoint('json/DataRequest') + path - } - - protected getSpecificationUrl( - paymentName: string, - serviceVersion: number, - type: RequestType = RequestType.Transaction - ) { - return type === RequestType.Transaction - ? this.getTransactionUrl( - `/Specification/${paymentName}?serviceVersion=${serviceVersion}` - ) - : this.getDataRequestUrl( - `/Specification/${paymentName}?serviceVersion=${serviceVersion}` - ) - } - call(config: { method: httpMethods; url: string; data?: object }) { - this.headers.setAuthHeader(config.method, config.url, config.data) - - return this.axios.request({ ...config, headers: this.headers.headers }) - } - post(url: string, data: object) { - return this.call({ - method: HttpMethods.POST, - url, - data: data - }) - } - get(url: string) { - return this.call({ - method: HttpMethods.GET, - url - }) - } - - transactionRequest(data: ITransaction) { - data.pushURL = data.pushURL || this.getConfig().pushURL - - return this.post(this.getTransactionUrl(), data).then((res) => { - return new TransactionResponse(res) - }) - } - dataRequest(data: ITransaction) { - return this.post(this.getDataRequestUrl(), data).then((res) => { - return new DataRequestResponse(res) - }) - } - specification(paymentName: string, serviceVersion = 0, type?: RequestType) { - const url = this.getSpecificationUrl(paymentName, serviceVersion, type) - return this.get(url).then((res) => { - return new DataRequestResponse(res) - }) - } - specifications( - paymentMethods: PaymentMethod[] | { paymentName: string; serviceVersion: number }[], - type: RequestType = RequestType.Transaction - ) { - let data = { - Services: paymentMethods.map((paymentMethod) => { - return { - Name: paymentMethod.paymentName, - Version: paymentMethod.serviceVersion - } - }) - } - - const url = - type === RequestType.Transaction - ? this.getTransactionUrl('/Specifications') - : this.getDataRequestUrl('/Specifications') - - return this.call({ - method: HttpMethods.POST, - url, - data - }).then((response) => { - return new Response(response.data) - }) - } - status(transactionKey: string) { - const url = this.getTransactionUrl(`/Status/${transactionKey}`) - return this.get(url) - } - cancelInfo(transactionKey: string) { - const url = this.getTransactionUrl(`/Cancel/${transactionKey}`) - return this.get(url) - } - refundInfo(transactionKey: string) { - const url = this.getTransactionUrl(`/RefundInfo/${transactionKey}`) - return this.get(url) - } - invoiceInfo(invoiceKey: string) { - const url = this.getTransactionUrl(`/InvoiceInfo/${invoiceKey}`) - return this.get(url) - } -} diff --git a/src/Request/DataModels.ts b/src/Request/DataModels.ts new file mode 100644 index 00000000..81bb7d80 --- /dev/null +++ b/src/Request/DataModels.ts @@ -0,0 +1,147 @@ +import { IAdditionalParameters, IRequest, IService, Model, ServiceList } from '../Models'; +import { ClientIP } from '../Constants'; +import { DataFormatter, ServiceCode } from '../Utils'; + +export class TransactionData extends Model implements IRequest { + constructor(data?: IRequest) { + super(data); + } + + set clientUserAgent(value: string) { + this.set('clientUserAgent', value); + } + + set order(order: string) { + this.set('order', order); + } + + set invoice(invoice: string) { + this.set('invoice', invoice); + } + + set description(description: string) { + this.set('description', description); + } + + set amountCredit(amountCredit: number) { + this.set('amountCredit', amountCredit); + } + + set amountDebit(amountDebit: number) { + this.set('amountDebit', amountDebit); + } + + set currency(currency: string) { + this.set('currency', currency); + } + + set clientIP(ipAddress: string) { + this.set('clientIP', new ClientIP(ipAddress)); + } + + set additionalParameters(value: IAdditionalParameters) { + this.set('additionalParameters', { + AdditionalParameter: DataFormatter.parametersMap(value), + }); + } + + set customParameters(value: IAdditionalParameters) { + this.set('customParameters', { + List: DataFormatter.parametersMap(value), + }); + } + + set pushURL(pushURL: string) { + this.set('pushURL', pushURL); + } + + set continueOnIncomplete(value: boolean) { + this.set('continueOnIncomplete', value ? 1 : 0); + } + + set culture(value: string) { + this.set('culture', value); + } + + set originalTransactionKey(value: string) { + this.set('originalTransactionKey', value); + } + + set originalTransactionReference(value: { type: string; reference: string }) { + this.set('originalTransactionReference', value); + } + + set pushURLFailure(value: string) { + this.set('pushURLFailure', value); + } + + set returnURL(value: string) { + this.set('returnURL', value); + } + + set returnURLCancel(value: string) { + this.set('returnURLCancel', value); + } + + set returnURLError(value: string) { + this.set('returnURLError', value); + } + + set returnURLReject(value: string) { + this.set('returnURLReject', value); + } + + set servicesExcludedForClient(services: ServiceCode[] | string) { + this.set('servicesExcludedForClient', Array.isArray(services) ? services?.join(',') : services); + } + + get servicesSelectableByClient() { + return ''; + } + + set servicesSelectableByClient(services: ServiceCode[] | string) { + this.set('servicesSelectableByClient', Array.isArray(services) ? services?.join(',') : services); + } + + set startRecurrent(value: boolean) { + this.set('startRecurrent', value); + } + + getServiceList(): ServiceList | undefined { + return this.get('services'); + } + + setServiceList(services: ServiceList | undefined) { + return this.set('services', services); + } +} + +export class DataRequestData extends TransactionData { + set additionalParameters(parameters: IAdditionalParameters) { + this.set('additionalParameters', { + List: DataFormatter.parametersMap(parameters), + }); + } + + set services(data: IService[]) { + this.set('services', data); + } +} + +export class SpecificationRequestData extends Model { + constructor(data?: IService[]) { + super({ services: data }); + } + + set services(data: IService[]) { + this.set( + 'services', + data.map((service) => { + return { + Name: service.name, + Version: service.version, + }; + }) + ); + } +} diff --git a/src/Request/Headers.ts b/src/Request/Headers.ts index 981a1a9b..7d1c620e 100644 --- a/src/Request/Headers.ts +++ b/src/Request/Headers.ts @@ -1,25 +1,71 @@ -import { RawAxiosRequestHeaders } from 'axios' -import { Hmac } from './Hmac' -export default class RequestHeaders { - headers: RawAxiosRequestHeaders = {} - defaultHeaders(): RawAxiosRequestHeaders { - return { - 'Content-type': 'application/json', - Accept: 'application/json', - Culture: 'en-GB' - } +import { AxiosRequestConfig } from 'axios'; + +export type RequestHeaders = { + 'Content-Type'?: string; + Accept?: string; + Culture?: string; + Authorization?: string; + Software?: string; + [header: string]: any; +}; + +export interface RequestConfig extends AxiosRequestConfig { + headers?: RequestHeaders; +} + +export default class Headers { + private _headers: RequestHeaders = this.getDefaultHeaders(); + get headers(): RequestHeaders { + return this._headers; } - addHeaders(headers: RawAxiosRequestHeaders) { + + setSoftwareHeader( + value: { + platformName?: string; + platformVersion?: string; + moduleSupplier?: string; + moduleName?: string; + moduleVersion?: string; + } = {} + ): this { + this._headers.Software = JSON.stringify({ + PlatformName: value.platformName || 'Node SDK', + PlatformVersion: value.platformVersion || '1.0', + ModuleSupplier: value.moduleSupplier || 'Buckaroo', + ModuleName: value.moduleName || 'BuckarooPayments', + ModuleVersion: value.moduleVersion || '1.0', + }); + return this; + } + + setHeaders(headers: RequestHeaders) { Object.keys(headers).forEach((key) => { - this.headers[key] = headers[key] - }) + this._headers[key] = headers[key]; + }); + return this; } - removeHeaders(headers: RawAxiosRequestHeaders) { + + removeHeaders(headers: RequestHeaders) { Object.keys(headers).forEach((key) => { - delete this.headers[key] - }) + delete this._headers[key]; + }); + return this; } - setAuthHeader(method: string, url: string, data?: object) { - this.headers.Authorization = new Hmac(method, url, data).createHeader() + + protected getDefaultHeaders(): RequestHeaders { + return { + 'Content-type': 'application/json; charset=utf-8', + Accept: 'application/json', + Culture: 'nl-NL', + Authorization: '', + Channel: 'Web', + Software: JSON.stringify({ + PlatformName: 'Node SDK', + PlatformVersion: '1.0', + ModuleSupplier: 'Buckaroo', + ModuleName: 'BuckarooPayments', + ModuleVersion: '1.0', + }), + }; } } diff --git a/src/Request/Hmac.ts b/src/Request/Hmac.ts index 4e4c1abc..137be5d0 100644 --- a/src/Request/Hmac.ts +++ b/src/Request/Hmac.ts @@ -1,73 +1,100 @@ -import md5 from 'crypto-js/md5' -import hmacSHA256 from 'crypto-js/hmac-sha256' -import Base64 from 'crypto-js/enc-base64' -import buckarooClient from '../BuckarooClient' -import HttpMethods from '../Constants/HttpMethods' +import { ICredentials } from '../Utils'; +import md5 from 'crypto-js/md5'; +import hmacSHA256 from 'crypto-js/hmac-sha256'; +import Base64 from 'crypto-js/enc-base64'; +import crypto from 'crypto'; export class Hmac { - data: string | object - url: string - nonce: string - time: string - method: string - constructor( - method: HttpMethods | string, - url: string = '', - data: string | object = '', - nonce?: string, - time?: string - ) { - this.url = url - this.data = data - this.nonce = nonce || '' - this.method = method - this.time = time || '' + protected _data?: object; + protected _url?: URL; + protected _nonce?: string; + protected _time?: string; + protected _method?: string; + + get data(): string { + return this._data ? JSON.stringify(this._data) : ''; } - createHeader() { - this.nonce = 'nonce_' + Math.floor(Math.random() * 9999999 + 1) - this.time = String(Math.round(Date.now() / 1000)) - return this.getHeader() + + set data(data: string) { + try { + let jsonData = JSON.parse(data); + if (Object.keys(jsonData).length > 0) { + this._data = jsonData; + } + } catch (e) {} } - getUrlFormat() { - let urlFormatted: URL | string = new URL(this.url) - if (this.url) { - urlFormatted = urlFormatted.host + urlFormatted.pathname + urlFormatted.search - urlFormatted = this.url.replace(/^[^:/.]*[:/]+/i, '') - urlFormatted = encodeURIComponent(urlFormatted).toLowerCase() || '' - } - return urlFormatted + + get url(): string | undefined { + return this._url + ? encodeURIComponent( + this._url.href + .replace(this._url.protocol, '') + .replace(/^[^:/.]*[:/]+/i, '') + .replace(/(^\w+:|^)\/\//, '') + ).toLowerCase() + : undefined; } - getBase64Data() { - let base64Data = this.data - if (this.data) { - if (typeof base64Data === 'object') { - base64Data = JSON.stringify(base64Data) - } - base64Data = Base64.stringify(md5(base64Data)) + + set url(url: string | undefined) { + if (url) this._url = new URL(url); + } + + get nonce(): string { + return this._nonce || 'nonce_' + Math.floor(Math.random() * 9999999 + 1); + } + + set nonce(nonce: string) { + this._nonce = nonce; + } + + get time(): string { + return this._time || String(Math.round(Date.now() / 1000)); + } + + set time(time: string) { + this._time = time; + } + + get method(): string { + return this._method || 'POST'; + } + + set method(method: string) { + this._method = method; + } + + get base64Data() { + if (this._data) { + return Base64.stringify(md5(this.data)); } - return base64Data + return ''; + } + + generate(credentials: ICredentials, nonce?: string, time?: string): string { + this._nonce = nonce || this.nonce; + this._time = time || this.time; + let hashString = this.getHashString(credentials.websiteKey); + let hashData = this.hashData(hashString, credentials.secretKey); + return `hmac ${credentials.websiteKey}:${hashData}:${this._nonce}:${this._time}`; } - hashData(hashString: string) { - return Base64.stringify(hmacSHA256(hashString, buckarooClient().getCredentials().secretKey)) + + validate(credentials: ICredentials, authHeader: string, url: string, data: string, method: string): boolean { + let header = authHeader.split(':'); + let providedHash = header[1]; + this.nonce = header[2]; + this.time = header[3]; + this.method = method; + this.url = url; + this.data = data; + let hash = this.hashData(this.getHashString(credentials.websiteKey), credentials.secretKey); + return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(providedHash)); } - getHashString() { - return ( - buckarooClient().getCredentials().websiteKey + - this.method + - this.getUrlFormat() + - this.time + - this.nonce + - this.getBase64Data() - ) + + protected getHashString(websiteKey: string) { + return websiteKey + this.method + this.url + this.time + this.nonce + this.base64Data; } - getHeader() { - let hashString = this.getHashString() - - return ( - `hmac ` + - `${buckarooClient().getCredentials().websiteKey}:${this.hashData(hashString)}:${ - this.nonce - }:${this.time}` - ) + + protected hashData(hashString: string, secretKey: string) { + return hmacSHA256(hashString, secretKey).toString(Base64); } } diff --git a/src/Request/HttpsClient.ts b/src/Request/HttpsClient.ts new file mode 100644 index 00000000..0a3ad18b --- /dev/null +++ b/src/Request/HttpsClient.ts @@ -0,0 +1,50 @@ +import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; +import { HttpResponseConstructor } from '../Models'; +import { RequestConfig } from './Headers'; +import { HttpMethods } from '../Constants'; +import { Agent } from 'https'; + +export default class HttpsClient { + protected _options: AxiosRequestConfig = {}; + private _axiosInstance: AxiosInstance; + + constructor(agent?: Agent) { + this._options.timeout = 10000; + this._options.maxRedirects = 10; + this._options.withCredentials = true; + + if (agent) { + this._options.httpsAgent = agent; + } + + this._axiosInstance = axios.create(this._options); + } + + public async sendRequest( + url: URL, + data: object, + options: RequestConfig, + responseClass: R + ): Promise> { + try { + const config = { + url: url.toString(), + ...this._options, + ...options, + }; + + if (options.method !== HttpMethods.GET) { + config.data = data; + } + + const response = await this._axiosInstance.request(config); + + return new responseClass(response, response.data) as InstanceType; + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + throw error.response?.data ?? error; + } + throw error; + } + } +} diff --git a/src/Request/Request.ts b/src/Request/Request.ts new file mode 100644 index 00000000..a16b2336 --- /dev/null +++ b/src/Request/Request.ts @@ -0,0 +1,121 @@ +import Headers, { RequestConfig } from './Headers'; +import { + BatchRequestResponse, + HttpClientResponse, + HttpResponseConstructor, + IRequest, + IService, + SpecificationRequestResponse, + TransactionResponse, +} from '../Models'; +import { DataRequestData, SpecificationRequestData, TransactionData } from './DataModels'; +import Buckaroo from '../index'; +import { Endpoints, HttpMethods, RequestTypes } from '../Constants'; +import { ICredentials } from '../Utils'; +import { Hmac } from './Hmac'; + +export default class Request< + HttpResponse extends HttpResponseConstructor = HttpResponseConstructor, + RequestData extends object | undefined = undefined +> extends Headers { + protected _path?: string; + protected _data?: object | object[] | undefined; + protected _httpMethod: HttpMethods; + protected _responseHandler?: HttpResponseConstructor; + + constructor(path?: string, method?: HttpMethods, data?: RequestData, responseHandler?: HttpResponse) { + super(); + this._path = path; + this._data = data; + this._httpMethod = method || HttpMethods.GET; + this._responseHandler = responseHandler; + } + + get data(): RequestData { + return this._data as any; + } + + get httpMethod(): HttpMethods { + return this._httpMethod; + } + + get url(): URL { + return new URL(Endpoints[Buckaroo.Client.config.mode] + (this._path || '')); + } + + protected get responseHandler(): HttpResponse { + return (this._responseHandler || HttpClientResponse) as HttpResponse; + } + + static Transaction(payload?: IRequest) { + return new Request( + RequestTypes.Transaction, + HttpMethods.POST, + new TransactionData(payload), + TransactionResponse + ); + } + + static DataRequest(payload?: IRequest) { + return new Request(RequestTypes.Data, HttpMethods.POST, new DataRequestData(payload), TransactionResponse); + } + + static Specification( + type: RequestTypes.Data | RequestTypes.Transaction, + data: T + ): T extends IService[] + ? Request + : Request { + if (Array.isArray(data)) { + return new Request( + type + `/Specifications`, + HttpMethods.POST, + new SpecificationRequestData(data), + SpecificationRequestResponse + ) as any; + } + return new Request( + type + `/Specification/${data?.name}?serviceVersion=${data?.version}`, + HttpMethods.GET, + undefined, + SpecificationRequestResponse + ) as any; + } + + static BatchTransaction(payload: IRequest[] = []) { + return new Request( + RequestTypes.BatchTransaction, + HttpMethods.POST, + payload.map((data) => new TransactionData(data)), + BatchRequestResponse + ); + } + + static BatchDataRequest(data: DataRequestData[] = []) { + return new Request(RequestTypes.BatchData, HttpMethods.POST, data, BatchRequestResponse); + } + + request(options: RequestConfig = {}) { + let data = (this._httpMethod === HttpMethods.GET ? {} : this._data) ?? {}; + this.setAuthorizationHeader(data); + return Buckaroo.Client.httpClient.sendRequest( + this.url, + data, + { + method: this._httpMethod, + headers: this.headers, + ...options, + }, + this.responseHandler + ); + } + + protected setAuthorizationHeader(data?: object, credentials: ICredentials = Buckaroo.Client.credentials): this { + let hmac = new Hmac(); + hmac.data = JSON.stringify(data); + hmac.method = this.httpMethod; + hmac.url = this.url.toString(); + this.headers.Authorization = hmac.generate(credentials); + return this; + } +} diff --git a/src/Request/Response.ts b/src/Request/Response.ts deleted file mode 100644 index 1a41c28c..00000000 --- a/src/Request/Response.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { - AxiosResponse, -} from 'axios' - -export class Response { - - protected readonly _data: any - protected readonly _axiosResponse: AxiosResponse - get data(): any { - return this._data - } - get axiosResponse(): AxiosResponse { - return this._axiosResponse - } - constructor(response: AxiosResponse) { - this._axiosResponse = response - this._data = response.data - } -} diff --git a/src/Request/index.ts b/src/Request/index.ts new file mode 100644 index 00000000..9dd74a9b --- /dev/null +++ b/src/Request/index.ts @@ -0,0 +1,7 @@ +import Headers, { RequestConfig, RequestHeaders } from './Headers'; + +export * from './DataModels'; +export * from './Hmac'; +export { default as HttpsClient } from './HttpsClient'; +export { default as Request } from './Request'; +export { Headers, RequestHeaders, RequestConfig }; \ No newline at end of file diff --git a/src/Services/PayablePaymentMethod.ts b/src/Services/PayablePaymentMethod.ts new file mode 100644 index 00000000..fe1ebd1d --- /dev/null +++ b/src/Services/PayablePaymentMethod.ts @@ -0,0 +1,31 @@ +import PaymentMethod from './PaymentMethod'; +import { IParameter, IPaymentRequest, IRefundRequest, IRequest, ServiceParameter } from '../Models'; +import { uniqid } from '../Utils'; + +export default abstract class PayablePaymentMethod extends PaymentMethod { + protected _requiredFields: Array = ['currency', 'returnURL', 'returnURLCancel', 'pushURL']; + + pay(payload: IPaymentRequest, serviceParameters?: ServiceParameter | IParameter[]) { + this.setPayPayload(payload); + this.setServiceList('Pay', serviceParameters); + return this.transactionRequest(); + } + + payRemainder(payload: IPaymentRequest, serviceParameters?: ServiceParameter | IParameter[]) { + this.setPayPayload(payload); + this.setServiceList('PayRemainder', serviceParameters); + return this.transactionRequest(); + } + + refund(payload: IRefundRequest, serviceParameters?: ServiceParameter | IParameter[]) { + this.setPayload(payload); + this.setServiceList('Refund', serviceParameters); + return this.transactionRequest(); + } + + protected setPayPayload(payload: IRequest) { + payload.invoice = payload.invoice ?? uniqid(); + payload.order = payload.order ?? uniqid(); + super.setPayload(payload); + } +} diff --git a/src/Services/PaymentMethod.ts b/src/Services/PaymentMethod.ts new file mode 100644 index 00000000..bab92b8c --- /dev/null +++ b/src/Services/PaymentMethod.ts @@ -0,0 +1,113 @@ +import { RequestTypes } from '../Constants'; +import { IParameter, IRequest, IService, ServiceList, ServiceParameter } from '../Models'; +import Buckaroo, { PaymentMethodInstance } from '../index'; +import { Request, TransactionData } from '../Request'; +import { ServiceCode } from '../Utils'; + +export default abstract class PaymentMethod { + protected _serviceCode?: ServiceCode; + protected _serviceVersion: number = 0; + protected _payload: TransactionData = new TransactionData(); + protected _requiredFields: Array = []; + + constructor(serviceCode?: ServiceCode) { + this.setServiceCode((serviceCode ?? this._serviceCode) as ServiceCode); + } + + get serviceVersion() { + return this._serviceVersion; + } + + set serviceVersion(value: number) { + this._serviceVersion = value; + } + + get serviceCode(): ServiceCode { + return this._serviceCode ?? 'noservice'; + } + + public abstract defaultServiceCode(): ServiceCode; + + setServiceCode(value: ServiceCode): this { + this._serviceCode = value; + return this; + } + + setPayload(payload?: IRequest) { + this.setRequiredFields(); + this._payload.initialize(payload); + } + + getPayload(): Record { + return this._payload.getData(); + } + + getServiceList() { + return this._payload.getServiceList(); + } + + combine(data: Name): PaymentMethodInstance; + + combine(data: Payload): this; + + combine(method: Method): this; + + combine(data: any): this { + if (typeof data === 'string') { + const method: PaymentMethod = Buckaroo.Client.method(data as any); + method.setPayload(this._payload); + return method as any; + } + this.setPayload(data instanceof PaymentMethod ? data.getPayload() : data); + return this; + } + + public specification( + type: RequestTypes.Transaction | RequestTypes.Data = RequestTypes.Data, + serviceVersion: number = this.serviceVersion + ) { + return Request.Specification(type, { name: this.serviceCode, version: serviceVersion }); + } + + protected setRequiredFields(requiredFields: Array = this._requiredFields) { + for (const fieldKey of requiredFields) { + let field = this._payload[fieldKey] ?? (Buckaroo.Client.config as IRequest)[fieldKey]; + if (field === undefined) { + throw new Error(`Missing required config parameter ${String(fieldKey)}`); + } + this._payload[fieldKey] = field; + } + return this; + } + + protected setServiceList( + action: string, + serviceParameters?: IParameter[] | ServiceParameter, + serviceCode = this.serviceCode, + serviceVersion = this.serviceVersion + ) { + const service: IService = { + name: serviceCode, + action: action, + version: serviceVersion, + parameters: + serviceParameters instanceof ServiceParameter ? serviceParameters.toParameterList() : serviceParameters, + }; + if (this.getServiceList() instanceof ServiceList) { + this.getServiceList()!.addService(service); + } else { + this._payload.setServiceList(new ServiceList(service)); + } + return this; + } + + protected transactionRequest(payload?: IRequest) { + this.setPayload(payload); + return Request.Transaction(this._payload); + } + + protected dataRequest(payload?: IRequest) { + this.setPayload(payload); + return Request.DataRequest(this._payload); + } +} \ No newline at end of file diff --git a/src/Services/TransactionService.ts b/src/Services/TransactionService.ts new file mode 100644 index 00000000..595b75e6 --- /dev/null +++ b/src/Services/TransactionService.ts @@ -0,0 +1,28 @@ +import { Request } from '../Request'; +import { HttpMethods, RequestTypes } from '../Constants'; +import { TransactionResponse } from '../Models'; + +export default class TransactionService { + private readonly _key: string; + + constructor(key: string) { + this._key = key; + } + + status() { + return new Request( + `${RequestTypes.Transaction}/Status/${this._key}`, + HttpMethods.GET, + undefined, + TransactionResponse + ).request(); + } + + refundInfo() { + return new Request(`${RequestTypes.Transaction}/RefundInfo/${this._key}`, HttpMethods.GET).request(); + } + + cancelInfo() { + return new Request(`${RequestTypes.Transaction}/Cancel/${this._key}`, HttpMethods.GET).request(); + } +} diff --git a/src/Services/index.ts b/src/Services/index.ts new file mode 100644 index 00000000..283136e5 --- /dev/null +++ b/src/Services/index.ts @@ -0,0 +1,4 @@ +export * from './PayablePaymentMethod'; +export { default as PaymentMethod } from './PaymentMethod'; +export { default as PayablePaymentMethod } from './PayablePaymentMethod'; +export { default as TransactionService } from './TransactionService'; \ No newline at end of file diff --git a/src/Utils/Functions.ts b/src/Utils/Functions.ts index 48924654..d5bc2fbf 100644 --- a/src/Utils/Functions.ts +++ b/src/Utils/Functions.ts @@ -1,13 +1,106 @@ +import os from 'os'; +import { + IAdditionalParameters, + IFormattedParameter, + IParameter, + IServiceParameters, + ServiceParameterTypes, +} from '../Models'; + export function uniqid(prefix: string = '', random: boolean = false) { - const sec = Date.now() * 1000 + Math.random() * 1000 - const id = sec.toString(16).replace(/\./g, '').padEnd(14, '0') - return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}` : ''}` + const sec = Date.now() * 1000 + Math.random() * 1000; + const id = sec.toString(16).replace(/\./g, '').padEnd(14, '0'); + return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}` : ''}`; } -export function firstUpperCase(propertyName: string) { - return propertyName.charAt(0).toUpperCase() + propertyName.slice(1) +export class Str { + public static ucfirst(value: string): string { + return value.charAt(0).toUpperCase() + value.slice(1); + } + + public static lcfirst(value: string): string { + return value.charAt(0).toLowerCase() + value.slice(1); + } + + public static ciEquals(a: string, b: string) { + return a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0; + } + + private static replace(search: string[], replace: string, subject: string): string { + let result: string = subject; + for (let value of search) { + result = result.split(value).join(replace); + } + return result; + } } -export function firstLowerCase(propertyName: string) { - return propertyName.charAt(0).toLowerCase() + propertyName.slice(1) +export abstract class DataFormatter { + static parametersMap(parameters: IAdditionalParameters, index1 = 'Name', index2 = 'Value'): IFormattedParameter[] { + return Object.keys(parameters).map((key) => { + return { + [index1]: Str.ucfirst(key), + [index2]: parameters[key], + }; + }) as any; + } + + static serviceParametersMap( + parameters: IServiceParameters | ServiceParameterTypes | undefined, + groups: { [key: string]: string } = {}, + countable: string[] = [], + parameter: IParameter = { name: '', value: '' }, + parametersArray: IParameter[] = [] + ): IParameter[] { + if (groups[parameter.name]) { + parameter.groupType = Str.ucfirst(groups[parameter.name]); + } + if (parameters instanceof Array) { + parameters.forEach((element) => { + if (countable.includes(parameter.name)) { + parameter.groupID = (parameter.groupID || 0) + 1; + } + this.serviceParametersMap(element, groups, countable, { ...parameter }, parametersArray); + }); + } else if (typeof parameters === 'object') { + for (const key of Object.keys(parameters)) { + this.serviceParametersMap( + parameters[key], + groups, + countable, + { ...parameter, name: key }, + parametersArray + ); + } + } else if (parameters !== undefined) { + parametersArray.push({ ...parameter, value: parameters }); + } + return parametersArray; + } + + static parametersReverseMap(parameter: IFormattedParameter[] = []): IAdditionalParameters { + return parameter.reduce((total, currentValue) => { + return { ...total, [Str.lcfirst(currentValue.name)]: currentValue.value }; + }, {}); + } } + +export const getIPAddress = (): string => { + const interfaces = os.networkInterfaces(); + + for (const devName in interfaces) { + const iface = interfaces[devName]; + + if (!iface) { + continue; + } + + for (const alias of iface) { + if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { + return alias.address; + } + } + } + + return '0.0.0.0'; +}; diff --git a/src/Utils/MethodTypes.ts b/src/Utils/MethodTypes.ts new file mode 100644 index 00000000..ba3699de --- /dev/null +++ b/src/Utils/MethodTypes.ts @@ -0,0 +1,14 @@ +import * as AllPaymentMethods from '../PaymentMethods'; + +export type AvailablePaymentMethods = typeof AllPaymentMethods; +export type ServiceCode = keyof AvailablePaymentMethods; +export type PaymentMethodInstance = InstanceType; + +export function getMethod(code: Code): PaymentMethodInstance { + const methodClass = AllPaymentMethods[code]; + if (!methodClass) { + throw new Error(`Invalid payment method code: ${code}`); + } + + return new methodClass(code as any) as PaymentMethodInstance; +} diff --git a/src/Utils/Types.ts b/src/Utils/Types.ts index 91b12c01..a40e3d88 100644 --- a/src/Utils/Types.ts +++ b/src/Utils/Types.ts @@ -1,26 +1,21 @@ +import { ServiceCode } from './MethodTypes'; + export declare interface IConfig { - mode: 'live' | 'test' - currency: string - returnURL: string - returnURLCancel: string - pushURL: string - baseUrl: string + mode: Mode; + currency: string; + continueOnIncomplete?: 0 | 1; + returnURL?: string; + returnURLCancel?: string; + pushURL?: string; + returnURLError?: string; + returnURLReject?: string; + activePaymentMethods?: ServiceCode[]; + disabledPaymentMethods?: ServiceCode[]; } export declare interface ICredentials { - websiteKey: string - secretKey: string -} - -export type IPAddress = { - address: string - type: number + websiteKey: string; + secretKey: string; } -export type ParameterTypes = string | number | boolean | undefined -export declare type AdditionalParameter = { - [name: string]: ParameterTypes -} -export declare interface ServiceParameters { - [name: string]: ParameterTypes | ParameterTypes[] | ServiceParameters | ServiceParameters[] -} +export type Mode = 'LIVE' | 'TEST'; diff --git a/src/Utils/index.ts b/src/Utils/index.ts new file mode 100644 index 00000000..6ff6c310 --- /dev/null +++ b/src/Utils/index.ts @@ -0,0 +1,3 @@ +export * from './MethodTypes'; +export * from './Types'; +export * from './Functions'; \ No newline at end of file diff --git a/src/buckaroo.ts b/src/buckaroo.ts new file mode 100644 index 00000000..fd92bc90 --- /dev/null +++ b/src/buckaroo.ts @@ -0,0 +1,69 @@ +import { getMethod, IConfig, ICredentials, PaymentMethodInstance, ServiceCode } from './Utils'; +import { HttpsClient, Request } from './Request'; +import { Agent } from 'https'; +import NoService from './PaymentMethods/NoService'; +import { TransactionService } from './Services'; +import { Credentials } from './Handlers'; + +export default class Buckaroo { + private static _client: Buckaroo; + private readonly _credentials: Credentials; + private readonly _httpClient: HttpsClient; + private _config: IConfig; + + constructor(credentials: ICredentials, config?: IConfig, agent?: Agent) { + this._credentials = new Credentials(credentials.secretKey, credentials.websiteKey); + this._config = { ...(config ?? { mode: 'TEST', currency: 'EUR' }) }; + this._httpClient = new HttpsClient(agent); + } + + static get Client(): Buckaroo { + return this._client; + } + + get config(): IConfig { + return { ...this._config }; + } + + set config(value: IConfig) { + this._config = value; + } + + get credentials(): ICredentials { + return this._credentials; + } + + get httpClient() { + return this._httpClient; + } + + get batch() { + return { + transaction: Request.BatchTransaction, + data: Request.BatchDataRequest, + }; + } + + static InitializeClient(credentials: ICredentials, config?: IConfig, agent?: Agent): Buckaroo { + return (this._client = new this(credentials, config, agent)); + } + + method(): NoService; + method(name: Name): PaymentMethodInstance; + method(name?: K) { + if (!name) { + return new NoService(); + } + return getMethod(name); + } + + confirmCredentials() { + return this._credentials.confirm(); + } + + transaction(key: string) { + return new TransactionService(key); + } +} + +export { Buckaroo }; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 00000000..1708bd9c --- /dev/null +++ b/src/index.ts @@ -0,0 +1,12 @@ +import Buckaroo from './buckaroo'; + +export * from './Constants'; +export * from './Handlers'; +export * from './Models'; +export * from './PaymentMethods'; +export * from './Request'; +export * from './Services'; +export * from './Utils'; + +export default Buckaroo; +export { Buckaroo }; \ No newline at end of file diff --git a/tests/BuckarooClient.test.js b/tests/BuckarooClient.test.js new file mode 100644 index 00000000..0c11eb77 --- /dev/null +++ b/tests/BuckarooClient.test.js @@ -0,0 +1,13 @@ +import Buckaroo from '../src'; +require('dotenv').config(); +const BuckarooClient = Buckaroo.InitializeClient({ + secretKey: process.env.BPE_SECRET_KEY || '', + websiteKey: process.env.BPE_WEBSITE_KEY || '' +}, { + mode: process.env.BPE_MODE === 'LIVE' ? 'LIVE' : 'TEST', + currency: process.env.BPE_CURRENCY_CODE || 'EUR', + returnURL: process.env.BPE_RETURN_URL || '', + returnURLCancel: process.env.BPE_RETURN_URL_CANCEL || '', + pushURL: process.env.BPE_PUSH_URL || '' +}); +export default BuckarooClient; diff --git a/tests/BuckarooClient.test.ts b/tests/BuckarooClient.test.ts index fed52b0b..f69f792e 100644 --- a/tests/BuckarooClient.test.ts +++ b/tests/BuckarooClient.test.ts @@ -1,16 +1,18 @@ -import { initializeBuckarooClient } from '../src/BuckarooClient' -require('dotenv').config() -export default initializeBuckarooClient( +import Buckaroo from '../src'; + +require('dotenv').config(); + +const BuckarooClient = Buckaroo.InitializeClient( { secretKey: process.env.BPE_SECRET_KEY || '', - websiteKey: process.env.BPE_WEBSITE_KEY || '' + websiteKey: process.env.BPE_WEBSITE_KEY || '', }, { - mode: process.env.BPE_MODE === 'live' ? 'live' : 'test', + mode: process.env.BPE_MODE === 'LIVE' ? 'LIVE' : 'TEST', currency: process.env.BPE_CURRENCY_CODE || 'EUR', returnURL: process.env.BPE_RETURN_URL || '', returnURLCancel: process.env.BPE_RETURN_URL_CANCEL || '', pushURL: process.env.BPE_PUSH_URL || '', - baseUrl: process.env.BPE_BASE_URL || '' } -) +); +export default BuckarooClient; diff --git a/tests/Client.test.js b/tests/Client.test.js new file mode 100644 index 00000000..fe724816 --- /dev/null +++ b/tests/Client.test.js @@ -0,0 +1,72 @@ +import client from './BuckarooClient.test'; +import { TransactionResponse } from '../src/Models/Response/TransactionResponse'; +import { HttpClientResponse } from '../src/Models/Response/HttpClientResponse'; +import { uniqid } from '../src/Utils/Functions'; +import { creditManagementTestInvoice } from "./PaymentMethods/CreditManagment.test"; +describe('Testing Buckaroo Client', () => { + test('Credentials', () => { + return client + .confirmCredentials() + .then((response) => { + expect(response).toBeTruthy(); + }); + }); + test('Batch transaction', async () => { + const transactionData = []; + for (let i = 0; i < 3; i++) { + let invoice = client + .method('CreditManagement3') + .createCombinedInvoice(creditManagementTestInvoice()) + .combine('sepadirectdebit') + .pay({ + invoice: uniqid(), + amountDebit: 10.1, + iban: 'NL13TEST0123456789', + bic: 'TESTNL2A', + collectdate: '2024-07-03', + mandateReference: '1DCtestreference', + mandateDate: '2022-07-03', + customer: { + name: 'John Smith' + } + }); + transactionData.push(invoice.data); + } + await client + .batch(transactionData) + .request() + .then((response) => { + expect(response).toBeTruthy(); + }) + .catch((err) => { + expect(err).toBeUndefined(); + }); + }); + describe('Transaction', () => { + const transactionService = client.transaction('39F3EC520A3F4A25B0A1899D4FF0E1CB'); + test('transaction Status', async () => { + await transactionService + .status() + .then((res) => { + expect(res instanceof TransactionResponse).toBeTruthy(); + }) + .catch((err) => { + expect(err).toBeUndefined(); + }); + }); + test('transaction Cancel Info', async () => { + await transactionService + .cancelInfo() + .then((res) => { + expect(res instanceof HttpClientResponse).toBeTruthy(); + }); + }); + test('transaction Refund Info', async () => { + await transactionService + .refundInfo() + .then((res) => { + expect(res instanceof HttpClientResponse).toBeTruthy(); + }); + }); + }); +}); diff --git a/tests/Client.test.ts b/tests/Client.test.ts new file mode 100644 index 00000000..d4880e4e --- /dev/null +++ b/tests/Client.test.ts @@ -0,0 +1,68 @@ +import client from './BuckarooClient.test'; +import { HttpClientResponse, IRequest, TransactionResponse, uniqid } from '../src'; +import { creditManagementTestInvoice } from './PaymentMethods/CreditManagment.test'; + +describe('Testing Buckaroo Client', () => { + test('Credentials', () => { + return client.confirmCredentials().then((response) => { + expect(response).toBeTruthy(); + }); + }); + test('Batch transaction', async () => { + const transactionData: IRequest[] = []; + const creditManagement = client.method('CreditManagement3'); + const sepaDirectDebit = client.method('sepadirectdebit'); + for (let i = 0; i < 3; i++) { + const combinedInvoice = creditManagement.createCombinedInvoice(creditManagementTestInvoice()); + + const sepaRequest = sepaDirectDebit.combine(combinedInvoice.data).pay({ + iban: 'NL39RABO0300065264', + bic: 'RABONL2U', + mandateReference: '1DCtestreference', + mandateDate: '2022-07-03', + collectDate: '2020-07-03', + amountDebit: 10.1, + customer: { + name: 'John Smith', + }, + invoice: uniqid('TestInvoice'), + }); + + transactionData.push(sepaRequest.data); + } + + await client.batch + .transaction(transactionData) + .request() + .then((response) => { + expect(response.data.message === '3 transactions were queued for processing.').toBeTruthy(); + }) + .catch((err) => { + expect(err).toBeUndefined(); + }); + }); + describe('Transaction', () => { + const transactionService = client.transaction('39F3EC520A3F4A25B0A1899D4FF0E1CB'); + test('transaction Status', async () => { + await transactionService + .status() + .then((res) => { + expect(res instanceof TransactionResponse).toBeTruthy(); + }) + .catch((err) => { + expect(err).toBeUndefined(); + }); + }); + test('transaction Cancel Info', async () => { + await transactionService.cancelInfo().then((res) => { + expect(res instanceof HttpClientResponse).toBeTruthy(); + }); + }); + + test('transaction Refund Info', async () => { + await transactionService.refundInfo().then((res) => { + expect(res instanceof HttpClientResponse).toBeTruthy(); + }); + }); + }); +}); diff --git a/tests/Models/index.js b/tests/Models/index.js new file mode 100644 index 00000000..b8a9fbe0 --- /dev/null +++ b/tests/Models/index.js @@ -0,0 +1,60 @@ +import RecipientCategory from '../../src/Constants/RecipientCategory'; +import { getIPAddress } from '../../src/Utils/Functions'; +export const TestPerson = { + birthDate: '1990-01-01', + category: RecipientCategory.PERSON, + culture: '321', + firstName: 'John', + gender: 'male', + initials: 'R.T', + lastName: 'Do', + lastNamePrefix: 'testlastprefix', + placeOfBirth: 't', + title: 'title' +}; +export const TestCompany = { + category: RecipientCategory.COMPANY, + careOf: 'test', + chamberOfCommerce: 'test', + companyName: 'testCompany', + culture: 'culture', + vatApplicable: false, + vatNumber: '321' +}; +export const TestAddress = { + city: 'city', + country: 'NL', + houseNumber: '2313432', + houseNumberAdditional: '324', + state: 'state', + street: 'street', + zipcode: '32323' +}; +export const TestArticle = { + description: 'test', + identifier: 'identifier', + price: 10, + quantity: 2, + type: 'PhysicalArticle', + unitCode: '23', + vatCategory: '323', + vatPercentage: 1 +}; +export const TestPhone = { + fax: '23232', + landline: '323123', + mobile: '21312332' +}; +export const TestEmail = 'test@hotmail.com'; +export const TestBankAccount = { + accountName: 'accountName', + bic: 'bic', + iban: 'iban' +}; +export const TestBilling = { + recipient: TestPerson, + address: TestAddress, + phone: TestPhone, + email: TestEmail +}; +export const TestIp = getIPAddress(); diff --git a/tests/Models/index.ts b/tests/Models/index.ts new file mode 100644 index 00000000..bca7510f --- /dev/null +++ b/tests/Models/index.ts @@ -0,0 +1,83 @@ +import { + Gender, + getIPAddress, + IAddress, + IArticle, + IBankAccount, + ICompany, + IPerson, + IPhone, + RecipientCategory, + uniqid, +} from '../../src'; + +export const TestPerson: IPerson = { + birthDate: '1990-01-01', + category: RecipientCategory.PERSON, + culture: '321', + firstName: 'John', + gender: 'male', + initials: 'R.T', + lastName: 'Do', + lastNamePrefix: 'testlastprefix', + placeOfBirth: 't', + title: 'title', +}; +export const TestCompany: ICompany = { + category: RecipientCategory.COMPANY, + careOf: 'test', + chamberOfCommerce: 'test', + companyName: 'testCompany', + culture: 'culture', + vatApplicable: false, + vatNumber: '321', +}; +export const TestAddress: IAddress = { + city: 'city', + country: 'NL', + houseNumber: '2313432', + houseNumberAdditional: '324', + state: 'state', + street: 'street', + zipcode: '32323', +}; +export const TestArticle: IArticle = { + description: 'test', + identifier: 'identifier', + price: 10, + quantity: 2, + type: 'PhysicalArticle', + unitCode: '23', + vatCategory: '323', + vatPercentage: 1, +}; + +export const TestPhone: IPhone = { + fax: '23232', + landline: '323123', + mobile: '21312332', +}; +export const TestEmail = 'test@hotmail.com'; +export const TestBankAccount: IBankAccount = { + accountName: 'accountName', + bic: 'bic', + iban: 'iban', +}; +export const TestBilling = { + recipient: TestPerson, + address: TestAddress, + phone: TestPhone, + email: TestEmail, +}; + +export const TestCustomer = { + identificationNumber: uniqid(), + gender: Gender.FEMALE, + culture: TestPerson.culture, + initials: TestPerson.initials, + lastName: TestPerson.lastName, + firstName: TestPerson.firstName, + birthDate: '1990-01-01', +}; + +export const TestIp = getIPAddress(); diff --git a/tests/PaymentMethods/AfterPay.test.js b/tests/PaymentMethods/AfterPay.test.js new file mode 100644 index 00000000..5e1780c9 --- /dev/null +++ b/tests/PaymentMethods/AfterPay.test.js @@ -0,0 +1,122 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { RequestTypes } from '../../src/Constants/Endpoints'; +import RecipientCategory from '../../src/Constants/RecipientCategory'; +const method = buckarooClientTest.method('afterpay'); +describe('AfterPay methods', () => { + test('Pay', () => { + return method + .pay(paymentPayload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + invoice: 'testinvoice 123', + originalTransactionKey: '4E8BD922192746C3918BF4077CXXXXXX', + amountCredit: 1.23 + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Authorize', async () => { + await method + .authorize(paymentPayload) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('CancelAuthorize', async () => { + await method + .cancelAuthorize({ + invoice: 'testinvoice 123', + originalTransactionKey: '4E8BD922192746C3918BF4077CXXXXXX', + amountCredit: 1.23 + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Capture', async () => { + await method + .capture({ + ...paymentPayload, + originalTransactionKey: '123456789' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('PayRemainder', async () => { + await method + .payRemainder({}) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('AuthorizeRemainder', async () => { + await method + .authorizeRemainder({}) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Spercifications', async () => { + return method + .specification(RequestTypes.Transaction) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); +const paymentPayload = { + clientIP: '127.0.0.1', + amountDebit: 40, + billing: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'John Smith', + firstName: 'John', + lastName: 'Do', + birthDate: '1990-01-01', + companyName: 'buckarooTest', + conversationLanguage: 'NL', + identificationNumber: 'IdNumber12345', + customerNumber: 'customerNumber12345' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '13', + houseNumberAdditional: 'a', + zipcode: '1234AB', + city: 'Heerenveen', + country: 'NL' + }, + email: 'test@buckaroo.nl', + phone: { + mobile: '0612345678', + landline: '0513123456' + } + }, + articles: [ + { + vatPercentage: 21, + price: 10, + description: 'Test', + quantity: 4, + identifier: 'test' + } + ], + description: 'Test', + merchantImageUrl: 'https://www.buckaroo.nl/Themes/Buckaroo/Content/images/logo.png' +}; diff --git a/tests/PaymentMethods/AfterPay.test.ts b/tests/PaymentMethods/AfterPay.test.ts index 3e24a537..fc826fe8 100644 --- a/tests/PaymentMethods/AfterPay.test.ts +++ b/tests/PaymentMethods/AfterPay.test.ts @@ -1,126 +1,94 @@ -import Afterpay from '../../src/PaymentMethods/Afterpay/index' -import { IPay } from '../../src/PaymentMethods/Afterpay/Model/Pay' -import { RefundPayload } from '../../src/Models/ITransaction' -import RecipientCategory from '../../src/Constants/RecipientCategory' -require('../BuckarooClient.test') +import buckarooClientTest from '../BuckarooClient.test'; +import { IPay } from '../../src/PaymentMethods/Afterpay/Model/Pay'; +import { getIPAddress, RecipientCategory, uniqid } from '../../src'; -const method = new Afterpay() -describe('AfterPay methods', () => { +const paymentPayload: IPay = { + invoice: uniqid(), + clientIP: getIPAddress(), + amountDebit: 100, + billing: { + recipient: { + category: RecipientCategory.PERSON, + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '01-01-1990', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + email: 'test@buckaroo.nl', + phone: { + mobile: '0612345678', + landline: '0201234567', + }, + }, + articles: [ + { + vatPercentage: 21, + price: 10, + description: 'Test', + quantity: 4, + identifier: 'test', + }, + ], +}; - test('Pay', async () => { - await method.pay(payload).then((data) => { - expect(data.isSuccess()).toBeTruthy() - }) - }) +const method = buckarooClientTest.method('afterpay'); +describe('AfterPay methods', () => { + test('Pay', () => { + return method + .pay(paymentPayload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); test('Refund', async () => { - await method.refund({ ...refundPayload }).then((data) => { - expect(data).toBeDefined() - }) - }) + await method + .refund({ + invoice: paymentPayload.invoice, //Set invoice number of the transaction to refund + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', //Set transaction key of the transaction to refund + amountCredit: paymentPayload.amountDebit, + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeDefined(); + }); + }); test('Authorize', async () => { - await method.authorize(payload).then((data) => { - expect(data).toBeDefined() - }) - }) + await method + .authorize(paymentPayload) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); test('CancelAuthorize', async () => { - await method.cancelAuthorize(refundPayload).then((data) => { - expect(data).toBeDefined() - }) - }) + await method + .cancelAuthorize({ + invoice: paymentPayload.invoice, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountCredit: 100, + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); test('Capture', async () => { await method .capture({ - amountDebit: 4, - invoice: '123456789', - originalTransactionKey: '123456789' + ...paymentPayload, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('PayRemainder', async () => { - await method.payRemainder(payload).then((data) => { - expect(data).toBeDefined() - }) - }) - test('AuthorizeRemainder', async () => { - await method.authorizeRemainder(payload).then((data) => { - expect(data).toBeDefined() - }) - }) -}) - -let refundPayload: RefundPayload = { - amountCredit: 14, - originalTransactionKey: '123456789' -} - -let payload: IPay = { - amountDebit: 14, - clientIP: '127.0.0.1', - - shippingCustomer: { - city: 'rew', - country: 'NL', - street: 'fsd', - streetNumber: '423', - streetNumberAdditional: 'ewr', - postalCode: '1234AB', - email: 'example@hotmail.com', - phone: '+31201234567', - mobilePhone: '+31612345678', - birthDate: '1999-11-21', - careOf: '', - category: RecipientCategory.PERSON, - conversationLanguage: 'NL', - customerNumber: 'a', - firstName: 'a', - identificationNumber: '675', - lastName: 'a', - salutation: 'Mr' - }, - billingCustomer: { - city: 'rew', - country: 'NL', - street: 'fsd', - streetNumber: '423', - streetNumberAdditional: 'ewr', - postalCode: '1234AB', - email: 'example@hotmail.com', - phone: '+31201234567', - mobilePhone: '+31612345678', - birthDate: '1999-11-21', - careOf: '', - category: RecipientCategory.PERSON, - conversationLanguage: 'NL', - customerNumber: 'a', - firstName: 'a', - identificationNumber: '675', - lastName: 'a', - salutation: 'Mr' - }, - article: [ - { - description: 'ter', - identifier: '423f', - imageUrl: '', - quantity: 1, - type: 'PhysicalArticle', - unitCode: '', - url: '', - vatPercentage: 0, - grossUnitPrice: 7 - - }, - { - description: 'ter', - identifier: '423f', - unitCode: '', - type: 'PhysicalArticle', - quantity: 1, - vatPercentage: 0, - grossUnitPrice: 7 - } - ] -} + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/AfterPayDigiAccept.test.js b/tests/PaymentMethods/AfterPayDigiAccept.test.js new file mode 100644 index 00000000..c415788a --- /dev/null +++ b/tests/PaymentMethods/AfterPayDigiAccept.test.js @@ -0,0 +1,114 @@ +import { RequestTypes } from '../../src/Constants/Endpoints'; +import { TestBilling } from '../Models'; +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src/Utils/Functions'; +import Gender from '../../src/Constants/Gender'; +const method = buckarooClientTest.method('afterpaydigiaccept'); +describe('AfterPayDigiAccept methods', () => { + test('Authorize', async () => { + await method + .authorize({ + amountDebit: 0, + articles: [], + bankAccount: '', + bankCode: '', + billing: TestBilling, + clientIP: '', + merchantImageUrl: '', + ourReference: '', + summaryImageUrl: '', + yourReference: '' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Pay', async () => { + await method + .pay({ ...paymentPayload, clientIP: '127.0.0.1' }) + .request() + .then((data) => { + expect(data.data).toBeDefined(); + }); + }); + test('Specification', async () => { + await method + .specification(RequestTypes.Transaction) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); +const paymentPayload = { + amountDebit: 40.5, + b2b: true, + addressesDiffer: true, + customerIPAddress: '0.0.0.0', + shippingCosts: 0.5, + costCentre: 'Test', + department: 'Test', + establishmentNumber: 123456, + billing: { + recipient: { + gender: Gender.FEMALE, + initials: 'AB', + lastName: 'Do', + birthDate: '1990-01-01', + culture: 'NL' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '13', + houseNumberAdditional: 'a', + zipcode: '1234AB', + city: 'Heerenveen', + country: 'NL' + }, + phone: { + mobile: '0698765433' + }, + email: 'test@buckaroo.nl' + }, + shipping: { + recipient: { + culture: 'NL', + gender: Gender.MALE, + initials: 'YJ', + lastName: 'Jansen', + companyName: 'Buckaroo B.V.', + birthDate: '1990-01-01', + chamberOfCommerce: '12345678', + vatNumber: 'NL12345678' + }, + address: { + street: 'Kalverstraat', + houseNumber: '13', + houseNumberAdditional: 'b', + zipcode: '4321EB', + city: 'Amsterdam', + country: 'NL' + }, + phone: { + mobile: '0698765433' + }, + email: 'test@buckaroo.nl' + }, + articles: [ + { + identifier: uniqid(), + description: 'Blue Toy Car', + price: 10.0, + quantity: 2, + vatCategory: '1' + }, + { + identifier: uniqid(), + description: 'Red Toy Car', + price: 10.0, + quantity: 2, + vatCategory: '1' + } + ] +}; diff --git a/tests/PaymentMethods/AfterPayDigiAccept.test.ts b/tests/PaymentMethods/AfterPayDigiAccept.test.ts index 197fe5ce..09eccb13 100644 --- a/tests/PaymentMethods/AfterPayDigiAccept.test.ts +++ b/tests/PaymentMethods/AfterPayDigiAccept.test.ts @@ -1,27 +1,105 @@ -require('../BuckarooClient.test') -import AfterPayDigiAccept from '../../src/PaymentMethods/AfterpayDigiAccept' +import { Gender, getIPAddress, RequestTypes, uniqid } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; +import { IPay } from '../../src/PaymentMethods/AfterpayDigiAccept/Model/Pay'; -const method = new AfterPayDigiAccept() +const method = buckarooClientTest.method('afterpaydigiaccept'); +const paymentPayload: IPay = { + amountDebit: 100, + order: uniqid(), + invoice: uniqid(), + b2b: true, + addressesDiffer: true, + customerIPAddress: getIPAddress(), + shippingCosts: 0.5, + costCentre: 'Test', + department: 'Test', + establishmentNumber: 123456, + billing: { + recipient: { + gender: Gender.FEMALE, + initials: 'AB', + lastName: 'Acceptatie', + birthDate: '1990-01-01', + culture: 'NL', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + phone: { + mobile: '0612345678', + }, + email: 'test@buckaroo.nl', + }, + shipping: { + recipient: { + culture: 'NL', + gender: Gender.MALE, + initials: 'TA', + lastName: 'Acceptatie', + companyName: 'Buckaroo B.V.', + chamberOfCommerce: 'XXXXXX41', + birthDate: '1990-01-01', + vatNumber: 'NLXXXXXXXXXXB01', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + phone: { + mobile: '0612345678', + }, + email: 'test@buckaroo.nl', + }, + articles: [ + { + identifier: uniqid(), + description: 'Blue Toy Car', + price: 10.0, + quantity: 2, + vatCategory: '1', + }, + { + identifier: uniqid(), + description: 'Red Toy Car', + price: 10.0, + quantity: 2, + vatCategory: '1', + }, + ], +}; describe('AfterPayDigiAccept methods', () => { test('Authorize', async () => { await method - .authorize({ - amountDebit: 14, - clientIP: '127.0.0.1' - }) + .authorize(paymentPayload) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('Pay', async () => { await method - .pay({ - amountDebit: 14, - clientIP: '127.0.0.1' - }) + .pay(paymentPayload) + .request() .then((data) => { - expect(data.data).toBeDefined() - }) - }) -}) + expect(data.data).toBeDefined(); + }); + }); + test('Specification', async () => { + await method + .specification(RequestTypes.Transaction) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); \ No newline at end of file diff --git a/tests/PaymentMethods/Alipay.test.js b/tests/PaymentMethods/Alipay.test.js new file mode 100644 index 00000000..21b692b1 --- /dev/null +++ b/tests/PaymentMethods/Alipay.test.js @@ -0,0 +1,26 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const alipay = buckarooClientTest.method('alipay'); +describe('Alipay methods', () => { + test('Pay Simple Payload', async () => { + await alipay + .pay({ + amountDebit: 10, + useMobileView: false + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await alipay + .refund({ + amountCredit: 5, + originalTransactionKey: 'F397777A251645F8BDD81547B5005B4B' + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Alipay.test.ts b/tests/PaymentMethods/Alipay.test.ts index c7263d0f..7a1ae36e 100644 --- a/tests/PaymentMethods/Alipay.test.ts +++ b/tests/PaymentMethods/Alipay.test.ts @@ -1,32 +1,30 @@ -require('../BuckarooClient.test') -import Alipay from '../../src/PaymentMethods/Alipay' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new Alipay() +const alipay = buckarooClientTest.method('alipay'); describe('Alipay methods', () => { test('Pay Simple Payload', async () => { - await method + await alipay .pay({ - amountDebit: 10, - useMobileView: false + amountDebit: 100, + useMobileView: false, }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { - await method + await alipay .refund({ - amountCredit: 5, - originalTransactionKey: 'F397777A251645F8BDD81547B5005B4B' + amountCredit: 0.01, + invoice: uniqid(), + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Specifications', async () => { - await method.specification().then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/ApplePay.test.js b/tests/PaymentMethods/ApplePay.test.js new file mode 100644 index 00000000..20566d83 --- /dev/null +++ b/tests/PaymentMethods/ApplePay.test.js @@ -0,0 +1,50 @@ +import { uniqid } from '../../src/Utils/Functions'; +require('../BuckarooClient.test'); +import ApplePay from '../../src/PaymentMethods/ApplePay'; +const method = new ApplePay(); +describe('Applepay methods', () => { + test('Pay Simple Payload', async () => { + await method + .pay({ + amountDebit: 10, + paymentData: 'sad', + customerCardName: '87y7y8' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Pay Redirect Payload', async () => { + await method + .payRedirect({ + amountDebit: 10, + invoice: uniqid(), + servicesSelectableByClient: 'applepay', + continueOnIncomplete: true + }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 5, + originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Specifications', async () => { + await method + .specification() + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/ApplePay.test.ts b/tests/PaymentMethods/ApplePay.test.ts index 7e4b201d..aad65bfe 100644 --- a/tests/PaymentMethods/ApplePay.test.ts +++ b/tests/PaymentMethods/ApplePay.test.ts @@ -1,34 +1,45 @@ -require('../BuckarooClient.test') -import ApplePay from '../../src/PaymentMethods/ApplePay/index' +import { uniqid } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; -const method = new ApplePay() +const method = buckarooClientTest.method('applepay'); describe('Applepay methods', () => { - test('Pay Simple Payload', async () => { + test('Pay', async () => { await method .pay({ - amountDebit: 10, - paymentData: 'sad', - customerCardName: '87y7y8' + amountDebit: 100, + invoice: uniqid(), + paymentData: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + customerCardName: 'XXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - + expect(data).toBeDefined(); + }); + }); + test('Pay Redirect Payload', async () => { + await method + .payRedirect({ + amountDebit: 100, + invoice: uniqid(), + servicesSelectableByClient: 'applepay', + continueOnIncomplete: true, }) - }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 5, - originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Specifications', async () => { - await method.specification().then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Bancontact.test.js b/tests/PaymentMethods/Bancontact.test.js new file mode 100644 index 00000000..c617fed3 --- /dev/null +++ b/tests/PaymentMethods/Bancontact.test.js @@ -0,0 +1,86 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('bancontactmrcash'); +describe('BanContact methods', () => { + test('Pay Simple Payload', async () => { + await method + .pay({ + amountDebit: 10, + saveToken: true + }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 5, + originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Authenticate', async () => { + await method + .authenticate({ amountDebit: 10 }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeDefined(); + }); + }); + test('PayOneClick', async () => { + await method + .payOneClick({ + originalTransactionKey: 'dsad', + amountDebit: 12 + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('CompletePayment', async () => { + await method + .completePayment({ + originalTransactionKey: 'dsad', + encryptedCardData: 'sUIB' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('PayEncrypted', async () => { + await method + .payEncrypted({ + amountDebit: 10, + encryptedCardData: 'yrtgdd' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('PayRecurring', async () => { + await method + .payRecurring({ + amountDebit: 10, + originalTransactionKey: 'sadas' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Specifications', () => { + method + .specification() + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Bancontact.test.ts b/tests/PaymentMethods/Bancontact.test.ts index f22a546a..f75357ec 100644 --- a/tests/PaymentMethods/Bancontact.test.ts +++ b/tests/PaymentMethods/Bancontact.test.ts @@ -1,86 +1,85 @@ -require('../BuckarooClient.test') -import BanContact from '../../src/PaymentMethods/Bancontact/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new BanContact() +const method = buckarooClientTest.method('bancontactmrcash'); describe('BanContact methods', () => { test('Pay Simple Payload', async () => { await method .pay({ - amountDebit: 10, - saveToken: true + amountDebit: 100, + saveToken: true, }) + .request() .then((data) => { - expect(data.isWaitingOnUserInput()).toBeTruthy() - }) - }) + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 5, - originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Authorize', async () => { - await method.authorize({ amountDebit: 10 }).then((data) => { - expect(data.isWaitingOnUserInput()).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); + test('Authenticate', async () => { + await method + .authenticate({ invoice: uniqid(), amountDebit: 100 }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeDefined(); + }); + }); test('PayOneClick', async () => { await method .payOneClick({ - originalTransactionKey: 'dsad', - amountDebit: 12 + invoice: uniqid(), + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountDebit: 100, }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('CompletePayment', async () => { await method .completePayment({ - originalTransactionKey: 'dsad', - encryptedCardData: 'sUIB' + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + encryptedCardData: 'XXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('PayEncrypted', async () => { await method .payEncrypted({ - amountDebit: 10, - encryptedCardData: 'yrtgdd' + invoice: uniqid(), + amountDebit: 100, + encryptedCardData: 'XXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('PayRecurring', async () => { await method .payRecurring({ - amountDebit: 10, - originalTransactionKey: 'sadas' + invoice: uniqid(), + amountDebit: 100, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Specifications', async () => { - await method.specification().then((data) => { - expect(data).toBeDefined() - }) - }) - - test('Capture', async () => { - await method.capture({ - originalTransactionKey: 'sadas', - amountDebit: 10 - }).then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/BankTransfer.test.js b/tests/PaymentMethods/BankTransfer.test.js new file mode 100644 index 00000000..599c31d4 --- /dev/null +++ b/tests/PaymentMethods/BankTransfer.test.js @@ -0,0 +1,23 @@ +import Gender from '../../src/Constants/Gender'; +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('transfer'); +describe('Transfer methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 10, + customer: { + firstName: 'John', + lastName: 'Doe', + gender: Gender.MALE + }, + email: 'test@hotmail.com', + sendMail: true, + dateDue: '2024-10-10' + }) + .request() + .then((res) => { + expect(res.isAwaitingConsumer()).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/BankTransfer.test.ts b/tests/PaymentMethods/BankTransfer.test.ts index 02449f3f..cb0c00e4 100644 --- a/tests/PaymentMethods/BankTransfer.test.ts +++ b/tests/PaymentMethods/BankTransfer.test.ts @@ -1,31 +1,25 @@ -import BankTransfer from '../../src/PaymentMethods/BankTransfer' -import Gender from '../../src/Constants/Gender' +import { Gender } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; -require('../BuckarooClient.test') - -const method = new BankTransfer() +const method = buckarooClientTest.method('transfer'); describe('Transfer methods', () => { - test('Specification', async () => { - await method.specification().then((res) => { - expect(res).toBeDefined() - }) - }) test('Pay', async () => { await method .pay({ - amountDebit: 10, - customerCountry: 'NL', - customerEmail: 'test@hotmail.com', - customerFirstName: 'test', - customerGender: Gender.FEMALE, - customerLastName: 'Test', - description: 'Test without payment method with ServicesSelectableByClient', - continueOnIncomplete: 1, - servicesSelectableByClient: 'ideal,creditcard' + amountDebit: 100, + customer: { + firstName: 'Test', + lastName: 'Acceptatie', + gender: Gender.MALE, + }, + email: 'test@buckaroo.nl', + sendMail: true, + dateDue: '2024-10-10', }) + .request() .then((res) => { - expect(res.isAwaitingConsumer()).toBeDefined() - }) - }) -}) + expect(res.isAwaitingConsumer()).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Belfius.test.js b/tests/PaymentMethods/Belfius.test.js new file mode 100644 index 00000000..83ddc881 --- /dev/null +++ b/tests/PaymentMethods/Belfius.test.js @@ -0,0 +1,33 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('belfius'); +describe('testing methods', () => { + test('Pay Simple Payload', async () => { + await method + .pay({ + amountDebit: 10 + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 5, + originalTransactionKey: '86CFE2CB5901463EADE061633BDB9EC8' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Specifications', async () => { + await method + .specification() + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Belfius.test.ts b/tests/PaymentMethods/Belfius.test.ts index cc70c3a6..ed27185f 100644 --- a/tests/PaymentMethods/Belfius.test.ts +++ b/tests/PaymentMethods/Belfius.test.ts @@ -1,31 +1,29 @@ -require('../BuckarooClient.test') -import Belfius from '../../src/PaymentMethods/Belfius/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new Belfius() +const method = buckarooClientTest.method('belfius'); describe('testing methods', () => { test('Pay Simple Payload', async () => { await method .pay({ - amountDebit: 10 + amountDebit: 100, }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 5, - originalTransactionKey: '86CFE2CB5901463EADE061633BDB9EC8' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Specifications', async () => { - await method.specification().then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Billink.test.js b/tests/PaymentMethods/Billink.test.js new file mode 100644 index 00000000..4cdeae3d --- /dev/null +++ b/tests/PaymentMethods/Billink.test.js @@ -0,0 +1,127 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import RecipientCategory from '../../src/Constants/RecipientCategory'; +require('../BuckarooClient.test'); +const method = buckarooClientTest.method('billink'); +describe('Billink methods', () => { + test('Pay', async () => { + await method + .pay(payload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 12, + originalTransactionKey: 'ytgty' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Authorize', async () => { + await method + .authorize(payload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('CancelAuthorize', async () => { + await method + .cancelAuthorize({ + originalTransactionKey: 'ytgty', + amountCredit: 10, + invoice: 'sdsa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Capture', async () => { + await method + .capture({ + originalTransactionKey: 'ytgty', + invoice: "'dsa", + amountDebit: 123, + articles: payload.articles + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); +const payload = { + amountDebit: 50.3, + order: '', + invoice: '', + trackAndTrace: 'TR0F123456789', + vATNumber: '2', + billing: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'John Smith', + title: 'Female', + initials: 'JD', + firstName: 'John', + lastName: 'Do', + birthDate: '01-01-1990', + chamberOfCommerce: 'TEST' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '13', + houseNumberAdditional: 'a', + zipcode: '1234AB', + city: 'Heerenveen', + country: 'NL' + }, + phone: { + mobile: '0698765433', + landline: '0109876543' + }, + email: 'test@buckaroo.nl' + }, + shipping: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'John Smith', + title: 'Male', + initials: 'JD', + firstName: 'John', + lastName: 'Do', + birthDate: '1990-01-01' + }, + address: { + street: 'Kalverstraat', + houseNumber: '13', + houseNumberAdditional: 'b', + zipcode: '4321EB', + city: 'Amsterdam', + country: 'NL' + } + }, + articles: [ + { + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + quantity: 2, + price: 20.1, + priceExcl: 5 + }, + { + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + quantity: 1, + price: 10.1, + priceExcl: 5 + } + ] +}; diff --git a/tests/PaymentMethods/Billink.test.ts b/tests/PaymentMethods/Billink.test.ts index b1d92cda..5f61a317 100644 --- a/tests/PaymentMethods/Billink.test.ts +++ b/tests/PaymentMethods/Billink.test.ts @@ -1,96 +1,131 @@ -import Billink from '../../src/PaymentMethods/Billink/index' -import { IPay } from '../../src/PaymentMethods/Billink/Models/Pay' +import { IPay } from '../../src/PaymentMethods/Billink/Models/Pay'; +import buckarooClientTest from '../BuckarooClient.test'; +import { RecipientCategory, uniqid } from '../../src'; -require('../BuckarooClient.test') - -const method = new Billink() +const method = buckarooClientTest.method('billink'); describe('Billink methods', () => { - test('Specifications', async () => { - await method.specification().then((data) => { - data.getActionRequestParameters('Pay') - expect(data).toBeDefined() - }) - }) + const invoiceId = uniqid(); + test('Pay', async () => { - await method.pay(payload).then((data) => { - expect(data).toBeDefined() - }) - }) + await method + .pay(payload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 12, - originalTransactionKey: 'ytgty' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('Authorize', async () => { - await method.authorize(payload).then((data) => { - expect(data).toBeDefined() - }) - }) + await method + .authorize({ ...payload, invoice: invoiceId }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); test('CancelAuthorize', async () => { await method .cancelAuthorize({ - originalTransactionKey: 'ytgty', - amountCredit: 10, - invoice: 'sdsa' + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountCredit: payload.amountDebit, + invoice: invoiceId, }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('Capture', async () => { await method .capture({ - originalTransactionKey: 'ytgty', - invoice: "'dsa", - amountDebit: 123 + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + invoice: invoiceId, + amountDebit: payload.amountDebit, + articles: payload.articles, }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data).toBeDefined(); + }); + }); +}); -let payload: IPay = { - VATNumber: '', - additionalParameters: undefined, - amountDebit: 0, - article: [], - billingCustomer: { - chamberOfCommerce: '', - city: '', - firstName: '', - initials: '', - lastName: '', - postalCode: '', - street: '', - streetNumber: 0 +const payload: IPay = { + amountDebit: 100, + trackAndTrace: 'XXXXXXXXXXXXX', + vatNumber: 'NLXXXXXXXXXXB01', + billing: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'Test Acceptatie', + title: 'Female', + initials: 'TA', + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '01-01-1990', + chamberOfCommerce: 'XXXXXX41', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + phone: { + mobile: '0612345678', + landline: '0201234567', + }, + email: 'test@buckaroo.nl', + }, + shipping: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'Test Acceptatie', + title: 'Male', + initials: 'TA', + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '1990-01-01', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, }, - clientIP: undefined, - continueOnIncomplete: 1, - culture: '', - currency: '', - customParameters: undefined, - description: '', - invoice: '', - order: '', - originalTransactionKey: '', - originalTransactionReference: '', - pushURL: '', - pushURLFailure: '', - returnURL: '', - returnURLCancel: '', - returnURLError: '', - returnURLReject: '', - servicesExcludedForClient: '', - servicesSelectableByClient: '', - shippingCustomer: undefined, - startRecurrent: false, - summaryImageUrl: '', - trackandtrace: '' -} + articles: [ + { + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + quantity: 2, + price: 20.1, + priceExcl: 5, + }, + { + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + quantity: 1, + price: 10.1, + priceExcl: 5, + }, + ], +}; diff --git a/tests/PaymentMethods/BuckarooVoucher.test.js b/tests/PaymentMethods/BuckarooVoucher.test.js new file mode 100644 index 00000000..40986071 --- /dev/null +++ b/tests/PaymentMethods/BuckarooVoucher.test.js @@ -0,0 +1,59 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('buckaroovoucher'); +describe('testing methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 12, + voucherCode: '' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 12, + originalTransactionKey: '' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('GetBalance', async () => { + await method + .getBalance({ + voucherCode: 'WP6W-XXXX-XXXX-56T7' + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('CreateApplication', async () => { + await method + .create({ + creationBalance: 12, + usageType: 1, + validFrom: '2021-01-01', + validUntil: '2024-01-01' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('DeactivateVoucher', async () => { + await method + .deactivate({ + voucherCode: '' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/BuckarooVoucher.test.ts b/tests/PaymentMethods/BuckarooVoucher.test.ts index d7be1ad4..25857c12 100644 --- a/tests/PaymentMethods/BuckarooVoucher.test.ts +++ b/tests/PaymentMethods/BuckarooVoucher.test.ts @@ -1,57 +1,63 @@ -require('../BuckarooClient.test') -import BuckarooVoucher from '../../src/PaymentMethods/BuckarooVoucher/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new BuckarooVoucher() +const method = buckarooClientTest.method('buckaroovoucher'); describe('testing methods', () => { test('Pay', async () => { await method .pay({ - amountDebit: 12, - voucherCode: '' + amountDebit: 100, + voucherCode: 'XXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 12, - originalTransactionKey: '' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('GetBalance', async () => { await method .getBalance({ - voucherCode: '' + voucherCode: 'XXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isFailed()).toBeTruthy(); + }); + }); test('CreateApplication', async () => { await method - .createApplication({ + .create({ creationBalance: 12, usageType: 1, validFrom: '2021-01-01', - validUntil: '2024-01-01' + validUntil: '2024-01-01', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data).toBeDefined(); + }); + }); test('DeactivateVoucher', async () => { await method - .deactivateVoucher({ - voucherCode: '' + .deactivate({ + voucherCode: 'XXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/BuckarooWallet.test.js b/tests/PaymentMethods/BuckarooWallet.test.js new file mode 100644 index 00000000..209621b7 --- /dev/null +++ b/tests/PaymentMethods/BuckarooWallet.test.js @@ -0,0 +1,115 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src/Utils/Functions'; +const method = buckarooClientTest.method('BuckarooWalletCollecting'); +describe('BuckarooWallet methods', () => { + test('Pay', async () => { + await method + .pay({ + invoice: 'string', + amountDebit: 12, + walletId: '2' + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + invoice: 'string', + amountCredit: 12, + originalTransactionKey: '46FB241693914AA4AE7A8B6DB33DE' + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('CancelReservation', async () => { + await method + .cancel({ + invoice: 'BuckarooWalletInvoiceId', + originalTransactionKey: '46FB241693914AA4AE7A8B6DB33DE', + amountDebit: 1, + walletMutationGuid: '49B018248ECE4346AC20B902' + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('deposit', async () => { + await method + .deposit({ + invoice: 'string', + walletId: '', + amountCredit: 12, + originalTransactionKey: '' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Update', async () => { + await method + .update({ + walletId: '10', + status: 'Disabled', + email: 'test@buckaroo.nl', + customer: { + firstName: 'John', + lastName: 'string' + }, + bankAccount: { + iban: 'NL13TEST0123456789' + } + }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('Withdrawal', async () => { + await method + .withdrawal({ + invoice: 'BuckarooWalletInvoiceId', + walletId: '10', + amountDebit: 10, + originalTransactionKey: '46FB241693914AA4AE7A8B6DB33DE' + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('Create Wallet', async () => { + await method + .create({ + walletId: uniqid(), + email: 'test@buckaroo.nl', + customer: { + firstName: 'John', + lastName: 'string' + }, + bankAccount: { + iban: 'NL13TEST0123456789' + } + }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('GetInfo', async () => { + await method + .getInfo({ + walletId: '10' + }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/BuckarooWallet.test.ts b/tests/PaymentMethods/BuckarooWallet.test.ts index fff1a12d..2f3bffa7 100644 --- a/tests/PaymentMethods/BuckarooWallet.test.ts +++ b/tests/PaymentMethods/BuckarooWallet.test.ts @@ -1,75 +1,117 @@ -require('../BuckarooClient.test') -import BuckarooWallet from '../../src/PaymentMethods/BuckarooWallet/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new BuckarooWallet() +const method = buckarooClientTest.method('BuckarooWalletCollecting'); describe('BuckarooWallet methods', () => { test('Pay', async () => { await method .pay({ - invoice: 'string', - amountDebit: 12, - walletId: '2' + invoice: uniqid(), + amountDebit: 100, + walletId: 'XXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - invoice: 'string', - walletId: '2', - amountCredit: 12, - originalTransactionKey: '' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isFailed()).toBeTruthy(); + }); + }); test('CancelReservation', async () => { await method .cancel({ - invoice: 'dsadsadsa', - walletMutationGuid: '2' + invoice: uniqid(), + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountDebit: 100, + walletMutationGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('deposit', async () => { await method .deposit({ - invoice: 'string', - walletId: '', - amountCredit: 12, - originalTransactionKey: '' + invoice: uniqid(), + walletId: 'XXXXXXXXXXXXXXXXXXXXX', + amountCredit: 100, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() + expect(data).toBeDefined(); + }); + }); + test('Update', async () => { + await method + .update({ + walletId: 'XXXXXXXXXXXXXXXXXXXXX', + status: 'Disabled', + email: 'test@buckaroo.nl', + customer: { + firstName: 'Test', + lastName: 'Acceptatie', + }, + bankAccount: { + iban: 'NLXXTESTXXXXXXXXXX', + }, }) - }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); test('Withdrawal', async () => { await method .withdrawal({ - invoice: 'dasd', - walletId: '654dfcvb', - amountDebit: 10, - originalTransactionKey: '' + invoice: uniqid(), + walletId: 'XXXXXXXXXXXXXXXXXXXXX', + amountDebit: 100, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('Create Wallet', async () => { await method .create({ - invoice: '', - pushURL: '', - walletId: '' + walletId: 'XXXXXXXXXXXXXXXXXXXXX', + email: 'test@buckaroo.nl', + customer: { + firstName: 'Test', + lastName: 'Acceptatie', + }, + bankAccount: { + iban: 'NLXXTESTXXXXXXXXXX', + }, }) + .request() .then((data) => { - expect(data).toBeDefined() + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('GetInfo', async () => { + await method + .getInfo({ + walletId: 'XXXXXXXXXXXXXXXXXXXXX', }) - }) -}) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Client.test.ts b/tests/PaymentMethods/Client.test.ts deleted file mode 100644 index a849f32a..00000000 --- a/tests/PaymentMethods/Client.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { uniqid } from '../../src/Utils/Functions' - -require('../BuckarooClient.test') -import buckarooClient from '../../src/BuckarooClient' - -const client = buckarooClient() -test('PaymentStatus', async () => { - await client.status('0AA966B997CB4676B55A07E9C3BA4DB4').then((data) => { - expect(data).toBeDefined() - }) -}) -test('paymentCancelInfo', async () => { - await client.cancelInfo('73902D944DC848CBADC49D9B8A8C2F16').then((data) => { - expect(data).toBeDefined() - }) -}) -test('paymentRefundInfo', async () => { - await client.refundInfo('73902D944DC848CBADC49D9B8A8C2F16').then((data) => { - expect(data).toBeDefined() - }) -}) - -test('paymentInvoiceInfo', async () => { - await client.invoiceInfo('5f5701d44aac88').then((data) => { - expect(data).toBeDefined() - }) -}) - -test('Service specifications', async () => { - let specifications = await client.specifications([ - { - paymentName: 'ideal', - serviceVersion: 1 - } - ]) - expect(specifications).toBeDefined() -}) -test('Client Transaction Request', async () => { - let specifications = await client.transactionRequest({ - invoice: uniqid(''), - order: uniqid(''), - currency: 'EUR', - amountDebit: 0.01, - pushURL: 'http://testcheckout.buckaroo.nl/push', - description: 'Test without payment method with ServicesSelectableByClient', - continueOnIncomplete: 1, - servicesSelectableByClient: 'ideal,paypal,bancontactmrcash', - servicesExcludedForClient: 'ideal' - }) - - expect(specifications).toBeDefined() -}) diff --git a/tests/PaymentMethods/CreditCard.test.js b/tests/PaymentMethods/CreditCard.test.js new file mode 100644 index 00000000..82c261ff --- /dev/null +++ b/tests/PaymentMethods/CreditCard.test.js @@ -0,0 +1,119 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('visa'); +describe('testing methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 10 + }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 5, + originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Authorize', async () => { + await method + .authorize({ + amountDebit: 10 + }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); + test('PayEncrypted', async () => { + await method + .payEncrypted({ + amountDebit: 10, + name: 'Visa', + encryptedCardData: '' + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('PayWithSecurityCode', async () => { + await method + .payWithSecurityCode({ + amountDebit: 10, + encryptedSecurityCode: 'sad', + name: 'Visa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('AuthorizeWithSecurityCode', async () => { + await method + .authorizeWithSecurityCode({ + amountDebit: 10, + encryptedSecurityCode: 'sad', + name: 'Visa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('AuthorizeEncrypted', async () => { + await method + .authorizeEncrypted({ + amountDebit: 10, + encryptedCardData: 'sad', + name: 'Visa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('CancelAuthorize', async () => { + await method + .cancelAuthorize({ + originalTransactionKey: 'sad', + amountCredit: 10, + name: 'Visa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Capture', async () => { + await method + .capture({ + originalTransactionKey: 'sad', + amountDebit: 10, + name: 'Visa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('PayRecurrent', async () => { + await method + .payRecurrent({ + originalTransactionKey: 'sad', + amountDebit: 10, + name: 'Visa' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/CreditCard.test.ts b/tests/PaymentMethods/CreditCard.test.ts index c38f16cc..848241aa 100644 --- a/tests/PaymentMethods/CreditCard.test.ts +++ b/tests/PaymentMethods/CreditCard.test.ts @@ -1,115 +1,123 @@ -require('../BuckarooClient.test') -import CreditCard from '../../src/PaymentMethods/CreditCard/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new CreditCard() +const method = buckarooClientTest.method('visa'); describe('testing methods', () => { - test('Pay', async () => { - await method + test('Pay', async () => { + await method .pay({ - amountDebit: 10, - name: 'Visa' + amountDebit: 100, }) + .request() .then((data) => { - expect(data).toBeDefined() + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) - }) - test('Refund', async () => { - await method - .refund({ - amountCredit: 5, - name: 'Visa', - originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Authorize', async () => { - await method - .authorize({ - amountDebit: 10, - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('PayEncrypted', async () => { - await method - .payEncrypted({ - amountDebit: 10, - name: 'Visa', - encryptedCardData: '' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('PayWithSecurityCode', async () => { - await method - .payWithSecurityCode({ - amountDebit: 10, - encryptedSecurityCode: 'sad', - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('AuthorizeWithSecurityCode', async () => { - await method - .authorizeWithSecurityCode({ - amountDebit: 10, - encryptedSecurityCode: 'sad', - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('AuthorizeEncrypted', async () => { - await method - .authorizeEncrypted({ - amountDebit: 10, - encryptedCardData: 'sad', - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('CancelAuthorize', async () => { - await method - .cancelAuthorize({ - originalTransactionKey: 'sad', - amountCredit: 10, - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Capture', async () => { - await method - .capture({ - originalTransactionKey: 'sad', - amountDebit: 10, - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) - test('PayRecurrent', async () => { - await method - .payRecurrent({ - originalTransactionKey: 'sad', - amountDebit: 10, - name: 'Visa' - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) -}) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Authorize', async () => { + await method + .authorize({ + amountDebit: 100, + }) + .request() + .then((data) => { + expect(data.isWaitingOnUserInput()).toBeTruthy(); + }); + }); + test('PayEncrypted', async () => { + await method + .payEncrypted({ + amountDebit: 100, + name: 'Visa', + encryptedCardData: 'XXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('PayWithSecurityCode', async () => { + await method + .payWithSecurityCode({ + amountDebit: 100, + encryptedSecurityCode: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + name: 'Visa', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('AuthorizeWithSecurityCode', async () => { + await method + .authorizeWithSecurityCode({ + amountDebit: 100, + encryptedSecurityCode: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + name: 'Visa', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('AuthorizeEncrypted', async () => { + await method + .authorizeEncrypted({ + amountDebit: 100, + encryptedCardData: 'XXXXXXXXXXXXXXXXXXXXXXXX', + name: 'Visa', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('CancelAuthorize', async () => { + await method + .cancelAuthorize({ + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountCredit: 100, + name: 'Visa', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Capture', async () => { + await method + .capture({ + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountDebit: 100, + name: 'Visa', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('PayRecurrent', async () => { + await method + .payRecurrent({ + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountDebit: 100, + name: 'Visa', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/CreditClick.test.js b/tests/PaymentMethods/CreditClick.test.js new file mode 100644 index 00000000..82994ff4 --- /dev/null +++ b/tests/PaymentMethods/CreditClick.test.js @@ -0,0 +1,32 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('creditclick'); +describe('Testing CreditClick methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 31, + person: { + firstName: 'test', + lastName: 'test' + }, + email: 't.tester@test.nl' + }) + .request() + .then((response) => { + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 31, + originalTransactionKey: 'C85BABFCCA2D4921B9CFBA0EBDF82C70', + description: 'test', + refundReason: 'Fraudulent' + }) + .request() + .then((response) => { + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/CreditClick.test.ts b/tests/PaymentMethods/CreditClick.test.ts index 5f75fdd4..43711b62 100644 --- a/tests/PaymentMethods/CreditClick.test.ts +++ b/tests/PaymentMethods/CreditClick.test.ts @@ -1,28 +1,36 @@ -require('../BuckarooClient.test') -import CreditClick from '../../src/PaymentMethods/CreditClick/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new CreditClick() +const method = buckarooClientTest.method('creditclick'); describe('Testing CreditClick methods', () => { test('Pay', async () => { await method .pay({ - amountDebit: 31 + amountDebit: 100, + person: { + firstName: 'Test', + lastName: 'Acceptatie', + }, + email: 'test@buckaroo.nl', }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 31, - originalTransactionKey: 'C85BABFCCA2D4921B9CFBA0EBDF82C70', - description: 'test', - refundReason: 'Fraudulent' + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + invoice: uniqid(), + description: 'refund', + refundReason: 'Fraudulent', }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) -}) + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/CreditManagment.test.js b/tests/PaymentMethods/CreditManagment.test.js new file mode 100644 index 00000000..86a196ba --- /dev/null +++ b/tests/PaymentMethods/CreditManagment.test.js @@ -0,0 +1,265 @@ +import Gender from '../../src/Constants/Gender'; +import CreditManagementInstallmentInterval from '../../src/Constants/CreditManagementInstallmentInterval'; +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src/Utils/Functions'; +const creditManagement = buckarooClientTest.method('CreditManagement3'); +describe('Testing Credit Management', () => { + test('CreateInvoice', async () => { + await creditManagement + .createInvoice(creditManagementTestInvoice()) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('CreateInvoice With Articles', async () => { + await creditManagement + .createInvoice(creditManagementTestInvoice({ + invoice: 'Billingtest101', + description: 'buckaroo_schema_test_PDF', + invoiceAmount: 217.8, + invoiceDate: '2022-01-01', + dueDate: '1990-01-01', + schemeKey: '2amq34', + poNumber: 'PO-12345', + debtor: { + code: 'johnsmith4' + }, + articles: [ + { + productGroupName: 'Toys', + productGroupOrderIndex: 1, + productOrderIndex: 1, + type: 'Regular', + identifier: 'ART12', + description: 'Blue Toy Car', + quantity: 3, + unitOfMeasurement: 'piece(s)', + price: 10, + discountPercentage: 20, + totalDiscount: 6, + vatPercentage: 21, + totalVat: 0.6, + totalAmountExVat: 8.4, + totalAmount: 123 + }, + { + productGroupName: 'Toys', + productGroupOrderIndex: 1, + productOrderIndex: 2, + type: 'Regular', + identifier: 'ART12', + description: 'Blue Toy Car', + quantity: 3, + unitOfMeasurement: 'piece(s)', + price: 10, + discountPercentage: 20, + totalDiscount: 6, + vatPercentage: 21, + totalVat: 0.6, + totalAmountExVat: 8.4, + totalAmount: 123 + } + ] + })) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('Pause Invoice', async () => { + await creditManagement + .pauseInvoice({ invoice: 'Testinvoice184915' }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('UnPause Invoice', async () => { + await creditManagement + .unpauseInvoice({ invoice: 'Testinvoice184915' }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('Invoice Info', async () => { + await creditManagement + .invoiceInfo({ + invoice: 'INV001', + invoices: [{ invoiceNumber: 'INV002' }, { invoiceNumber: 'INV003' }] + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('Debtor Info', async () => { + await creditManagement + .debtorInfo({ + debtor: { + code: 'TestDebtor123123' + } + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('AddOrUpdateProductLines', async () => { + await creditManagement + .addOrUpdateProductLines({ + invoiceKey: 'd42', + articles: [ + { + type: 'Regular', + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + totalVat: 12, + totalAmount: 123, + quantity: 2, + price: 20.1 + }, + { + type: 'Regular', + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + totalVat: 12, + totalAmount: 123, + quantity: 1, + price: 10.1 + } + ] + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('resumeDebtorFile', async () => { + await creditManagement + .resumeDebtorFile({ debtorFileGuid: 'd42' }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('pauseDebtorFile', async () => { + await creditManagement + .pauseDebtorFile({ debtorFileGuid: 'd42' }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('addOrUpdateDebtor', async () => { + await creditManagement + .addOrUpdateDebtor(creditManagementTestInvoice({ + addressUnreachable: false, + emailUnreachable: false, + mobileUnreachable: false + })) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('CreateCombinedInvoice', async () => { + const combinedInvoice = creditManagement.createCombinedInvoice(creditManagementTestInvoice()); + buckarooClientTest + .method('sepadirectdebit') + .combine(combinedInvoice.data) + .pay({ + iban: 'NL39RABO0300065264', + bic: 'RABONL2U', + mandateReference: 'TestMandateReference', + mandateDate: '2020-01-01', + collectDate: '2020-07-03', + amountDebit: 10.1, + customer: { + name: 'John Smith' + }, + invoice: uniqid('TestInvoice') + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('CreatePaymentPlan', async () => { + await creditManagement + .createPaymentPlan({ + description: 'Payment in two intstallments', + includedInvoiceKey: '20D09973FB5C4DBC9A33DB0F4F707xxx', + dossierNumber: 'PaymentplanJohnsmith123', + installmentCount: 2, + initialAmount: 100, + startDate: '2030-01-01', + interval: CreditManagementInstallmentInterval.MONTH, + paymentPlanCostAmount: 3.5, + paymentPlanCostAmountVat: 1.2, + recipientEmail: 'test@buckaroo.nl' + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('pauseInvoice', async () => { + await creditManagement + .pauseInvoice({ + invoice: 'd42' + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); +export const creditManagementTestInvoice = (append = {}) => { + return { + applyStartRecurrent: false, + invoiceAmount: 10, + invoiceAmountVAT: 1, + invoiceDate: '2022-01-01', + dueDate: '2030-01-01', + schemeKey: '2amq34', + maxStepIndex: 1, + allowedServices: 'ideal,mastercard', + debtor: { + code: 'johnsmith4' + }, + email: 'youremail@example.nl', + phone: { + mobile: '06198765432' + }, + person: { + culture: 'nl-NL', + title: 'Msc', + initials: 'JS', + firstName: 'Test', + lastNamePrefix: 'Jones', + lastName: 'Aflever', + gender: Gender.MALE + }, + company: { + culture: 'nl-NL', + name: 'My Company Corporation', + vatApplicable: true, + vatNumber: 'NL140619562B01', + chamberOfCommerce: '20091741' + }, + address: { + street: 'Hoofdtraat', + houseNumber: '90', + houseNumberAdditional: 'A', + zipcode: '8441ER', + city: 'Heerenveen', + state: 'Friesland', + country: 'NL' + }, + ...append + }; +}; diff --git a/tests/PaymentMethods/CreditManagment.test.ts b/tests/PaymentMethods/CreditManagment.test.ts index 0200b350..fb35a65f 100644 --- a/tests/PaymentMethods/CreditManagment.test.ts +++ b/tests/PaymentMethods/CreditManagment.test.ts @@ -1,139 +1,247 @@ -require('../BuckarooClient.test') +import { IInvoice } from '../../src/PaymentMethods/CreditManagement/Models/Invoice'; +import { CreditManagementInstallmentInterval, Gender, uniqid } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; -import CreditManagement from '../../src/PaymentMethods/CreditManagement/index' -import { IInvoice } from '../../src/PaymentMethods/CreditManagement/Models/Invoice' -import Gender from '../../src/Constants/Gender' -import Ideal from '../../src/PaymentMethods/Ideal' -import CreditManagementInstallmentInterval from '../../src/Constants/CreditManagementInstallmentInterval' - -const creditManagement = new CreditManagement() +const creditManagement = buckarooClientTest.method('CreditManagement3'); describe('Testing Credit Management', () => { test('CreateInvoice', async () => { - await creditManagement.createInvoice(invoice()).then((data) => { - expect(data).toBeDefined() - }) - }) - + await creditManagement + .createInvoice(creditManagementTestInvoice()) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('CreateInvoice With Articles', async () => { + await creditManagement + .createInvoice( + creditManagementTestInvoice({ + invoice: uniqid(), + description: 'buckaroo_schema_test_PDF', + invoiceAmount: 217.8, + invoiceDate: '2022-01-01', + dueDate: '2024-01-01', + schemeKey: 'XXXXXXX', + poNumber: 'XX-XXXXX', + debtor: { + code: 'XXXXXXXX', + }, + articles: [ + { + productGroupName: 'Toys', + productGroupOrderIndex: 1, + productOrderIndex: 1, + type: 'Regular', + identifier: 'ART12', + description: 'Blue Toy Car', + quantity: 3, + unitOfMeasurement: 'piece(s)', + price: 10, + discountPercentage: 20, + totalDiscount: 6, + vatPercentage: 21, + totalVat: 0.6, + totalAmountExVat: 8.4, + totalAmount: 123, + }, + { + productGroupName: 'Toys', + productGroupOrderIndex: 1, + productOrderIndex: 2, + type: 'Regular', + identifier: 'ART12', + description: 'Blue Toy Car', + quantity: 3, + unitOfMeasurement: 'piece(s)', + price: 10, + discountPercentage: 20, + totalDiscount: 6, + vatPercentage: 21, + totalVat: 0.6, + totalAmountExVat: 8.4, + totalAmount: 123, + }, + ], + }) + ) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('Pause Invoice', async () => { - await creditManagement.pauseInvoice({ invoice: 'd42' }).then((data) => { - expect(data).toBeDefined() - }) - }) - test('Debtor Info', async () => { await creditManagement - .debtorInfo({ - debtor: { - code: 'adsad' - } - }) + .pauseInvoice({ invoice: uniqid() }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('UnPause Invoice', async () => { + await creditManagement + .unpauseInvoice({ invoice: uniqid() }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('Invoice Info', async () => { await creditManagement .invoiceInfo({ - invoice: 'invoice1', - invoices: [ - { - invoiceNumber: 'invoice2' - }, - { - invoiceNumber: 'invoice3' - } - ] + invoice: uniqid(), + invoices: [{ invoiceNumber: 'INV002' }, { invoiceNumber: 'INV003' }], }) + .request() .then((data) => { - expect(data).toBeDefined() + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('Debtor Info', async () => { + await creditManagement + .debtorInfo({ + debtor: { + code: 'XXXXXXXX', + }, }) - }) - test('UnPause Invoice', async () => { - await creditManagement.unpauseInvoice({ invoice: 'd42' }).then((data) => { - expect(data).toBeDefined() - }) - }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); test('AddOrUpdateProductLines', async () => { await creditManagement .addOrUpdateProductLines({ - invoiceKey: 'd42', - article: [] + invoiceKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + articles: [ + { + type: 'Regular', + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + totalVat: 12, + totalAmount: 123, + quantity: 2, + price: 20.1, + }, + { + type: 'Regular', + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + totalVat: 12, + totalAmount: 123, + quantity: 1, + price: 10.1, + }, + ], }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('resumeDebtorFile', async () => { - await creditManagement.resumeDebtorFile({ debtorFileGuid: 'd42' }).then((data) => { - expect(data).toBeDefined() - }) - }) + await creditManagement + .resumeDebtorFile({ debtorFileGuid: 'd42' }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('pauseDebtorFile', async () => { - await creditManagement.pauseDebtorFile({ debtorFileGuid: 'd42' }).then((data) => { - expect(data).toBeDefined() - }) - }) + await creditManagement + .pauseDebtorFile({ debtorFileGuid: 'd42' }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('addOrUpdateDebtor', async () => { + await creditManagement + .addOrUpdateDebtor({ + debtor: { + code: 'XXXXXXXX', + }, + person: { + culture: 'nl-NL', + lastName: 'Acceptatie', + }, + }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); test('CreateCombinedInvoice', async () => { - const ideal1 = new Ideal() - const combined = creditManagement.createCombinedInvoice(invoice()) - - await ideal1.combine(combined).pay({ - amountDebit: 10.1, - issuer: 'ABNANL2A' - }) - }) + const combinedInvoice = creditManagement.createCombinedInvoice(creditManagementTestInvoice()); + buckarooClientTest + .method('sepadirectdebit') + .combine(combinedInvoice.data) + .pay({ + iban: 'NLXXTESTXXXXXXXXXX', + bic: 'XXXXXXXXX', + mandateReference: 'XXXXXXXXXXXXXXX', + mandateDate: '2020-01-01', + collectDate: '2020-07-03', + amountDebit: 100, + customer: { + name: 'Test Acceptatie', + }, + invoice: uniqid('TestInvoice'), + }) + .request() + .then((data) => { + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); test('CreatePaymentPlan', async () => { await creditManagement .createPaymentPlan({ - dossierNumber: '', - includedInvoiceKey: '', - initialAmount: 0, - installmentAmount: 0, - installmentCount: 0, + description: 'Payment in two intstallments', + includedInvoiceKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + dossierNumber: 'XXXXXXXXXXXXXXXXXXXXXX', + installmentCount: 2, + initialAmount: 100, + startDate: '2030-01-01', interval: CreditManagementInstallmentInterval.MONTH, - paymentPlanCostAmount: 0, - paymentPlanCostAmountVat: 0, - recipientEmail: '', - startDate: '' + paymentPlanCostAmount: 3.5, + paymentPlanCostAmountVat: 1.2, + recipientemail: 'test@buckaroo.nl', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) - test('Specifications', async () => { - // + expect(data.isValidationFailure()).toBeTruthy(); + }); + }); + test('pauseInvoice', async () => { await creditManagement .pauseInvoice({ - invoice: 'd42' + invoice: uniqid(), }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) -}) - -const invoice = (append: object = {}): IInvoice => { + expect(data).toBeDefined(); + }); + }); +}); +export const creditManagementTestInvoice = (append: object = {}): IInvoice => { return { - code: 'Billingtest101', - // invoiceNumber: 'd42', - description: 'buckaroo_schema_test_PDF', - currency: 'EUR', + invoice: uniqid(), applyStartRecurrent: false, invoiceAmount: 10, invoiceAmountVAT: 1, invoiceDate: '2022-01-01', dueDate: '2030-01-01', - schemeKey: 'ezf7xn', - // maxStepIndex: 1, + schemeKey: 'XXXXXX', + maxStepIndex: 1, allowedServices: 'ideal,mastercard', debtor: { - code: 'johnsmith4' + code: 'XXXXXXXX', }, - email: { email: 'youremail@example.nl' }, + email: 'test@buckaroo.nl', phone: { - mobile: '06198765432', - landline: '06198765432', - fax: '06198765432' + mobile: '0612345678', }, person: { culture: 'nl-NL', @@ -141,46 +249,25 @@ const invoice = (append: object = {}): IInvoice => { initials: 'JS', firstName: 'Test', lastNamePrefix: 'Jones', - lastName: 'Aflever', + lastName: 'Acceptatie', gender: Gender.MALE, - birthDate: '', - placeOfBirth: '' }, company: { culture: 'nl-NL', - name: 'My Company Corporation', + name: 'Buckaroo B.V.', vatApplicable: true, - vatNumber: 'NL140619562B01', - chamberOfCommerce: '' + vatNumber: 'NLXXXXXXXXXXB01', + chamberOfCommerce: 'XXXXXX41', }, address: { - street: 'Hoofdtraat', - houseNumber: '90', - houseNumberSuffix: 'A', - postalCode: '8441ER', + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', city: 'Heerenveen', state: 'Friesland', - country: 'NL' + country: 'NL', }, - productLine: [ - { - discountPercentage: 0, - productGroupName: '', - productGroupOrderIndex: 0, - productOrderIndex: 0, - quantity: 0, - totalAmount: 0, - totalAmountExVat: 0, - totalDiscount: 0, - totalVat: 0, - type: 'Regular', - unitOfMeasurement: '', - vatPercentage: 0, - pricePerUnit: 0, - productName: '324' - - } - ], - ...append - } -} + ...append, + }; +}; diff --git a/tests/PaymentMethods/EPS.test.js b/tests/PaymentMethods/EPS.test.js new file mode 100644 index 00000000..b8d1c150 --- /dev/null +++ b/tests/PaymentMethods/EPS.test.js @@ -0,0 +1,25 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('eps'); +describe('Testing Eps methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 10.1 + }) + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); + test('Refund', async () => { + method + .refund({ + amountCredit: 10.1, + originalTransactionKey: '1234567890' + }) + .request() + .then((response) => { + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/EPS.test.ts b/tests/PaymentMethods/EPS.test.ts new file mode 100644 index 00000000..b24d018a --- /dev/null +++ b/tests/PaymentMethods/EPS.test.ts @@ -0,0 +1,28 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; + +const method = buckarooClientTest.method('eps'); +describe('Testing Eps methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 100, + }) + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); + test('Refund', async () => { + method + .refund({ + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((response) => { + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Emandate.test.js b/tests/PaymentMethods/Emandate.test.js new file mode 100644 index 00000000..019ebebc --- /dev/null +++ b/tests/PaymentMethods/Emandate.test.js @@ -0,0 +1,56 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('emandate'); +describe('Testing Emandates methods', () => { + test('GetIssuerList', async () => { + await method + .issuerList() + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); + test('CreateMandate', async () => { + method + .createMandate({ + debtorReference: 'klant1234', + language: 'nl', + continueOnIncomplete: true, + purchaseId: 'purchaseid1234', + sequenceType: 0 + }) + .request() + .then((response) => { + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); + test('GetStatus', async () => { + method + .status({ mandateId: '1DC014098EC5C1F40AD803B83A425153BBC' }) + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); + test('ModifyMandate', async () => { + method + .modifyMandate({ + originalMandateId: '1DC014098EC5C1F40AD803B83A425153BBC', + continueOnIncomplete: true + }) + .request() + .then((response) => { + expect(response.isFailed()).toBeTruthy(); + }); + }); + test('CancelMandate', async () => { + method + .cancelMandate({ + mandateId: '1DC014098EC5C1F40AD803B83A425153BBC', + purchaseId: 'purchaseid1234' + }) + .request() + .then((response) => { + expect(response.isValidationFailure()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Emandate.test.ts b/tests/PaymentMethods/Emandate.test.ts index 5f8cc761..84accb72 100644 --- a/tests/PaymentMethods/Emandate.test.ts +++ b/tests/PaymentMethods/Emandate.test.ts @@ -1,51 +1,59 @@ -require('../BuckarooClient.test') -import Emandates from '../../src/PaymentMethods/Emandates' +import buckarooClientTest from '../BuckarooClient.test'; +import { ServiceCode } from '../../src'; -const method = new Emandates() +const method = buckarooClientTest.method('emandate'); describe('Testing Emandates methods', () => { test('GetIssuerList', async () => { - method.issuerList().then((response) => { - expect(response.data).toBeDefined() - }) - }) + await method + .issuerList() + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); test('CreateMandate', async () => { method .createMandate({ - debtorReference: 'klant1234', + debtorReference: 'XXXXXXXXX', language: 'nl', - continueOnIncomplete: 1, - purchaseId: 'purchaseid1234', - sequenceType: 0 + continueOnIncomplete: true, + purchaseId: 'XXXXXXXXXXXXXX', + sequenceType: 0, }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }).catch((err)=>{ - console.log(err); - }) - }) + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); test('GetStatus', async () => { - method.status({ mandateId: '1DC014098EC5C1F40AD803B83A425153BBC' }).then((response) => { - expect(response.data).toBeDefined() - }) - }) + method + .status({ mandateId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }) + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); test('ModifyMandate', async () => { method .modifyMandate({ - originalMandateId: '1DC014098EC5C1F40AD803B83A425153BBC', - continueOnIncomplete: 1 + originalMandateId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + continueOnIncomplete: true, }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) + expect(response.isFailed()).toBeTruthy(); + }); + }); test('CancelMandate', async () => { method + .setServiceCode('emandateb2b' as ServiceCode) .cancelMandate({ - mandateId: '1DC014098EC5C1F40AD803B83A425153BBC', - purchaseId: 'purchaseid1234' + mandateId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + purchaseId: 'XXXXXXXXXXXXXX', }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) -}) + expect(response.isValidationFailure()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Giftcard.test.js b/tests/PaymentMethods/Giftcard.test.js new file mode 100644 index 00000000..d05c2d33 --- /dev/null +++ b/tests/PaymentMethods/Giftcard.test.js @@ -0,0 +1,37 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('boekenbon'); +describe('GiftCard methods', () => { + test('Pay', async () => { + const responsePay = await method + .pay({ + amountDebit: 10, + intersolveCardnumber: '0000000000000000001', + intersolvePIN: '500' + }) + .request(); + expect(responsePay.isSuccess()).toBeTruthy(); + const responseRemainderPay = await buckarooClientTest + .method('ideal') + .payRemainder({ + amountDebit: 10.1, + issuer: 'ABNANL2A', + invoice: responsePay.data.invoice, + originalTransactionKey: responsePay.data.relatedTransactions[0].relatedTransactionKey + }) + .request(); + expect(responseRemainderPay.isPendingProcessing()).toBeTruthy(); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 5, + originalTransactionKey: '9F99B530DA5449EB919D27351D28BDF2', + email: '', + lastName: '' + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Giftcard.test.ts b/tests/PaymentMethods/Giftcard.test.ts index a9c0dde1..c720a0da 100644 --- a/tests/PaymentMethods/Giftcard.test.ts +++ b/tests/PaymentMethods/Giftcard.test.ts @@ -1,28 +1,41 @@ -require('../BuckarooClient.test') -import GiftCard from '../../src/PaymentMethods/GiftCard/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new GiftCard() +const method = buckarooClientTest.method('boekenbon'); describe('GiftCard methods', () => { test('Pay', async () => { - await method + const responsePay = await method .pay({ - amountDebit: 10, - name: 'GiftCard' + amountDebit: 100, + intersolveCardnumber: '0000000000000000001', + intersolvePIN: '1000', }) - .then((data) => { - expect(data).toBeDefined() + .request(); + expect(responsePay.isSuccess()).toBeTruthy(); + const responseRemainderPay = await buckarooClientTest + .method('ideal') + .payRemainder({ + amountDebit: 100, + issuer: 'ABNANL2A', + invoice: responsePay.data.invoice, + originalTransactionKey: responsePay.data.relatedTransactions[0].relatedTransactionKey, }) - }) + .request(); + expect(responseRemainderPay.isPendingProcessing()).toBeTruthy(); + }); test('Refund', async () => { await method .refund({ - amountCredit: 5, - name: 'GiftCard', - originalTransactionKey: 'F397DA6A251645F8BDD81547B5005B4B' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + email: 'test@buckaroo.nl', + lastName: 'Acceptatie', }) + .request() .then((data) => { - expect(data).toBeDefined() - }) - }) -}) + expect(data.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/GiroPay.test.js b/tests/PaymentMethods/GiroPay.test.js new file mode 100644 index 00000000..8fb80d49 --- /dev/null +++ b/tests/PaymentMethods/GiroPay.test.js @@ -0,0 +1,28 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src/Utils/Functions'; +const method = buckarooClientTest.method('giropay'); +describe('Testing Giropay methods', () => { + test('Pay', async () => { + await method + .pay({ + bic: 'GENODETT488', + amountDebit: 10.1 + }) + .request() + .then((response) => { + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 10, + invoice: uniqid(), + originalTransactionKey: '2D04704995B74D679AACC59F87XXXXXX' + }) + .request() + .then((response) => { + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/GiroPay.test.ts b/tests/PaymentMethods/GiroPay.test.ts index f888f133..acf2ede8 100644 --- a/tests/PaymentMethods/GiroPay.test.ts +++ b/tests/PaymentMethods/GiroPay.test.ts @@ -1,28 +1,29 @@ -require('../BuckarooClient.test') -import GiroPay from '../../src/PaymentMethods/Giropay/index' - -const method = new GiroPay() +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; +const method = buckarooClientTest.method('giropay'); describe('Testing Giropay methods', () => { test('Pay', async () => { await method .pay({ - bic: '', - costumerIBAN: '', - amountDebit: 0 + bic: 'XXXXXXXXX', + amountDebit: 100, }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 0, - originalTransactionKey: '' + amountCredit: 0.01, + invoice: uniqid(), + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) -}) + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Ideal.test.js b/tests/PaymentMethods/Ideal.test.js new file mode 100644 index 00000000..4842f589 --- /dev/null +++ b/tests/PaymentMethods/Ideal.test.js @@ -0,0 +1,55 @@ +import { getIPAddress, uniqid } from '../../src/Utils/Functions'; +import buckarooClientTest from '../BuckarooClient.test'; +const ideal = buckarooClientTest.method('ideal'); +describe('testing Ideal methods', () => { + test('Issuers', () => { + return ideal.issuers().then((response) => { + expect(Array.isArray(response)).toBeTruthy(); + }); + }); + test('Pay Simple Payload', () => { + return ideal + .pay({ + amountDebit: 10.1, + issuer: 'ABNANL2A', + continueOnIncomplete: false, + additionalParameters: { + initiated_by_magento: 1, + service_action: 'something' + } + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', () => { + return ideal + .refund({ + order: uniqid(), + invoice: uniqid(), + originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1', + amountCredit: 4.23, + clientIP: getIPAddress(), + additionalParameters: { + initiated_by_magento: '1', + service_action: 'something' + } + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('InstantRefund', () => { + return ideal + .instantRefund({ + amountCredit: 4.23, + originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1' + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Ideal.test.ts b/tests/PaymentMethods/Ideal.test.ts index e2da713e..1b0b512c 100644 --- a/tests/PaymentMethods/Ideal.test.ts +++ b/tests/PaymentMethods/Ideal.test.ts @@ -1,58 +1,57 @@ -require('../BuckarooClient.test') -import { uniqid } from '../../src/Utils/Functions' -import Ideal from '../../src/PaymentMethods/Ideal/index' +import { getIPAddress, uniqid } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; -const ideal = new Ideal() +const ideal = buckarooClientTest.method('ideal'); describe('testing Ideal methods', () => { - test('Issuers', async () => { - await ideal.issuers().then((response) => { - expect(Array.isArray(response)).toBeTruthy() - }) - }) - test('Pay Simple Payload', async () => { - await ideal + test('Issuers', () => { + return ideal.issuers().then((response) => { + expect(Array.isArray(response)).toBeTruthy(); + }); + }); + test('Pay Simple Payload', () => { + return ideal .pay({ - amountDebit: 10.1, + amountDebit: 100, issuer: 'ABNANL2A', - clientIP: { - address: '123.456.789.123', - type: 0 - }, + continueOnIncomplete: false, additionalParameters: { initiated_by_magento: 1, - service_action: 'something' - } + service_action: 'something', + }, }) + .request() .then((data) => { - expect(data.isPendingProcessing()).toBeTruthy() - }) - }) - test('Refund', async () => { - await ideal + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', () => { + return ideal .refund({ order: uniqid(), invoice: uniqid(), - originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1', - amountCredit: 4.23, - clientIP: { - address: '123.456.789.123', - type: 0 - }, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountCredit: 0.01, + clientIP: getIPAddress(), additionalParameters: { initiated_by_magento: '1', - service_action: 'something' - } + service_action: 'something', + }, }) + .request() .then((data) => { - expect(data).toBeDefined() + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('InstantRefund', () => { + return ideal + .instantRefund({ + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) - }) - test('InstantRefund', async () => { - await ideal.instantRefund({ - amountCredit: 4.23, - originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1', - }).then((data) => { - expect(data).toBeDefined() - }) - }) -}) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/IdealQR.test.js b/tests/PaymentMethods/IdealQR.test.js new file mode 100644 index 00000000..db67b992 --- /dev/null +++ b/tests/PaymentMethods/IdealQR.test.js @@ -0,0 +1,31 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('idealqr'); +describe('Testing IdealQR methods', () => { + test('Pay', async () => { + await method + .generate({ + description: 'Test purchase', + returnURL: 'https://buckaroo.dev/return', + returnURLCancel: 'https://buckaroo.dev/cancel', + returnURLError: 'https://buckaroo.dev/error', + returnURLReject: 'https://buckaroo.dev/reject', + minAmount: 0.1, + maxAmount: 10.0, + imageSize: 2000, + purchaseId: 'Testpurchase123', + isOneOff: false, + amount: 1.0, + amountIsChangeable: true, + expiration: '2030-09-30', + isProcessing: false, + additionalParameters: { + initiated_by_magento: '1', + service_action: 'something' + } + }) + .request() + .then((response) => { + expect(response.isSuccess()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/IdealQR.test.ts b/tests/PaymentMethods/IdealQR.test.ts index b997db14..7ffeab00 100644 --- a/tests/PaymentMethods/IdealQR.test.ts +++ b/tests/PaymentMethods/IdealQR.test.ts @@ -1,25 +1,32 @@ -require('../BuckarooClient.test') -import IDealQR from '../../src/PaymentMethods/iDealQR' +import buckarooClientTest from '../BuckarooClient.test'; -const method = new IDealQR() - -describe('Testing iDealQR methods', () => { +const method = buckarooClientTest.method('idealqr'); +describe('Testing IdealQR methods', () => { test('Pay', async () => { - method + await method .generate({ - amount: 0, - amountDebit: 0, - amountIsChangeable: false, - Description: '', - expiration: '', - imageSize: 0, + description: 'Test purchase', + returnURL: 'https://buckaroo.dev/return', + returnURLCancel: 'https://buckaroo.dev/cancel', + returnURLError: 'https://buckaroo.dev/error', + returnURLReject: 'https://buckaroo.dev/reject', + minAmount: 0.1, + maxAmount: 10.0, + imageSize: 2000, + purchaseId: 'Testpurchase123', isOneOff: false, - maxAmount: 0, - minAmount: 0, - purchaseId: '' + amount: 1.0, + amountIsChangeable: true, + expiration: '2030-09-30', + isProcessing: false, + additionalParameters: { + initiated_by_magento: '1', + service_action: 'something', + }, }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) -}) + expect(response.isSuccess()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Idin.test.ts b/tests/PaymentMethods/Idin.test.ts new file mode 100644 index 00000000..711a15f1 --- /dev/null +++ b/tests/PaymentMethods/Idin.test.ts @@ -0,0 +1,38 @@ +import buckarooClientTest from '../BuckarooClient.test'; + +const method = buckarooClientTest.method('idin'); + +describe('Idin methods', () => { + test('Verify', async () => { + await method + .verify({ + issuer: 'BANKNL2Y', + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + + test('Identify', async () => { + await method + .identify({ + issuer: 'BANKNL2Y', + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + + test('Login', async () => { + await method + .login({ + issuer: 'BANKNL2Y', + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); +}); \ No newline at end of file diff --git a/tests/PaymentMethods/In3.test.js b/tests/PaymentMethods/In3.test.js new file mode 100644 index 00000000..3c17c00c --- /dev/null +++ b/tests/PaymentMethods/In3.test.js @@ -0,0 +1,105 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src/Utils/Functions'; +import RecipientCategory from '../../src/Constants/RecipientCategory'; +const in3 = buckarooClientTest.method('In3'); +describe('Testing In3 methods', () => { + test('Pay', async () => { + await in3 + .pay(payload) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await in3 + .refund({ + amountCredit: 42, + originalTransactionKey: '', + merchantImageUrl: '', + summaryImageUrl: '', + articles: [] + }) + .request() + .then((data) => { + expect(data.isSuccess()).toBeFalsy(); + }); + }); +}); +const payload = { + amountDebit: 52.3, + description: 'in3 pay', + order: uniqid(), + invoice: uniqid(), + clientIP: '127.0.0.1', + billing: { + recipient: { + category: RecipientCategory.PERSON, + initials: 'J', + firstName: 'John', + lastName: 'Dona', + birthDate: '1990-01-01', + customerNumber: '12345', + companyName: 'Buckaroo', + chamberOfCommerce: '123456' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '13', + houseNumberAdditional: 'a', + zipcode: '1234AB', + city: 'Heerenveen', + country: 'NL' + }, + phone: { + mobile: '0698765433' + }, + email: 'test@buckaroo.nl' + }, + shipping: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'J', + firstName: 'John', + lastName: 'Dona', + chamberOfCommerce: '123456' + }, + address: { + street: 'Kalverstraat', + houseNumber: '13', + houseNumberAdditional: 'b', + zipcode: '4321EB', + city: 'Amsterdam', + country: 'NL' + } + }, + articles: [ + { + identifier: 'Articlenumber1', + type: 'Physical', + description: 'Blue Toy Car', + category: 'test product', + vatPercentage: 21, + quantity: 2, + price: 20.1 + }, + { + identifier: 'Articlenumber2', + type: 'Physical', + description: 'Red Toy Car', + category: 'test product', + vatPercentage: 21, + quantity: 1, + price: 10.1 + }, + { + identifier: 'USPShippingID', + type: 'Physical', + description: 'UPS', + category: 'test product', + vatPercentage: 21, + quantity: 1, + price: 2 + } + ] +}; diff --git a/tests/PaymentMethods/In3.test.ts b/tests/PaymentMethods/In3.test.ts index 1e1ee3ac..a80c10cb 100644 --- a/tests/PaymentMethods/In3.test.ts +++ b/tests/PaymentMethods/In3.test.ts @@ -1,57 +1,106 @@ -import In3 from '../../src/PaymentMethods/In3' -import Gender from '../../src/Constants/Gender' -import RecipientCategory from '../../src/Constants/RecipientCategory' +import buckarooClientTest from '../BuckarooClient.test'; +import { getIPAddress, RecipientCategory, uniqid } from '../../src'; +import { IPay } from '../../src/PaymentMethods/In3/Models/Pay'; -require('../BuckarooClient.test') - -const in3 = new In3() +const in3 = buckarooClientTest.method('In3'); describe('Testing In3 methods', () => { test('Pay', async () => { await in3 - .payInInstallments({ - clientIP: '127.0.0.0', - description: 'fdsfsdfdsf', - subtotalLine: [], - amountDebit: 32, - customerType: RecipientCategory.COMPANY, - invoiceDate: '22-01-2018', - person: { - gender: Gender.FEMALE, - culture: 'nl-NL', - initials: 'J.S.', - lastName: 'Aflever', - birthDate: '1990-01-01' - }, - company: { - name: 'My Company B.V.', - chamberOfCommerce: '123456' - }, - address: { - street: 'Hoofdstraat', - houseNumber: 2, - houseNumberSuffix: 'a', - zipCode: '8441EE', - city: 'Heerenveen', - country: 'NL' - }, - email: { - email: 'test@buckaroo.nl' - }, - phone: { - phone: '0612345678' - }, - productLine: [ - { - code: '64381664f2f8b', - price: 10, - quantity: 1, - name: 'Blue Toy Car' - } - ], - }) - .then((response) => { - expect(response.data).toBeDefined() + .pay(payload) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await in3 + .refund({ + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) - }) -}) + .request() + .then((data) => { + expect(data.isSuccess()).toBeFalsy(); + }); + }); +}); + +const payload: IPay = { + amountDebit: 100, + description: 'in3 pay', + order: uniqid(), + invoice: uniqid(), + clientIP: getIPAddress(), + billing: { + recipient: { + category: RecipientCategory.PERSON, + initials: 'TA', + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '1990-01-01', + customerNumber: 'XXXXX', + companyName: 'Buckaroo B.V.', + chamberOfCommerce: 'XXXXXX41', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + phone: { + mobile: '0612345678', + }, + email: 'test@buckaroo.nl', + }, + shipping: { + recipient: { + category: RecipientCategory.PERSON, + careOf: 'J', + firstName: 'Test', + lastName: 'Acceptatie', + chamberOfCommerce: 'XXXXXX41', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + }, + articles: [ + { + identifier: 'Articlenumber1', + type: 'Physical', + description: 'Blue Toy Car', + category: 'test product', + vatPercentage: 21, + quantity: 2, + price: 25, + }, + { + identifier: 'Articlenumber2', + type: 'Physical', + description: 'Red Toy Car', + category: 'test product', + vatPercentage: 21, + quantity: 1, + price: 25, + }, + { + identifier: 'USPShippingID', + type: 'Physical', + description: 'UPS', + category: 'test product', + vatPercentage: 21, + quantity: 1, + price: 25, + }, + ], +}; diff --git a/tests/PaymentMethods/In3Old.test.js b/tests/PaymentMethods/In3Old.test.js new file mode 100644 index 00000000..2100e257 --- /dev/null +++ b/tests/PaymentMethods/In3Old.test.js @@ -0,0 +1,77 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import Gender from '../../src/Constants/Gender'; +import RecipientCategory from '../../src/Constants/RecipientCategory'; +const capayable = buckarooClientTest.method('capayable'); +describe('Testing capayable methods', () => { + test('Pay', async () => { + await capayable + .pay(paymentPayload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await capayable + .refund({ + amountCredit: 42, + originalTransactionKey: '' + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('PayInInstallments', async () => { + await capayable + .payInInstallments(paymentPayload) + .request() + .then((response) => { + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); +}); +const paymentPayload = { + clientIP: '127.0.0.0', + description: 'fdsfsdfdsf', + amountDebit: 32, + customerType: RecipientCategory.COMPANY, + invoiceDate: '22-01-2018', + customer: { + gender: Gender.FEMALE, + culture: 'nl-NL', + initials: 'J.S.', + lastName: 'Aflever', + birthDate: '1990-01-01' + }, + company: { + companyName: 'My Company B.V.', + chamberOfCommerce: '123456' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '2', + houseNumberSuffix: 'a', + zipcode: '8441EE', + city: 'Heerenveen', + country: 'NL' + }, + email: 'test@buckaroo.nl', + phone: { + mobile: '0612345678' + }, + articles: [ + { + identifier: '64381664f2f8b', + price: 10, + quantity: 1, + description: 'Blue Toy Car' + } + ], + subtotals: [ + { + name: 'Verzendkosten', + value: 2 + } + ] +}; diff --git a/tests/PaymentMethods/In3Old.test.ts b/tests/PaymentMethods/In3Old.test.ts new file mode 100644 index 00000000..b8d03976 --- /dev/null +++ b/tests/PaymentMethods/In3Old.test.ts @@ -0,0 +1,80 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { Gender, getIPAddress, RecipientCategory, uniqid } from '../../src'; + +const capayable = buckarooClientTest.method('capayable'); + +describe('Testing capayable methods', () => { + test('Pay', async () => { + await capayable + .pay(paymentPayload) + .request() + .then((data) => { + expect(data.isSuccess()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await capayable + .refund({ + invoice: uniqid(), + amountCredit: paymentPayload.amountDebit, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((data) => { + expect(data.isFailed()).toBeTruthy(); + }); + }); + test('PayInInstallments', async () => { + await capayable + .payInInstallments(paymentPayload) + .request() + .then((response) => { + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); +}); + +const paymentPayload = { + clientIP: getIPAddress(), + description: 'Test', + amountDebit: 100, + customerType: RecipientCategory.COMPANY, + invoiceDate: '22-01-2018', + customer: { + gender: Gender.FEMALE, + culture: 'nl-NL', + initials: 'TA', + lastName: 'Acceptatie', + birthDate: '1990-01-01', + }, + company: { + companyName: 'Buckaroo B.V.', + chamberOfCommerce: 'XXXXXX41', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberSuffix: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + email: 'test@buckaroo.nl', + phone: { + mobile: '0612345678', + }, + articles: [ + { + identifier: '64381664f2f8b', + price: 10, + quantity: 1, + description: 'Blue Toy Car', + }, + ], + subtotals: [ + { + name: 'Verzendkosten', + value: 2, + }, + ], +}; diff --git a/tests/PaymentMethods/KBC.test.js b/tests/PaymentMethods/KBC.test.js new file mode 100644 index 00000000..dac67ae6 --- /dev/null +++ b/tests/PaymentMethods/KBC.test.js @@ -0,0 +1,25 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('KBCPaymentButton'); +describe('Testing KBC methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 10 + }) + .request() + .then((response) => { + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + method + .refund({ + amountCredit: 10, + originalTransactionKey: 'B5675356904444F3965C33D280591C74' + }) + .request() + .then((response) => { + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/KBC.test.ts b/tests/PaymentMethods/KBC.test.ts index ff393cb4..f25e6e4b 100644 --- a/tests/PaymentMethods/KBC.test.ts +++ b/tests/PaymentMethods/KBC.test.ts @@ -1,26 +1,29 @@ -require('../BuckarooClient.test') -import KBC from '../../src/PaymentMethods/KBC' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new KBC() +const method = buckarooClientTest.method('KBCPaymentButton'); describe('Testing KBC methods', () => { test('Pay', async () => { await method .pay({ - amountDebit: 10 + amountDebit: 100, }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { method .refund({ - amountCredit: 0, - originalTransactionKey: 'B5675356904444F3965C33D280591C74' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) -}) + expect(response.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Klarna.test.js b/tests/PaymentMethods/Klarna.test.js new file mode 100644 index 00000000..45e9bd2c --- /dev/null +++ b/tests/PaymentMethods/Klarna.test.js @@ -0,0 +1,82 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src/Utils/Functions'; +import RecipientCategory from '../../src/Constants/RecipientCategory'; +const klarna = buckarooClientTest.method('klarna'); +describe('Testing Klarna methods', () => { + test('Pay', async () => { + await klarna + .pay(payload) + .request() + .then((res) => { + expect(res.isPendingProcessing()).toBeTruthy(); + }); + }); + test('PayInInstallments', async () => { + await klarna + .payInInstallments(payload) + .request() + .then((res) => { + expect(res).toBeDefined(); + }); + }); +}); +let payload = { + amountDebit: 50.3, + invoice: uniqid(), + order: uniqid(), + billing: { + recipient: { + category: RecipientCategory.PERSON, + gender: 'female', + firstName: 'John', + lastName: 'Do', + birthDate: '1990-01-01' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '13', + houseNumberAdditional: 'a', + zipcode: '1234AB', + city: 'Heerenveen', + country: 'NL' + }, + phone: { + mobile: '0698765433' + }, + email: 'test@buckaroo.nl' + }, + shipping: { + recipient: { + category: RecipientCategory.COMPANY, + gender: 'male', + firstName: 'John', + lastName: 'Do', + birthDate: '1990-01-01' + }, + address: { + street: 'Kalverstraat', + houseNumber: '13', + houseNumberAdditional: 'b', + zipcode: '4321EB', + city: 'Amsterdam', + country: 'NL' + }, + email: 'test@buckaroo.nl' + }, + articles: [ + { + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + quantity: 2, + price: 20.1 + }, + { + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + quantity: 1, + price: 10.1 + } + ] +}; diff --git a/tests/PaymentMethods/Klarna.test.ts b/tests/PaymentMethods/Klarna.test.ts index c49b500c..4d453789 100644 --- a/tests/PaymentMethods/Klarna.test.ts +++ b/tests/PaymentMethods/Klarna.test.ts @@ -1,62 +1,87 @@ -import { IPay } from '../../src/PaymentMethods/Klarna/Models/Pay' - -require('../BuckarooClient.test') -import Klarna from '../../src/PaymentMethods/Klarna/index' -import { uniqid } from '../../src/Utils/Functions' - -const klarna = new Klarna() +import buckarooClientTest from '../BuckarooClient.test'; +import { IPay } from '../../src/PaymentMethods/Klarna/Models/Pay'; +import { RecipientCategory, uniqid } from '../../src'; +const klarna = buckarooClientTest.method('klarna'); describe('Testing Klarna methods', () => { test('Pay', async () => { - await klarna.pay(payload).then((res) => { - expect(res).toBeDefined() - }) - }) - test('Refund', async () => { await klarna - .refund({ - amountCredit: 21, - originalTransactionKey: '' - }) + .pay(payload) + .request() + .then((res) => { + expect(res.isPendingProcessing()).toBeTruthy(); + }); + }); + test('PayInInstallments', async () => { + const clonedPayload = JSON.parse(JSON.stringify(payload)); + clonedPayload.currency = 'GBP'; + clonedPayload.billing.address.country = 'GB'; + await klarna + .payInInstallments(clonedPayload) + .request() .then((res) => { - expect(res).toBeDefined() - }) - }) -}) + expect(res).toBeDefined(); + }); + }); +}); let payload: IPay = { - order: uniqid(), - amountDebit: 50.3, + amountDebit: 100, invoice: uniqid(), - additionalParameters: undefined, - article: [], - billingCustomer: { - city: '', - country: '', - email: '', - firstName: '', - lastName: '', - phone: '', - postalCode: '', - street: '', - streetNumber: '', - streetNumberAdditional: '' + order: uniqid(), + billing: { + recipient: { + category: RecipientCategory.PERSON, + gender: 'female', + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '1990-01-01', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + phone: { + mobile: '0612345678', + }, + email: 'test@buckaroo.nl', + }, + shipping: { + recipient: { + category: RecipientCategory.COMPANY, + gender: 'male', + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '1990-01-01', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + email: 'test@buckaroo.nl', }, - clientIP: undefined, - culture: '', - currency: '', - customParameters: undefined, - description: '', - originalTransactionKey: '', - originalTransactionReference: '', - pushURL: '', - pushURLFailure: '', - returnURL: '', - returnURLCancel: '', - returnURLError: '', - returnURLReject: '', - servicesExcludedForClient: '', - servicesSelectableByClient: '', - shippingCustomer: undefined, - startRecurrent: false -} + articles: [ + { + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + quantity: 1, + price: 50, + }, + { + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + quantity: 1, + price: 50, + }, + ], +}; diff --git a/tests/PaymentMethods/KlarnaKp.test.js b/tests/PaymentMethods/KlarnaKp.test.js new file mode 100644 index 00000000..30022eae --- /dev/null +++ b/tests/PaymentMethods/KlarnaKp.test.js @@ -0,0 +1,87 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import gender from '../../src/Constants/Gender'; +const klarnaKp = buckarooClientTest.method('klarnakp'); +describe('KlarnaKp', () => { + test('Pay', async () => { + await klarnaKp + .pay({ + amountDebit: 50.3, + reservationNumber: '2377577452' + }) + .request() + .then((info) => { + expect(info.isFailed()).toBeTruthy(); + }); + }); + test('Reserve', async () => { + await klarnaKp + .reserve({ + gender: gender.MALE, + operatingCountry: 'NL', + pno: '01011990', + billing: { + recipient: { + firstName: 'John', + lastName: 'Do' + }, + address: { + street: 'Neherkade', + houseNumber: '1', + zipcode: '2521VA', + city: 'Gravenhage', + country: 'NL' + }, + phone: { + mobile: '0612345678' + }, + email: 'youremail@example.nl' + }, + shipping: { + recipient: { + firstName: 'John', + lastName: 'Do' + }, + address: { + street: 'Rosenburglaan', + houseNumber: '216', + zipcode: '4385 JM', + city: 'Vlissingen', + country: 'NL' + }, + email: 'test@buckaroo.nl' + }, + articles: [ + { + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + quantity: 2, + price: 20.1 + }, + { + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + quantity: 1, + price: 10.1 + } + ], + additionalParameters: { + initiated_by_magento: '1', + service_action: 'something' + } + }) + .request() + .then((info) => { + expect(info.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Cancel', async () => { + await klarnaKp + .cancel({}) + .request() + .then((info) => { + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/KlarnaKp.test.ts b/tests/PaymentMethods/KlarnaKp.test.ts index b23a20dc..e8735dab 100644 --- a/tests/PaymentMethods/KlarnaKp.test.ts +++ b/tests/PaymentMethods/KlarnaKp.test.ts @@ -1,11 +1,72 @@ -require('../BuckarooClient.test') -import KlarnaKp from '../../src/PaymentMethods/KlarnaKP' -const klarnaKp = new KlarnaKp() -describe('KlarnaKp', () => { - test('reserve', async () => { +import buckarooClientTest from '../BuckarooClient.test'; +import { Gender } from '../../src'; - await klarnaKp.reserve({}).then((info) => { - expect(info).toBeDefined() - }) - }) -}) +const klarnaKp = buckarooClientTest.method('klarnakp'); + +describe('KlarnaKp', () => { + test('Pay', async () => { + await klarnaKp + .pay({ + amountDebit: 100, + reservationNumber: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((info) => { + expect(info.isFailed()).toBeTruthy(); + }); + }); + test('Reserve', async () => { + await klarnaKp + .reserve({ + gender: Gender.MALE, + operatingCountry: 'NL', + pno: '01011990', + billing: { + recipient: { + firstName: 'Test', + lastName: 'Acceptatie', + }, + address: { + street: 'Hoofdstraat', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + phone: { + mobile: '0612345678', + }, + email: 'test@buckaroo.nl', + }, + articles: [ + { + identifier: 'Articlenumber1', + description: 'Blue Toy Car', + vatPercentage: 21, + quantity: 2, + price: 20.1, + }, + { + identifier: 'Articlenumber2', + description: 'Red Toy Car', + vatPercentage: 21, + quantity: 1, + price: 10.1, + }, + ], + }) + .request() + .then((info) => { + expect(info.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Cancel', async () => { + await klarnaKp + .cancel({ + reservationNumber: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((info) => { + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Marketplaces.test.js b/tests/PaymentMethods/Marketplaces.test.js new file mode 100644 index 00000000..16d27038 --- /dev/null +++ b/tests/PaymentMethods/Marketplaces.test.js @@ -0,0 +1,51 @@ +require('../BuckarooClient.test'); +import Marketplaces from '../../src/PaymentMethods/Marketplaces'; +import Ideal from '../../src/PaymentMethods/Ideal'; +const marketplaces = new Marketplaces(); +const ideal = new Ideal(); +describe('Testing Marketplaces methods', () => { + test('Split', async () => { + marketplaces.split({ + daysUntilTransfer: 2, + marketplace: { + amount: 10, + description: '' + }, + seller: [ + { + accountId: '789C60F316D24B088ACD471', + amount: 50, + description: '' + }, + { + accountId: '369C60F316D24B088ACD238', + amount: 35, + description: '' + } + ] + }); + ideal + .combine(marketplaces) + .pay({ + issuer: 'ABNANL2A', + amountDebit: 95.0 + }) + .then((response) => { + expect(response.data).toBeDefined(); + }); + }); + test('transfer', async () => { + marketplaces.transfer({ originalTransactionKey: 'fwcafgdhgf' }).then((response) => { + expect(response.data).toBeDefined(); + }); + }); + test('refundSupplementary', async () => { + const market = marketplaces.refundSupplementary(); + ideal + .combine(market) + .refund({ originalTransactionKey: 'dasda', amountCredit: 10 }) + .then((response) => { + expect(response.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Marketplaces.test.ts b/tests/PaymentMethods/Marketplaces.test.ts index c2e79a66..a4a9170f 100644 --- a/tests/PaymentMethods/Marketplaces.test.ts +++ b/tests/PaymentMethods/Marketplaces.test.ts @@ -1,52 +1,82 @@ -require('../BuckarooClient.test') -import Marketplaces from '../../src/PaymentMethods/Marketplaces/index' -import Ideal from '../../src/PaymentMethods/Ideal/index' -const marketplaces = new Marketplaces() -const ideal = new Ideal() +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; + +const marketplaces = buckarooClientTest.method('marketplaces'); +const ideal = buckarooClientTest.method('ideal'); describe('Testing Marketplaces methods', () => { test('Split', async () => { - marketplaces.split({ + const marketplacesResponse = marketplaces.split({ + description: 'INV0001', daysUntilTransfer: 2, marketplace: { amount: 10, - description: '' + description: '', }, - seller: [ + sellers: [ { - accountId: '789C60F316D24B088ACD471', + accountId: 'XXXXXXXXXXXXXXXXXXXXXXXX', amount: 50, - description: '' + description: '', }, { - accountId: '369C60F316D24B088ACD238', - amount: 35, - description: '' - } - ] - }) - ideal - .combine(marketplaces) + accountId: 'XXXXXXXXXXXXXXXXXXXXXXXX', + amount: 45, + description: '', + }, + ], + }); + return ideal + .combine(marketplacesResponse.data) .pay({ issuer: 'ABNANL2A', - amountDebit: 95.0 + amountDebit: 100, }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) + expect(response.isValidationFailure()).toBeTruthy(); + }); + }); test('transfer', async () => { - marketplaces.transfer({ originalTransactionKey: 'fwcafgdhgf' }).then((response) => { - expect(response.data).toBeDefined() - }) - }) + marketplaces + .transfer({ + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + marketplace: { + amount: 10, + description: 'INV0001 Commission Marketplace', + }, + sellers: [ + { + accountId: 'XXXXXXXXXXXXXXXXXXXXXXXX', + amount: 50, + description: 'INV001 Payout Make-Up Products BV', + }, + ], + }) + .request() + .then((response) => { + expect(response.isValidationFailure()).toBeTruthy(); + }); + }); test('refundSupplementary', async () => { - const market = marketplaces.refundSupplementary() + const marketplacesResponse = marketplaces.refundSupplementary({ + sellers: [ + { + accountId: 'XXXXXXXXXXXXXXXXXXXXXXXX', + description: 'INV001 Payout Make-Up Products BV', + }, + ], + }); ideal - .combine(market) - .refund({ originalTransactionKey: 'dasda', amountCredit: 10 }) - .then((response) => { - expect(response.data).toBeDefined() + .combine(marketplacesResponse.data) + .refund({ + invoice: uniqid(), + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + amountCredit: 0.01, }) - }) -}) + .request() + .then((response) => { + expect(response.isValidationFailure()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Mbway.test.ts b/tests/PaymentMethods/Mbway.test.ts new file mode 100644 index 00000000..65f0de6e --- /dev/null +++ b/tests/PaymentMethods/Mbway.test.ts @@ -0,0 +1,15 @@ +import buckarooClientTest from '../BuckarooClient.test'; + +const method = buckarooClientTest.method('MBWay'); +describe('Mbway methods', () => { + test('Pay', () => { + return method + .pay({ + amountDebit: 100, + }) + .request() + .then((response) => { + expect(response.isValidationFailure()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Multibanco.test.ts b/tests/PaymentMethods/Multibanco.test.ts new file mode 100644 index 00000000..3d7dd2c8 --- /dev/null +++ b/tests/PaymentMethods/Multibanco.test.ts @@ -0,0 +1,15 @@ +import buckarooClientTest from '../BuckarooClient.test'; + +describe('Multibanco methods', () => { + test('Pay', async () => { + await buckarooClientTest + .method('multibanco') + .pay({ + amountDebit: 100, + }) + .request() + .then((info) => { + expect(info.isValidationFailure()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/NoService.test.ts b/tests/PaymentMethods/NoService.test.ts new file mode 100644 index 00000000..e4110748 --- /dev/null +++ b/tests/PaymentMethods/NoService.test.ts @@ -0,0 +1,21 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; + +const method = buckarooClientTest.method('noservice'); + +describe('NoService methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 100, + invoice: uniqid(), + servicesSelectableByClient: 'ideal,bancontactmrcash,paypal', + servicesExcludedForClient: 'ideal', + continueOnIncomplete: true, + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); +}); \ No newline at end of file diff --git a/tests/PaymentMethods/PayPerEmail.test.js b/tests/PaymentMethods/PayPerEmail.test.js new file mode 100644 index 00000000..829588c6 --- /dev/null +++ b/tests/PaymentMethods/PayPerEmail.test.js @@ -0,0 +1,44 @@ +import Gender from '../../src/Constants/Gender'; +import PayPerEmail from '../../src/PaymentMethods/PayPerEmail'; +require('../BuckarooClient.test'); +const method = new PayPerEmail(); +describe('PayPerEmail methods', () => { + test('paymentInvitation', async () => { + await method + .paymentInvitation({ + invoice: '123456', + amountDebit: 10, + currency: 'EUR', + attachment: '', + additionalParameters: undefined, + clientIP: undefined, + continueOnIncomplete: 1, + culture: '', + customParameters: undefined, + customerEmail: '', + customerFirstName: '', + customerGender: Gender.NOT_APPLICABLE, + customerLastName: '', + description: '', + order: '', + originalTransactionKey: '', + originalTransactionReference: '', + pushURL: '', + pushURLFailure: '', + returnURL: '', + returnURLCancel: '', + returnURLError: '', + returnURLReject: '', + servicesExcludedForClient: '', + servicesSelectableByClient: '', + startRecurrent: false, + email: 's', + expirationDate: '', + merchantSendsEmail: false, + paymentMethodsAllowed: 'ideal' + }) + .then((response) => { + expect(response).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/PayPerEmail.test.ts b/tests/PaymentMethods/PayPerEmail.test.ts index 3da31577..49bde930 100644 --- a/tests/PaymentMethods/PayPerEmail.test.ts +++ b/tests/PaymentMethods/PayPerEmail.test.ts @@ -1,47 +1,30 @@ -import Gender from "../../src/Constants/Gender"; -import PayPerEmail from '../../src/PaymentMethods/PayPerEmail/index' +import { Gender, uniqid } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; -require('../BuckarooClient.test') - -const method = new PayPerEmail() +const method = buckarooClientTest.method('payperemail'); describe('PayPerEmail methods', () => { test('paymentInvitation', async () => { await method .paymentInvitation({ - invoice: '123456', - amountDebit: 10, currency: 'EUR', - attachment: '', - additionalParameters: undefined, - clientIP: undefined, - continueOnIncomplete: 1, - culture: '', - customParameters: undefined, - customerEmail: '', - customerFirstName: '', - customerGender: Gender.NOT_APPLICABLE, - customerLastName: '', - description: '', - order: '', - originalTransactionKey: '', - originalTransactionReference: '', - pushURL: '', - pushURLFailure: '', - returnURL: '', - returnURLCancel: '', - returnURLError: '', - returnURLReject: '', - servicesExcludedForClient: '', - servicesSelectableByClient: '', - startRecurrent: false, - email: 's', - expirationDate: '', + amountDebit: 100, + order: uniqid(), + invoice: uniqid(), merchantSendsEmail: false, - paymentMethodsAllowed: 'ideal' + email: 'test@buckaroo.nl', + expirationDate: '2030-01-01', + paymentMethodsAllowed: 'ideal,mastercard,paypal', + attachment: '', + customer: { + gender: Gender.FEMALE, + firstName: 'Test', + lastName: 'Acceptatie', + }, }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) -}) + expect(response).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Payconiq.test.js b/tests/PaymentMethods/Payconiq.test.js new file mode 100644 index 00000000..8f12e1ef --- /dev/null +++ b/tests/PaymentMethods/Payconiq.test.js @@ -0,0 +1,34 @@ +import buckarooClientTest from "../BuckarooClient.test"; +const payconiq = buckarooClientTest.method("payconiq"); +describe('Payconiq', () => { + test('Pay', async () => { + await payconiq + .pay({ + amountDebit: 50.3, + order: '123456' + }).request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); + test('Refund', async () => { + await payconiq + .refund({ + amountCredit: 50.3, + originalTransactionKey: '123456' + }).request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); + test('InstantRefund', async () => { + await payconiq + .instantRefund({ + amountCredit: 4.23, + originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1' + }).request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Payconiq.test.ts b/tests/PaymentMethods/Payconiq.test.ts index d4e5b48a..38feedbb 100644 --- a/tests/PaymentMethods/Payconiq.test.ts +++ b/tests/PaymentMethods/Payconiq.test.ts @@ -1,35 +1,41 @@ -require('../BuckarooClient.test') -import Payconiq from '../../src/PaymentMethods/Payconiq/index' - -const payconiq = new Payconiq() +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; +const payconiq = buckarooClientTest.method('payconiq'); describe('Payconiq', () => { test('Pay', async () => { await payconiq .pay({ - amountDebit: 50.3, - order: '123456' + amountDebit: 100, + order: uniqid(), }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) + expect(info.data).toBeDefined(); + }); + }); test('Refund', async () => { await payconiq .refund({ - amountCredit: 50.3, - originalTransactionKey: '123456' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) + expect(info.data).toBeDefined(); + }); + }); test('InstantRefund', async () => { - await payconiq.instantRefund({ - amountCredit: 4.23, - originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1', - }).then((data) => { - expect(data).toBeDefined() - }) - }) -}) + await payconiq + .instantRefund({ + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/PaymentInitiation.test.js b/tests/PaymentMethods/PaymentInitiation.test.js new file mode 100644 index 00000000..0bdae1d6 --- /dev/null +++ b/tests/PaymentMethods/PaymentInitiation.test.js @@ -0,0 +1,29 @@ +require('../BuckarooClient.test'); +import PayByBank from '../../src/PaymentMethods/PayByBank'; +const paymentInitiation = new PayByBank('PayByBank'); +describe('PayByBank methods', () => { + test('Pay', async () => { + await paymentInitiation + .pay({ + amountDebit: 50.3, + order: '123456', + issuer: 'INGBNL2A', + countryCode: 'NL' + }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); + test('Refund', async () => { + await paymentInitiation + .refund({ + amountCredit: 50.3, + originalTransactionKey: '123456' + }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/PaymentInitiation.test.ts b/tests/PaymentMethods/PaymentInitiation.test.ts index 6f4b2450..1c719e4b 100644 --- a/tests/PaymentMethods/PaymentInitiation.test.ts +++ b/tests/PaymentMethods/PaymentInitiation.test.ts @@ -1,29 +1,40 @@ -require('../BuckarooClient.test') -import PaymentInitiation from '../../src/PaymentMethods/PaymentInitiation' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const payByBank = new PaymentInitiation() +const method = buckarooClientTest.method('PayByBank'); describe('PaymentInitiation methods', () => { + test('Issuers', async () => { + await method + .issuers() + .then((response) => { + expect(Array.isArray(response)).toBeTruthy(); + }); + }); test('Pay', async () => { - await payByBank + await method .pay({ - amountDebit: 50.3, - order: '123456', - issuer: 'INGBNL2A', - countryCode: 'NL' - }) - .then((response) => { - expect(response).toBeTruthy() + issuer: 'RABONL2U', + amountDebit: 100, + order: uniqid(), + invoice: uniqid(), + countryCode: 'NL', }) - }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); test('Refund', async () => { - await payByBank + await method .refund({ - amountCredit: 50.3, - originalTransactionKey: '123456' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) -}) + expect(info.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Paypal.test.js b/tests/PaymentMethods/Paypal.test.js new file mode 100644 index 00000000..d548718a --- /dev/null +++ b/tests/PaymentMethods/Paypal.test.js @@ -0,0 +1,50 @@ +import buckarooClientTest from '../BuckarooClient.test'; +require('../BuckarooClient.test'); +import Paypal from '../../src/PaymentMethods/Paypal'; +const method = new Paypal('paypal'); +describe('Paypal', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 50.3 + }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 50.3, + originalTransactionKey: '123456' + }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); + test('ExtraInfo', async () => { + buckarooClientTest.method('subscriptions').createCombined({}); + await method + .extraInfo({ + amountDebit: 50.3, + address: { + street: 'Hoofstraat 90', + street2: 'Street 2', + city: 'Heerenveen', + state: 'Friesland', + zipcode: '8441AB', + country: 'NL' + }, + addressOverride: false, + costumer: { name: 'John' }, + noShipping: '0', + phone: { mobile: '0612345678' } + }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Paypal.test.ts b/tests/PaymentMethods/Paypal.test.ts index 3ac78130..e3828369 100644 --- a/tests/PaymentMethods/Paypal.test.ts +++ b/tests/PaymentMethods/Paypal.test.ts @@ -1,47 +1,52 @@ -require('../BuckarooClient.test') -import Paypal from '../../src/PaymentMethods/Paypal/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new Paypal() +const method = buckarooClientTest.method('paypal'); describe('Paypal', () => { test('Pay', async () => { await method .pay({ - amountDebit: 50.3 + amountDebit: 100, }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) + expect(info.data).toBeDefined(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 50.3, - originalTransactionKey: '123456' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) + expect(info.data).toBeDefined(); + }); + }); test('ExtraInfo', async () => { + buckarooClientTest.method('subscriptions').createCombined({}); await method .extraInfo({ - amountDebit: 50.3, + amountDebit: 100, address: { - city: 're', - country: 'rw', - state: 'fsd', - street: 'dsf', - street2: 'dsf', - zipcode: 'sdf' + street: 'Hoofdstraat', + street2: 'Street 2', + city: 'Heerenveen', + state: 'Friesland', + zipcode: '8441ER', + country: 'NL', }, addressOverride: false, - costumer: { name: 'ers' }, - noShipping: 0, - phone: { mobile: '534' } + customer: { name: 'Test Acceptatie' }, + noShipping: '0', + phone: { mobile: '0612345678' }, }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) -}) + expect(info.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/PiM.test.js b/tests/PaymentMethods/PiM.test.js new file mode 100644 index 00000000..ddf1750c --- /dev/null +++ b/tests/PaymentMethods/PiM.test.js @@ -0,0 +1,10 @@ +require('../BuckarooClient.test'); +import PiM from '../../src/PaymentMethods/PiM'; +const pim = new PiM(); +describe('PiM', () => { + test('generate', async () => { + await pim.generate().then((info) => { + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/PiM.test.ts b/tests/PaymentMethods/PiM.test.ts index 113ff994..b1d90ced 100644 --- a/tests/PaymentMethods/PiM.test.ts +++ b/tests/PaymentMethods/PiM.test.ts @@ -1,13 +1,32 @@ -require("../BuckarooClient.test"); -import PiM from "../../src/PaymentMethods/PiM"; +import buckarooClientTest from '../BuckarooClient.test'; +import { Gender } from '../../src'; -const pim = new PiM(); +const method = buckarooClientTest.method('pim'); -describe("PiM", () => { - - test("generate", async () => { - await pim.generate().then((info) => { - expect(info).toBeDefined(); +describe('PiM', () => { + test('generate', async () => { + await method + .generate({ + amountDebit: 100, + description: 'Omschrijving', + title: 'Titel', + return: { + nickname: 'test', + initials: 'TA', + firstName: 'Test', + lastName: 'Acceptatie', + birthDate: '01-01-1990', + gender: Gender.MALE, + email: 'test@buckaroo.nl', + }, + result: { + title: 'success', + text: 'bedankt', + }, + }) + .request() + .then((info) => { + expect(info).toBeDefined(); + }); }); - }); -}) \ No newline at end of file +}); diff --git a/tests/PaymentMethods/Pos.test.ts b/tests/PaymentMethods/Pos.test.ts new file mode 100644 index 00000000..87d48462 --- /dev/null +++ b/tests/PaymentMethods/Pos.test.ts @@ -0,0 +1,19 @@ +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; + +const method = buckarooClientTest.method('pospayment'); + +describe('POS methods', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 100, + invoice: uniqid(), + terminalId: '50000001', + }) + .request() + .then((data) => { + expect(data.isPendingProcessing()).toBeTruthy(); + }); + }); +}); \ No newline at end of file diff --git a/tests/PaymentMethods/Przelewy24.test.js b/tests/PaymentMethods/Przelewy24.test.js new file mode 100644 index 00000000..bebf63b3 --- /dev/null +++ b/tests/PaymentMethods/Przelewy24.test.js @@ -0,0 +1,31 @@ +require('../BuckarooClient.test'); +import Przelewy24 from '../../src/PaymentMethods/Przelewy24'; +const method = new Przelewy24('Przelewy24'); +describe('Przelewy24', () => { + test('Pay', async () => { + method + .pay({ + amountDebit: 50.3, + customer: { + firstName: 'test', + lastName: 'test' + }, + email: 'test@hotmail.com' + }) + .request() + .then((res) => { + expect(res.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 50.3, + originalTransactionKey: '123456' + }) + .request() + .then((info) => { + expect(info.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Przelewy24.test.ts b/tests/PaymentMethods/Przelewy24.test.ts index 8ccbb97e..4b477a59 100644 --- a/tests/PaymentMethods/Przelewy24.test.ts +++ b/tests/PaymentMethods/Przelewy24.test.ts @@ -1,31 +1,34 @@ -require('../BuckarooClient.test') -import Przelewy24 from '../../src/PaymentMethods/Przelewy24/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -const method = new Przelewy24() +const method = buckarooClientTest.method('przelewy24'); describe('Przelewy24', () => { test('Pay', async () => { - await method + method .pay({ - customerLastName: "", - additionalParameters: undefined, - amountDebit: 0, - customerEmail: "", - customerFirstName: "", - email: "", - }) - .then((info) => { - expect(info).toBeDefined() + amountDebit: 100, + customer: { + firstName: 'Test', + lastName: 'Acceptatie', + }, + email: 'test@buckaroo.nl', }) - }) + .request() + .then((res) => { + expect(res.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 50.3, - originalTransactionKey: '123456' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info.data).toBeDefined() - }) - }) -}) + expect(info.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/SEPA.test.js b/tests/PaymentMethods/SEPA.test.js new file mode 100644 index 00000000..4d5e74de --- /dev/null +++ b/tests/PaymentMethods/SEPA.test.js @@ -0,0 +1,128 @@ +require('../BuckarooClient.test'); +import SEPA from '../../src/PaymentMethods/SEPA'; +const method = new SEPA(); +describe('SEPA', () => { + test('Pay', async () => { + await method + .pay({ + additionalParameters: undefined, + amountDebit: 0, + clientIP: undefined, + collectDate: '', + continueOnIncomplete: 0, + culture: '', + currency: '', + customParameters: undefined, + customerBIC: '', + customerIBAN: '', + customeraccountname: '', + description: '', + invoice: '', + mandateDate: '', + mandateReference: '', + order: '', + originalTransactionKey: '', + originalTransactionReference: '', + pushURL: '', + pushURLFailure: '', + returnURL: '', + returnURLCancel: '', + returnURLError: '', + returnURLReject: '', + servicesExcludedForClient: '', + servicesSelectableByClient: '', + startRecurrent: false + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 50.3, + originalTransactionKey: '' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('Authorize', async () => { + await method + .authorize({ + amountDebit: 0, + collectDate: '', + customerIBAN: '', + customeraccountname: '' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('PayRecurrent', async () => { + await method + .payRecurrent({ + collectDate: '', + amountDebit: 50.3, + originalTransactionKey: '' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('ExtraInfo', async () => { + await method + .extraInfo({ + additionalParameters: undefined, + amountDebit: 0, + city: '', + clientIP: undefined, + collectDate: '', + contractID: '', + country: '', + culture: '', + currency: '', + customParameters: undefined, + customerBIC: '', + customerCode: '', + customerIBAN: '', + customerName: '', + customerReferencePartyCode: '', + customerReferencePartyName: '', + customeraccountname: '', + description: '', + houseNumber: '', + houseNumberSuffix: '', + invoice: '', + mandateDate: '', + mandateReference: '', + order: '', + originalTransactionKey: '', + originalTransactionReference: '', + pushURL: '', + pushURLFailure: '', + returnURL: '', + returnURLCancel: '', + returnURLError: '', + returnURLReject: '', + servicesExcludedForClient: '', + servicesSelectableByClient: '', + startRecurrent: false, + street: '', + zipcode: '' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('Emandates', async () => { + await method + .payWithEmandate({ + mandateReference: '', + amountDebit: 50.3 + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/SEPA.test.ts b/tests/PaymentMethods/SEPA.test.ts index 9652e532..58ba5e25 100644 --- a/tests/PaymentMethods/SEPA.test.ts +++ b/tests/PaymentMethods/SEPA.test.ts @@ -1,130 +1,101 @@ -require('../BuckarooClient.test') -import SEPA from '../../src/PaymentMethods/SEPA/index' +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; +import { IPay } from '../../src/PaymentMethods/SEPA/Models/Pay'; -const method = new SEPA() +const method = buckarooClientTest.method('sepadirectdebit'); -describe('SEPA', () => { +const paymentPayload: IPay = { + invoice: uniqid(), + amountDebit: 100, + iban: 'NLXXTESTXXXXXXXXXX', + bic: 'XXXXXXXXX', + collectdate: '2022-12-01', + mandateReference: 'XXXXXXXXXXXXXXX', + mandateDate: '2022-07-03', + customer: { + name: 'Test Acceptatie', + }, +}; + +describe('SEPA methods', () => { test('Pay', async () => { await method - .pay({ - additionalParameters: undefined, - amountDebit: 0, - clientIP: undefined, - collectDate: '', - continueOnIncomplete: 0, - culture: '', - currency: '', - customParameters: undefined, - customerBIC: '', - customerIBAN: '', - customeraccountname: '', - description: '', - invoice: '', - mandateDate: '', - mandateReference: '', - order: '', - originalTransactionKey: '', - originalTransactionReference: '', - pushURL: '', - pushURLFailure: '', - returnURL: '', - returnURLCancel: '', - returnURLError: '', - returnURLReject: '', - servicesExcludedForClient: '', - servicesSelectableByClient: '', - startRecurrent: false - }) + .pay(paymentPayload) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 50.3, - originalTransactionKey: '' + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('Authorize', async () => { await method - .authorize({ - amountDebit: 0, - collectDate: '', - customerIBAN: '', - customeraccountname: '' - }) + .authorize(paymentPayload) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('PayRecurrent', async () => { await method .payRecurrent({ - collectDate: '', - amountDebit: 50.3, - originalTransactionKey: '' + invoice: uniqid(), + collectDate: '2030-07-03', + amountDebit: 100, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('ExtraInfo', async () => { await method .extraInfo({ - additionalParameters: undefined, - amountDebit: 0, - city: '', - clientIP: undefined, - collectDate: '', - contractID: '', - country: '', - culture: '', - currency: '', - customParameters: undefined, - customerBIC: '', - customerCode: '', - customerIBAN: '', - customerName: '', - customerReferencePartyCode: '', - customerReferencePartyName: '', - customeraccountname: '', - description: '', - houseNumber: '', - houseNumberSuffix: '', - invoice: '', - mandateDate: '', - mandateReference: '', - order: '', - originalTransactionKey: '', - originalTransactionReference: '', - pushURL: '', - pushURLFailure: '', - returnURL: '', - returnURLCancel: '', - returnURLError: '', - returnURLReject: '', - servicesExcludedForClient: '', - servicesSelectableByClient: '', - startRecurrent: false, - street: '', - zipcode: '' + amountDebit: 100, + invoice: uniqid(), + iban: 'NLXXTESTXXXXXXXXXX', + bic: 'XXXXXXXXX', + contractID: 'Test', + mandateDate: '2022-07-03', + customerReferencePartyName: 'Test', + customer: { + name: 'Test Acceptatie', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('Emandates', async () => { await method .payWithEmandate({ - mandateReference: '', - amountDebit: 50.3 + order: uniqid(), + invoice: uniqid(), + mandateReference: 'XXXXXXXXXXXXXXX', + amountDebit: 100, }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) -}) + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/SEPAB2B.test.ts b/tests/PaymentMethods/SEPAB2B.test.ts deleted file mode 100644 index b8f23fd9..00000000 --- a/tests/PaymentMethods/SEPAB2B.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -require('../BuckarooClient.test') -import SEPA from '../../src/PaymentMethods/SEPA' - -const sepab2b = new SEPA('B2B') -describe('SEPA', () => { - test('Pay', async () => { - await sepab2b - .pay({ - additionalParameters: undefined, - amountDebit: 0, - clientIP: undefined, - collectDate: '', - continueOnIncomplete: 0, - culture: '', - currency: '', - customParameters: undefined, - customerBIC: '', - customerIBAN: '', - customeraccountname: '', - description: '', - invoice: '', - mandateDate: '', - mandateReference: '', - order: '', - originalTransactionKey: '', - originalTransactionReference: '', - pushURL: '', - pushURLFailure: '', - returnURL: '', - returnURLCancel: '', - returnURLError: '', - returnURLReject: '', - servicesExcludedForClient: '', - servicesSelectableByClient: '', - startRecurrent: false - }) - .then((info) => { - expect(info).toBeDefined() - }) - }) - test('Refund', async () => { - await sepab2b - .refund({ - amountCredit: 50.3, - originalTransactionKey: '' - }) - .then((info) => { - expect(info).toBeDefined() - }) - }) - test('Authorize', async () => { - await sepab2b - .authorize({ - amountDebit: 0, - collectDate: '', - customerIBAN: '', - customeraccountname: '' - }) - .then((info) => { - expect(info).toBeDefined() - }) - }) - test('PayRecurrent', async () => { - await sepab2b - .payRecurrent({ - collectDate: '', - amountDebit: 50.3, - originalTransactionKey: '' - }) - .then((info) => { - expect(info).toBeDefined() - }) - }) - test('ExtraInfo', async () => { - await sepab2b - .extraInfo({ - amountDebit: 0, - city: "", - collectDate: "", - contractID: "", - country: "", - customerIBAN: "", - customeraccountname: "", - houseNumberSuffix: "", - street: "", - zipcode: "" - }) - .then((info) => { - expect(info).toBeDefined() - }) - }) - test('Emandates', async () => { - await sepab2b - .payWithEmandate({ - mandateReference: '', - amountDebit: 50.3 - }) - .then((info) => { - expect(info).toBeDefined() - }) - }) -}) diff --git a/tests/PaymentMethods/Sofort.test.js b/tests/PaymentMethods/Sofort.test.js new file mode 100644 index 00000000..8663717a --- /dev/null +++ b/tests/PaymentMethods/Sofort.test.js @@ -0,0 +1,35 @@ +require('../BuckarooClient.test'); +import Sofort from '../../src/PaymentMethods/Sofort'; +const method = new Sofort(); +describe('Sofort', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 50.3, + order: '123456' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 50.3, + originalTransactionKey: '123456' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); + test('InstantRefund', async () => { + await method + .instantRefund({ + amountCredit: 4.23, + originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1' + }) + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Sofort.test.ts b/tests/PaymentMethods/Sofort.test.ts index 9d039f9a..1d3a1741 100644 --- a/tests/PaymentMethods/Sofort.test.ts +++ b/tests/PaymentMethods/Sofort.test.ts @@ -1,35 +1,43 @@ -require('../BuckarooClient.test') -import Sofort from '../../src/PaymentMethods/Sofort' -const method = new Sofort() +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; + +const method = buckarooClientTest.method('sofortueberweisung'); describe('Sofort', () => { test('Pay', async () => { - await method + return await method .pay({ - amountDebit: 50.3, - order: '123456' + amountDebit: 100, + order: uniqid(), }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 50.3, - originalTransactionKey: '123456' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) + expect(info).toBeDefined(); + }); + }); test('InstantRefund', async () => { - await method.instantRefund({ - amountCredit: 4.23, - originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1', - }).then((data) => { - expect(data).toBeDefined() - }) - }) -}) + await method + .instantRefund({ + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Subscriptions.test.js b/tests/PaymentMethods/Subscriptions.test.js new file mode 100644 index 00000000..c4baa95f --- /dev/null +++ b/tests/PaymentMethods/Subscriptions.test.js @@ -0,0 +1,154 @@ +import buckarooClientTest from '../BuckarooClient.test'; +const subscription = buckarooClientTest.method('subscriptions'); +test('Create', async () => { + subscription + .create({ + additionalParameters: { + signature: '123213' + }, + ratePlans: { + add: { + startDate: '2024-07-23', + ratePlanCode: 'zfv59mmy' + } + }, + ratePlanCharges: { + add: { + ratePlanChargeCode: 'test' + } + }, + configurationCode: 'gfyh9fe4', + configuration: { + name: 'owiejr' + }, + debtor: { + code: 'johnsmith4' + } + }) + .request() + .then((data) => { + expect(data.hasError()).toBeTruthy(); + }) + .catch((e) => { + expect(e).toBeDefined(); + }) + .catch((e) => { + expect(e).toBeDefined(); + }); +}); +test('Update', async () => { + subscription + .update({ + email: 'test@buckaroo.nl', + subscriptionGuid: 'FC512FC9CC3A485D8CF3D1804FF6xxxx', + configurationCode: '9wqe32ew', + ratePlan: { + update: { + ratePlanGuid: 'F075470B1BB24B9291943A888A2Fxxxx', + startDate: '2022-01-01', + endDate: '2030-01-01' + } + } + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); +}); +test('Combined Subscription', async () => { + const combinable = subscription + .createCombined({ + pushURL: 'https://buckaroo.dev/push', + includeTransaction: false, + transactionVatPercentage: 5, + configurationCode: 'gfyh9fe4', + email: 'test@buckaroo.nl', + ratePlans: { + add: { + startDate: '2033-01-01', + ratePlanCode: '9863hdcj' + } + }, + phone: { + mobile: '0612345678' + }, + debtor: { + code: 'johnsmith4' + }, + company: { + culture: 'nl-NL', + companyName: 'My Company Coporation', + vatApplicable: true, + vatNumber: 'NL140619562B01', + chamberOfCommerce: '20091741' + }, + address: { + street: 'Hoofdstraat', + houseNumber: '90', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL' + } + }) + .combine('ideal') + .pay({ + issuer: 'ABNANL2A', + amountDebit: 10, + startRecurrent: true + }) + .request() + .then((res) => { + expect(res).toBeDefined(); + }); +}); +test('Update Combined Subscription', async () => { + const combinable = subscription + .updateCombined({ + subscriptionGuid: '515461997AD34C50881D74157E38A64D' + }) + .combine('ideal') + .pay({ + issuer: 'ABNANL2A', + amountDebit: 10 + }) + .request() + .then((res) => { + expect(res).toBeDefined(); + }); +}); +test('Stop Subscription', async () => { + const stop = await subscription.stop({ + subscriptionGuid: '515461997AD34C50881D74157E38A64D' + }); + expect(stop).toBeDefined(); +}); +test('Subscription Info', async () => { + const info = await subscription.info({ + subscriptionGuid: '515461997AD34C50881D74157E38A64D' + }); + expect(info).toBeDefined(); +}); +test('Delete Subscription Config', async () => { + await subscription + .deletePaymentConfig({ + subscriptionGuid: '515461997AD34C50881D74157E38A64D' + }) + .request() + .then((res) => { + expect(res.httpResponse.statusCode === 200).toBeTruthy(); + }); +}); +test('Subscription Pause', async () => { + const pause = await subscription.pause({ + subscriptionGuid: '515461997AD34C50881D74157E38A64D', + resumeDate: '2030-01-01' + }); + expect(pause).toBeDefined(); +}); +test('Subscription Resume', async () => { + const resume = await subscription.resume({ + resumeDate: '2030-01-01', + subscriptionGuid: '515461997AD34C50881D74157E38A64D' + }); + expect(resume).toBeDefined(); +}); diff --git a/tests/PaymentMethods/Subscriptions.test.ts b/tests/PaymentMethods/Subscriptions.test.ts index 4193aad2..c78e1157 100644 --- a/tests/PaymentMethods/Subscriptions.test.ts +++ b/tests/PaymentMethods/Subscriptions.test.ts @@ -1,145 +1,154 @@ -import Subscriptions from '../../src/PaymentMethods/Subscriptions/index' -import Ideal from '../../src/PaymentMethods/Ideal/index' +import buckarooClientTest from '../BuckarooClient.test'; -require('../BuckarooClient.test') +const subscription = buckarooClientTest.method('subscriptions'); -const subscription = new Subscriptions() -const ideal = new Ideal() - -test('Create', async () => { - subscription - .create({ - ratePlan: { - update: { - startDate: '2024-07-23', - ratePlanGuid: '' - } - }, - ratePlanCharge: { +describe('Subscription methods', () => { + test('Create', () => { + return subscription + .create({ + additionalParameters: { + signature: 'XXXXXXXX', + }, + ratePlans: { + add: { + startDate: '2024-07-23', + ratePlanCode: 'XXXXXXXX', + }, + }, + ratePlanCharges: { + add: { + ratePlanChargeCode: 'XXXXXXXX', + }, + }, + configurationCode: 'XXXXXXXX', + configuration: { + name: 'XXXXXXXX', + }, + debtor: { + code: 'XXXXXXXX', + }, + }) + .request() + .then((data) => { + expect(data.hasError()).toBeTruthy(); + }); + }); + test('Update', async () => { + subscription + .update({ + email: 'test@buckaroo.nl', + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + configurationCode: 'XXXXXXXX', + ratePlan: { + update: { + ratePlanGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + startDate: '2022-01-01', + endDate: '2030-01-01', + }, + }, + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); + test('Combined Subscription', async () => { + subscription.createCombined({ + pushURL: 'https://buckaroo.dev/push', + includeTransaction: false, + transactionVatPercentage: 5, + configurationCode: 'XXXXXXXX', + email: 'test@buckaroo.nl', + ratePlans: { add: { - ratePlanChargeCode: 'test' - } + startDate: '2033-01-01', + ratePlanCode: 'XXXXXXXX', + }, }, - configurationCode: 'gfyh9fe4', - addConfiguration: { - name: 'owiejr' + phone: { + mobile: '0612345678', }, debtor: { - code: 'johnsmith4' - } - }) - .catch((e) => { - expect(e.response.data).toBeDefined() - }) - .catch((e) => { - expect(e.response.data).toBeDefined() - }) -}) -test('Update', async () => { - subscription - .update({ - email: { email: 'test@buckaroo.nl' }, - subscriptionGuid: 'FC512FC9CC3A485D8CF3D1804FF6xxxx', - configurationCode: '9wqe32ew', - ratePlan: { - update: { - ratePlanGuid: 'F075470B1BB24B9291943A888A2Fxxxx', - startDate: '2022-01-01', - endDate: '2030-01-01' - } - } - }) - .then((data) => { - expect(data).toBeDefined() - }) -}) - -test('Combined Subscription', async () => { - const combinable = subscription.createCombined({ - address: undefined, - allowedServices: '', - b2b: '', - bankAccount: { accountName: '', bic: '', iban: '' }, - billingTiming: 0, - // company: undefined, - configuration: undefined, - configurationCode: '', - customerAccountName: '', - customerBIC: '', - customerIBAN: '', - debtor: { code: '' }, - email: { email: '' }, - includeTransaction: false, - mandateReference: '', - person: undefined, - phone: undefined, - ratePlan: undefined, - ratePlanCharge: undefined, - subscriptionGuid: '', - termStartDay: 0, - termStartMonth: 0, - termStartWeek: '', - transactionVatPercentage: 0 - }) - ideal - .combine(combinable) - .pay({ - issuer: 'ABNANL2A', - amountDebit: 10, - startRecurrent: true - }) - .then((res) => { - expect(res).toBeDefined() - }) -}) + code: 'XXXXXXXX', + }, + company: { + culture: 'nl-NL', + companyName: 'Buckaroo B.V.', + vatApplicable: true, + vatNumber: 'NLXXXXXXXXXXB01', + chamberOfCommerce: 'XXXXXX41', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + }); + subscription + .combine('ideal') + .pay({ + issuer: 'ABNANL2A', + amountDebit: 100, + startRecurrent: true, + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); -test('Update Combined Subscription', async () => { - const combinable = subscription.updateCombined({ - subscriptionGuid: '515461997AD34C50881D74157E38A64D' - }) - ideal - .combine(combinable) - .pay({ - issuer: 'ABNANL2A', - amountDebit: 10 - }) - .then((res) => { - expect(res).toBeDefined() - }) -}) + test('Update Combined Subscription', async () => { + subscription.updateCombined({ + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }); + subscription + .combine('ideal') + .pay({ + issuer: 'ABNANL2A', + amountDebit: 100, + }) + .request() + .then((data) => { + expect(data).toBeDefined(); + }); + }); -test('Stop Subscription', async () => { - const stop = await subscription.stop({ - subscriptionGuid: '515461997AD34C50881D74157E38A64D' - }) - expect(stop).toBeDefined() -}) -test('Subscription Info', async () => { - const info = await subscription.info({ - subscriptionGuid: '515461997AD34C50881D74157E38A64D' - }) - expect(info).toBeDefined() -}) -test('Delete Subscription Config', async () => { - await subscription - .deletePaymentConfig({ - subscriptionGuid: '515461997AD34C50881D74157E38A64D' - }) - .then((res) => { - expect(res.status === 200).toBeTruthy() - }) -}) -test('Subscription Pause', async () => { - const pause = await subscription.pause({ - subscriptionGuid: '515461997AD34C50881D74157E38A64D', - resumeDate: '2030-01-01' - }) - expect(pause).toBeDefined() -}) -test('Subscription Resume', async () => { - const resume = await subscription.resume({ - resumeDate: '2030-01-01', - subscriptionGuid: '515461997AD34C50881D74157E38A64D' - }) - expect(resume).toBeDefined() -}) + test('Stop Subscription', async () => { + const stop = await subscription.stop({ + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }); + expect(stop).toBeDefined(); + }); + test('Subscription Info', async () => { + const info = await subscription.info({ + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }); + expect(info).toBeDefined(); + }); + test('Delete Subscription Config', async () => { + await subscription + .deletePaymentConfig({ + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }) + .request() + .then((res) => { + expect(res.httpResponse.status === 200).toBeTruthy(); + }); + }); + test('Subscription Pause', async () => { + const pause = await subscription.pause({ + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + resumeDate: '2030-01-01', + }); + expect(pause).toBeDefined(); + }); + test('Subscription Resume', async () => { + const resume = await subscription.resume({ + resumeDate: '2030-01-01', + subscriptionGuid: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + }); + expect(resume).toBeDefined(); + }); +}); diff --git a/tests/PaymentMethods/SurePay.test.js b/tests/PaymentMethods/SurePay.test.js new file mode 100644 index 00000000..01319efb --- /dev/null +++ b/tests/PaymentMethods/SurePay.test.js @@ -0,0 +1,14 @@ +require('../BuckarooClient.test'); +import SurePay from '../../src/PaymentMethods/Surepay'; +const method = new SurePay(); +describe('Sofort', () => { + test('Verify', async () => { + await method + .verify({ + customeraccountname: 'string' + }) + .then((info) => { + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/SurePay.test.ts b/tests/PaymentMethods/SurePay.test.ts index 0efad202..8a29968b 100644 --- a/tests/PaymentMethods/SurePay.test.ts +++ b/tests/PaymentMethods/SurePay.test.ts @@ -1,16 +1,20 @@ -require('../BuckarooClient.test') -import SurePay from '../../src/PaymentMethods/Surepay/index' +import buckarooClientTest from '../BuckarooClient.test'; -const method = new SurePay() +const method = buckarooClientTest.method('surepay'); -describe('Sofort', () => { +describe('SurePay methods', () => { test('Verify', async () => { await method .verify({ - customeraccountname: "string" + amountDebit: 100, + bankAccount: { + iban: 'NLXXTESTXXXXXXXXXX', + accountName: 'Test Acceptatie', + }, }) + .request() .then((info) => { - expect(info).toBeDefined() - }) - }) -}) + expect(info).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Thunes.test.js b/tests/PaymentMethods/Thunes.test.js new file mode 100644 index 00000000..d02b5a7f --- /dev/null +++ b/tests/PaymentMethods/Thunes.test.js @@ -0,0 +1,25 @@ +require('../BuckarooClient.test'); +import Thunes from '../../src/PaymentMethods/Thunes'; +const thunes = new Thunes(); +describe('Thunes methods', () => { + test('authorize', async () => { + thunes.authorize({ amountDebit: 0 }).then((res) => { + expect(res.data).toBeDefined(); + }); + }); + test('capture', async () => { + thunes.capture({ amountDebit: 0, originalTransactionKey: '1' }).then((res) => { + expect(res.data).toBeDefined(); + }); + }); + test('getStatus', async () => { + thunes.getStatus({ originalTransactionKey: '111111111111' }).then((res) => { + expect(res.data).toBeDefined(); + }); + }); + test('cancel', async () => { + thunes.cancel({ originalTransactionKey: '111111111111' }).then((res) => { + expect(res.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Thunes.test.ts b/tests/PaymentMethods/Thunes.test.ts index e3f329eb..4f660f69 100644 --- a/tests/PaymentMethods/Thunes.test.ts +++ b/tests/PaymentMethods/Thunes.test.ts @@ -1,28 +1,56 @@ -require('../BuckarooClient.test') +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; -import Thunes from "../../src/PaymentMethods/Thunes"; - -const thunes = new Thunes() +const method = buckarooClientTest.method('thunes'); describe('Thunes methods', () => { - test('authorize', async () => { - thunes.authorize({ amountDebit: 0 }).then((res)=>{ - expect(res.data).toBeDefined() - }) - }) - test('capture', async () => { - thunes.capture({ amountDebit: 0 ,originalTransactionKey:'1'}).then((res)=>{ - expect(res.data).toBeDefined() - }) - }) - test('getStatus', async () => { - thunes.getStatus({originalTransactionKey:'111111111111'}).then((res)=>{ - expect(res.data).toBeDefined() - }) - }) - test('cancel', async () => { - thunes.cancel({originalTransactionKey:'111111111111'}).then((res)=>{ - expect(res.data).toBeDefined() - }) - }) -}) \ No newline at end of file + test('authorize', async () => { + await method + .authorize({ + amountDebit: 100, + order: uniqid(), + invoice: uniqid(), + name: 'monizzeecovoucher', + articles: [ + { + identifier: 'Articlenumber1', + description: 'Articledesciption1', + price: '1', + }, + { + identifier: 'Articlenumber2', + description: 'Articledesciption2', + price: '2', + }, + ], + }) + .request() + .then((res) => { + expect(res.data).toBeDefined(); + }); + }); + test('capture', async () => { + await method + .capture({ amountDebit: 100, originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }) + .request() + .then((res) => { + expect(res.data).toBeDefined(); + }); + }); + test('getStatus', async () => { + await method + .getStatus({ originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }) + .request() + .then((res) => { + expect(res.data).toBeDefined(); + }); + }); + test('cancel', async () => { + await method + .cancel({ originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }) + .request() + .then((res) => { + expect(res.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Tinka.test.js b/tests/PaymentMethods/Tinka.test.js new file mode 100644 index 00000000..e939962a --- /dev/null +++ b/tests/PaymentMethods/Tinka.test.js @@ -0,0 +1,64 @@ +import Gender from "../../src/Constants/Gender"; +import buckarooClientTest from "../BuckarooClient.test"; +const method = buckarooClientTest.method('tinka'); +describe('Tinka', () => { + test('Pay', async () => { + await method + .pay({ + billing: { + recipient: { + lastNamePrefix: "the" + }, + email: "billingcustomer@buckaroo.nl", + phone: { + mobile: "0109876543" + }, + address: { + street: "Hoofdstraat", + houseNumber: "80", + houseNumberAdditional: "A", + zipcode: "8441EE", + city: "Heerenveen", + country: "NL" + } + }, + customer: { + gender: Gender.MALE, + firstName: 'Buck', + lastName: 'Aroo', + initials: 'BA', + birthDate: '1990-01-01', + }, + amountDebit: 3.5, + articles: [ + { + type: '1', + description: "Blue Toy Car", + brand: "Ford Focus", + manufacturer: "Ford", + color: "Red", + size: "Small", + quantity: 1, + price: 3.5, + unitCode: "test" + } + ], + deliveryDate: '09-07-2020', + deliveryMethod: 'CompanyStore', + paymentMethod: 'Credit' + }).request() + .then((res) => { + expect(res.isPendingProcessing()).toBeTruthy(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 3.5, + originalTransactionKey: '1234567890' + }).request() + .then((res) => { + expect(res.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Tinka.test.ts b/tests/PaymentMethods/Tinka.test.ts index 3613a782..43c9b0dd 100644 --- a/tests/PaymentMethods/Tinka.test.ts +++ b/tests/PaymentMethods/Tinka.test.ts @@ -1,58 +1,65 @@ -require('../BuckarooClient.test') -import Tinka from '../../src/PaymentMethods/Tinka/index' - -const method = new Tinka() +import { Gender, uniqid } from '../../src'; +import buckarooClientTest from '../BuckarooClient.test'; +const method = buckarooClientTest.method('tinka'); describe('Tinka', () => { test('Pay', async () => { await method .pay({ - amountDebit: 3.5, - article: [ + billing: { + email: 'test@buckaroo.nl', + phone: { + mobile: '0612345678', + }, + address: { + street: 'Hoofdstraat', + houseNumber: '80', + houseNumberAdditional: 'a', + zipcode: '8441ER', + city: 'Heerenveen', + country: 'NL', + }, + }, + customer: { + gender: Gender.MALE, + firstName: 'Test', + lastName: 'Acceptatie', + initials: 'BA', + birthDate: '1990-01-01', + }, + amountDebit: 100, + articles: [ { - description: 'ewf', + type: '1', + description: 'Blue Toy Car', + brand: 'Ford Focus', + manufacturer: 'Ford', + color: 'Red', + size: 'Small', quantity: 1, - unitCode: '', - unitGrossPrice: 3.5 - } + price: 100, + unitCode: 'test', + }, ], - billingCustomer: { - city: 'wef', - country: 'rfew', - email: 'few@hotmail.com', - phone: '3161234567', - postalCode: '345445', - prefixLastName: 'fsd', - street: 'ds', - streetNumber: '32', - streetNumberAdditional: 'descs' - }, - dateOfBirth: '', - deliveryDate: '', + deliveryDate: '09-07-2020', deliveryMethod: 'CompanyStore', - firstName: '323', - initials: '', - lastName: '54', - paymentMethod: 'Credit' + paymentMethod: 'Credit', }) - .then((info) => { - expect(info.data).toBeDefined() - }) - }) + .request() + .then((res) => { + expect(res.isPendingProcessing()).toBeTruthy(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 3.5, - originalTransactionKey: '1234567890' - }) - .then((info) => { - expect(info).toBeDefined() + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) - }) - - test('Specifications', async () => { - await method.specification().then((info) => { - expect(info).toBeDefined() - }) - }) -}) + .request() + .then((res) => { + expect(res.isFailed()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/Trustly.test.js b/tests/PaymentMethods/Trustly.test.js new file mode 100644 index 00000000..a226eca6 --- /dev/null +++ b/tests/PaymentMethods/Trustly.test.js @@ -0,0 +1,17 @@ +require('../BuckarooClient.test'); +import Trustly from '../../src/PaymentMethods/Trustly'; +const method = new Trustly(); +describe('Trustly', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 12, + customerCountryCode: 'DE', + customerFirstName: 'da', + customerLastName: '34' + }) + .then((response) => { + expect(response).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/Trustly.test.ts b/tests/PaymentMethods/Trustly.test.ts index cd57104b..90ef3466 100644 --- a/tests/PaymentMethods/Trustly.test.ts +++ b/tests/PaymentMethods/Trustly.test.ts @@ -1,19 +1,21 @@ -require('../BuckarooClient.test') -import Trustly from '../../src/PaymentMethods/Trustly/index' +import buckarooClientTest from '../BuckarooClient.test'; -const method = new Trustly() +const method = buckarooClientTest.method('trustly'); describe('Trustly', () => { test('Pay', async () => { await method .pay({ - amountDebit: 12, - customerCountryCode: 'DE', - customerFirstName: 'da', - customerLastName: '34' + amountDebit: 100, + customer: { + firstName: 'Test', + lastName: 'Acceptatie', + countryCode: 'NL', + }, }) + .request() .then((response) => { - expect(response).toBeDefined() - }) - }) -}) + expect(response.isPendingProcessing()).toBeTruthy(); + }); + }); +}); diff --git a/tests/PaymentMethods/WechatPay.test.js b/tests/PaymentMethods/WechatPay.test.js new file mode 100644 index 00000000..10c0f9a6 --- /dev/null +++ b/tests/PaymentMethods/WechatPay.test.js @@ -0,0 +1,24 @@ +import buckarooClientTest from "../BuckarooClient.test"; +const method = buckarooClientTest.method('wechatpay'); +describe('WechatPay', () => { + test('Pay', async () => { + await method + .pay({ + amountDebit: 3.5, + locale: 'en-US' + }).request() + .then((response) => { + expect(response.isPendingProcessing()).toBeDefined(); + }); + }); + test('Refund', async () => { + await method + .refund({ + amountCredit: 3.5, + originalTransactionKey: '1234567890' + }).request() + .then((response) => { + expect(response.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/WechatPay.test.ts b/tests/PaymentMethods/WechatPay.test.ts index b80a7020..187cd06c 100644 --- a/tests/PaymentMethods/WechatPay.test.ts +++ b/tests/PaymentMethods/WechatPay.test.ts @@ -1,27 +1,29 @@ -require('../BuckarooClient.test') -import WechatPay from '../../src/PaymentMethods/WeChatPay/index' - -const method = new WechatPay() +import buckarooClientTest from '../BuckarooClient.test'; +import { uniqid } from '../../src'; +const method = buckarooClientTest.method('wechatpay'); describe('WechatPay', () => { test('Pay', async () => { await method .pay({ - amountDebit: 3.5, - locale: 'en-US' + amountDebit: 100, + locale: 'en-US', }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) + expect(response.isPendingProcessing()).toBeDefined(); + }); + }); test('Refund', async () => { await method .refund({ - amountCredit: 3.5, - originalTransactionKey: '1234567890' + invoice: uniqid(), + amountCredit: 0.01, + originalTransactionKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', }) + .request() .then((response) => { - expect(response.data).toBeDefined() - }) - }) -}) + expect(response.data).toBeDefined(); + }); + }); +}); diff --git a/tests/PaymentMethods/idealProcessing.test.ts b/tests/PaymentMethods/idealProcessing.test.ts deleted file mode 100644 index 8678c2b6..00000000 --- a/tests/PaymentMethods/idealProcessing.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -require('../BuckarooClient.test') -import { uniqid } from '../../src/Utils/Functions' -import Ideal from '../../src/PaymentMethods/Ideal' - -const ideal = new Ideal('idealProcessing') -describe('testing Ideal processing methods', () => { - test('Issuers', async () => { - await ideal.issuers().then((response) => { - expect(Array.isArray(response)).toBeTruthy() - }) - }) - test('Pay Simple Payload', async () => { - await ideal - .pay({ - amountDebit: 10.1, - issuer: 'ABNANL2A', - clientIP: { - address: '123.456.789.123', - type: 0 - }, - additionalParameters: { - initiated_by_magento: 1, - service_action: 'something' - } - }) - .then((data) => { - expect(data.isPendingProcessing()).toBeTruthy() - }) - }) - test('Refund', async () => { - await ideal - .refund({ - order: uniqid(), - invoice: uniqid(), - originalTransactionKey: '97DC0A03BBDF4DAAAC694D7FEC8785E1', - amountCredit: 4.23, - clientIP: { - address: '123.456.789.123', - type: 0 - }, - additionalParameters: { - initiated_by_magento: '1', - service_action: 'something' - } - }) - .then((data) => { - expect(data).toBeDefined() - }) - }) -}) diff --git a/tsconfig-declarations.json b/tsconfig-declarations.json new file mode 100644 index 00000000..616f8e18 --- /dev/null +++ b/tsconfig-declarations.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "files": [], + "compilerOptions": { + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "dist/types" + } +} diff --git a/tsconfig.json b/tsconfig.json index f3c0dec6..a7f1282e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,19 +2,25 @@ "compilerOptions": { "target": "es5", "module": "commonjs", - "lib": ["ES2021", "dom"], + "lib": [ + "ES2021", + "dom" + ], "strict": true, + "noEmitOnError": true, "esModuleInterop": true, - "skipLibCheck": false /* Skip type checking of declaration files. */, - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, + "skipLibCheck": true + /* Skip type checking of declaration files. */, + "forceConsistentCasingInFileNames": true + /* Disallow inconsistently-cased references to the same file. */, "declaration": true, - "outDir": "./dist", - "rootDir": "./src", - "experimentalDecorators": true, + "sourceMap": true, "moduleResolution": "node", - "noImplicitAny": false, - "typeRoots": ["./node_modules/@types"], - "resolveJsonModule": true, + "noImplicitAny": true, + "outDir": "dist", + "resolveJsonModule": true }, - "include": ["src/**/*.ts"], + "include": [ + "src/**/*.ts" + ] } diff --git a/tsconfig.spec.json b/tsconfig.spec.json new file mode 100644 index 00000000..0d6da8d0 --- /dev/null +++ b/tsconfig.spec.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "types": [ + "jest", + "node" + ] + } +}