Compare commits

..

6 Commits

Author SHA1 Message Date
Ricardo Ambrogi
c59fca0f31 rc4 2020-01-16 12:24:34 +01:00
Ricardo Ambrogi
6f1d95432e rc3 2020-01-15 16:41:22 +01:00
Ricardo Ambrogi
a3ebb01aee change types ext 2020-01-15 16:23:45 +01:00
Ricardo Ambrogi
e5d4d72098 fix tests type 2020-01-15 15:31:37 +01:00
Ricardo Ambrogi
2654f5b20a change tsconfig 2020-01-15 15:20:18 +01:00
Ricardo Ambrogi
605e364082 Bundle type definitions with package 2020-01-15 12:51:57 +00:00
622 changed files with 24168 additions and 54588 deletions

View File

@@ -1,2 +1,3 @@
/src/typings/**/*.ts
/examples
/src/__mocks__/*
/src/__tests__/*
/src/typings/*

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
const path = require('path');
module.exports = {
@@ -42,8 +23,7 @@ module.exports = {
],
rules: {
quotes: ["error", "double"],
semi: ["error", "always"],
"@typescript-eslint/no-non-null-assertion": 0
semi: ["error", "always"]
},
overrides: [
{

2
.github/CODEOWNERS vendored
View File

@@ -1 +1 @@
* @zaiddreakh @maassenbas @AlexandrosMor @peterojo @wboereboom
* @KadoBOT @msilvagarcia @cyattilakiss @rkewlani @Aleffio @rikterbeek

View File

@@ -3,7 +3,7 @@ name: Bug report
about: Create a report to help us improve
title: '[BUG]'
labels: 'bug'
assignees: ''
assignees: 'KadoBOT'
---

View File

@@ -3,7 +3,7 @@ name: Feature request
about: Suggest an idea for this project
title: '[FEATURE]'
labels: 'feature'
assignees: ''
assignees: 'KadoBOT'
---

View File

@@ -1,7 +0,0 @@
**Description**
<!-- Please provide a description of the changes proposed in the Pull Request -->
**Tested scenarios**
<!-- Description of tested scenarios -->
**Fixed issue**: <!-- #-prefixed issue number -->

View File

@@ -1,15 +0,0 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
time: "04:00"
open-pull-requests-limit: 10
reviewers:
- zaiddreakh
maassenbas
msilvagarcia
AlexandrosMor
peterojo
wboereboom

11
.github/stale.yml vendored
View File

@@ -1,11 +0,0 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Label to use when marking an issue as stale
staleLabel: wontfix
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.

View File

@@ -1,46 +0,0 @@
name: "Code scanning - action"
on:
push:
pull_request:
schedule:
- cron: '0 21 * * 4'
jobs:
CodeQL-Build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@@ -1,50 +0,0 @@
on: ["push", "pull_request"]
name: Coveralls
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
uses: actions/setup-node@v1
with:
node-version: 12.x
- name: npm install, npm test:coverage
run: |
npm install
npm run test:coverage
env:
CI: true
ADYEN_API_KEY: ${{ secrets.ADYEN_API_KEY }}
ADYEN_MERCHANT: ${{ secrets.ADYEN_MERCHANT }}
ADYEN_PASSWORD: ${{ secrets.ADYEN_PASSWORD }}
ADYEN_REVIEWPAYOUT_APIKEY: ${{ secrets.ADYEN_REVIEWPAYOUT_APIKEY }}
ADYEN_REVIEWPAYOUT_PASSWORD: ${{ secrets.ADYENREVIEWPAYOUT_PASSWORD }}
ADYEN_REVIEWPAYOUT_USER: ${{ secrets.ADYENREVIEWPAYOUT_USER }}
ADYEN_STOREPAYOUT_APIKEY: ${{ secrets.ADYEN_STOREPAYOUT_APIKEY }}
ADYEN_STOREPAYOUT_PASSWORD: ${{ secrets.ADYEN_STOREPAYOUT_PASSWORD }}
ADYEN_STOREPAYOUT_USER: ${{ secrets.ADYEN_STOREPAYOUT_USER }}
ADYEN_USER: ${{ secrets.ADYEN_USER }}
ADYEN_MARKETPLACE_USER: ${{ secrets.ADYEN_MARKETPLACE_USER }}
ADYEN_MARKETPLACE_PASSWORD: ${{ secrets.ADYEN_MARKETPLACE_PASSWORD }}
ADYEN_TERMINAL_APIKEY: ${{ secrets.ADYEN_TERMINAL_APIKEY }}
ADYEN_TERMINAL_POIID: ${{ secrets.ADYEN_TERMINAL_POIID }}
ADYEN_TERMINAL_MERCHANT: ${{ secrets.ADYEN_TERMINAL_MERCHANT }}
- name: Coveralls Parallel
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: ./coverage/lcov.info # optional (default value)
- name: Coveralls Finished
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,42 +0,0 @@
name: Node.js CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [10.x, 12.x, 13.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: npm install, lint and test
run: |
npm install
npm run lint:fix
npm run lint
npm test
env:
CI: true
ADYEN_API_KEY: ${{ secrets.ADYEN_API_KEY }}
ADYEN_MERCHANT: ${{ secrets.ADYEN_MERCHANT }}
ADYEN_PASSWORD: ${{ secrets.ADYEN_PASSWORD }}
ADYEN_REVIEWPAYOUT_APIKEY: ${{ secrets.ADYEN_REVIEWPAYOUT_APIKEY }}
ADYEN_REVIEWPAYOUT_PASSWORD: ${{ secrets.ADYENREVIEWPAYOUT_PASSWORD }}
ADYEN_REVIEWPAYOUT_USER: ${{ secrets.ADYENREVIEWPAYOUT_USER }}
ADYEN_STOREPAYOUT_APIKEY: ${{ secrets.ADYEN_STOREPAYOUT_APIKEY }}
ADYEN_STOREPAYOUT_PASSWORD: ${{ secrets.ADYEN_STOREPAYOUT_PASSWORD }}
ADYEN_STOREPAYOUT_USER: ${{ secrets.ADYEN_STOREPAYOUT_USER }}
ADYEN_USER: ${{ secrets.ADYEN_USER }}
ADYEN_MARKETPLACE_USER: ${{ secrets.ADYEN_MARKETPLACE_USER }}
ADYEN_MARKETPLACE_PASSWORD: ${{ secrets.ADYEN_MARKETPLACE_PASSWORD }}
ADYEN_TERMINAL_APIKEY: ${{ secrets.ADYEN_TERMINAL_APIKEY }}
ADYEN_TERMINAL_POIID: ${{ secrets.ADYEN_TERMINAL_POIID }}
ADYEN_TERMINAL_MERCHANT: ${{ secrets.ADYEN_TERMINAL_MERCHANT }}

View File

@@ -1,22 +0,0 @@
name: Node.js Package
on:
workflow_dispatch
jobs:
publish-npm:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
registry-url: https://registry.npmjs.org/
- run: |
npm install
echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc
npm run build
npm publish
env:
GITHUB_TOKEN: ${{ secrets.USER_GITHUB_TOKEN }}
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}

View File

@@ -1,21 +0,0 @@
name: "Sonarcloud Analysis"
on: ["push", "pull_request"]
jobs:
sonarcloud-analysis:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# Disabling shallow clone to improve relevancy of SonarCloud reporting
fetch-depth: 0
- name: SonarCloud integration
uses: sonarsource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

3
.gitignore vendored
View File

@@ -11,5 +11,4 @@ node_modules
.ssh/
.viminfo
coverage/
.env
lib/
dist/

View File

@@ -7,5 +7,4 @@ src/
tsconfig.json
jest.config.js
tslint.json
webpack.config.js
.github
webpack.config.js

View File

@@ -1,20 +1,12 @@
{
"git": {
"tagName": "v${version}",
"changelog": "npx auto-changelog --hide-credit --stdout --commit-limit false --unreleased-only -t keepachangelog",
"commitMessage": "Release ${version}",
"tag": true,
"requireCleanWorkingDir": false
"changelog": "npx auto-changelog --stdout --commit-limit false -u"
},
"github": {
"release": true,
"releaseName": "Adyen Node API Library v${version}"
"release": true
},
"hooks": {
"after:bump": [
"npm run build",
"npx auto-changelog -p"
],
"after:release": "echo Successfully released ${name} v${version} to ${repo.repository}."
"after:bump": "npx auto-changelog -p"
}
}

View File

@@ -1,13 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the ODPi Egeria project.
# General settings
sonar.organization=adyen
sonar.projectKey=Adyen_adyen-node-api-library
# Path to sources
#sonar.sources=.
sonar.exclusions=src/__mocks__/**/* , src/typings/**/* , src/__tests__/**/*
sonar.exclusions=src/__mocks__/*
sonar.exclusions=src/typings/*
#sonar.inclusions=
# Path to tests

25
.travis.yml Normal file
View File

@@ -0,0 +1,25 @@
language: node_js
node_js:
- "8"
- stable
cache: yarn
script:
- yarn run lint:fix
- yarn run lint
- yarn run test
jobs:
include:
- stage: npm release
if: tag IS present
node_js: stable
script: yarn run build
deploy:
provider: npm
email: "$NPM_EMAIL"
api_key: "$NPM_TOKEN"
skip_cleanup: true
on:
tags: true
- stage: Produce Coverage
node_js: stable
script: jest --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2020 Adyen
Copyright (c) 2019 Adyen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,35 +1,28 @@
# Adyen Node.js API Library
![Node.js CI](https://github.com/Adyen/adyen-node-api-library/workflows/Node.js%20CI/badge.svg)
[![Build Status](https://travis-ci.org/Adyen/adyen-node-api-library.svg?branch=master)](https://travis-ci.org/Adyen/adyen-node-api-library)
[![Coverage Status](https://coveralls.io/repos/github/Adyen/adyen-node-api-library/badge.svg?branch=master)](https://coveralls.io/github/Adyen/adyen-node-api-library?branch=master)
[![Downloads](https://img.shields.io/npm/dm/@adyen/api-library.svg)](https://www.npmjs.com/package/@adyen/api-library)
![npm bundle size (scoped)](https://img.shields.io/bundlephobia/minzip/@adyen/api-library.svg)
[![Version](https://img.shields.io/npm/v/@adyen/api-library.svg)](https://www.npmjs.com/package/@adyen/api-library)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=Adyen_adyen-node-api-library&metric=alert_status)](https://sonarcloud.io/dashboard?id=Adyen_adyen-node-api-library)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/Adyen/adyen-node-api-library.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Adyen/adyen-node-api-library/alerts/)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Adyen/adyen-node-api-library.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Adyen/adyen-node-api-library/context:javascript)
This is the officially supported NodeJS library for using Adyen's APIs.
The Adyen API Library for NodeJS enables you to work with Adyen APIs.
## Integration
The Library supports all APIs under the following services:
* [Checkout API](https://docs.adyen.com/api-explorer/#/CheckoutService/v67/overview): Our latest integration for accepting online payments. Current supported version: **v67**
* [Payments API](https://docs.adyen.com/api-explorer/#/Payment/v64/overview): Our classic integration for online payments. Current supported version: **v64**
* [Recurring API](https://docs.adyen.com/api-explorer/#/Recurring/v49/overview): Endpoints for managing saved payment details. Current supported version: **v49**
* [Payouts API](https://docs.adyen.com/api-explorer/#/Payout/v64/overview): Endpoints for sending funds to your customers. Current supported version: **v64**
* [Platforms APIs](https://docs.adyen.com/platforms/api): Set of APIs when using Adyen for Platforms.
* [Account API](https://docs.adyen.com/api-explorer/#/Account/v6/overview) Current supported version: **v6**
* [Fund API](https://docs.adyen.com/api-explorer/#/Fund/v6/overview) Current supported version: **v6**
* [Notification Configuration API](https://docs.adyen.com/api-explorer/#/NotificationConfigurationService/v6/overview) Current supported version: **v6**
* [Local/Cloud-based Terminal API](https://docs.adyen.com/point-of-sale/terminal-api-reference): Our point-of-sale integration.
* [BIN lookup API](https://docs.adyen.com/api-explorer/#/BinLookup/v50/overview): The BIN Lookup API provides endpoints for retrieving information based on a given BIN. Current supported version: **v50**
* [x] checkout
* [x] checkout utility
* [x] payments
* [x] modifications
* [x] payouts
* [x] recurring
* [x] notifications
* [x] BIN lookup
For more information, refer to our [documentation](https://docs.adyen.com/) or the [API Explorer](https://docs.adyen.com/api-explorer/).
## Requirements
## Prerequisites
- [Adyen test account](https://docs.adyen.com/get-started-with-adyen)
- [API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). For testing, your API credential needs to have the [API PCI Payments role](https://docs.adyen.com/development-resources/api-credentials#roles).
- Node 10 or higher
* Node 8.1.1 or higher
## Installation
@@ -41,28 +34,12 @@ You can use NPM to add our library to your project
npm install --save @adyen/api-library
```
Alternatively, you can download the [release on GitHub](https://github.com/Adyen/adyen-node-api-library/releases).
## Documentation
* https://docs.adyen.com/developers/development-resources/libraries
* https://docs.adyen.com/developers/checkout/api-integration
## HTTP Client Configuration
## Using the library
### General use with API key
Set up the client as a singleton resource; you can then use it to create service objects for the API calls that you make to Adyen:
```typescript
const client = new Client({apiKey: "YOUR_API_KEY", environment: "TEST"});
```
### General use with API key for live environment
```typescript
const client = new Client({apiKey: "YOUR_API_KEY", environment: "LIVE"});
```
### General use with basic auth
```typescript
const client = new Client({username: "YOUR_USERNAME", password: "YOUR_PASSWORD", environment: "TEST"});
```
### Custom HTTP Client Configuration
By default, NodeJS [https](https://nodejs.org/api/https.html) will be used to submit requests to the API. But you can change that by injecting your own HttpClient on your client instance. In the example below, we use `axios`:
```javascript
@@ -109,23 +86,18 @@ client.httpClient = httpClient;
...
```
### Example integration
For a closer look at how our NodeJS library works, clone our [example integration](https://github.com/adyen-examples/adyen-node-online-payments). This includes commented code, highlighting key features and concepts, and examples of API calls that can be made using the library.
## Support
## Contributing
If you have any problems, questions or suggestions, create an issue here or send your inquiry to support@adyen.com.
## Contributing
We strongly encourage you to join us in contributing to this repository so everyone can benefit from:
* New features and functionality
* Resolved bug fixes and issues
* Any general improvements
Read our [**contribution guidelines**](CONTRIBUTING.md) to find out how to create a pull request.
## Support
If you have a feature request, or spotted a bug or a technical problem, create a GitHub issue. For other questions, contact our [support team](https://support.adyen.com/).
Read our [**contribution guidelines**](CONTRIBUTING.md) to find out how.
## Licence
This repository is available under the [MIT license](LICENSE).
## See also
* [example integration](https://github.com/adyen-examples/adyen-node-online-payments)
MIT license. For more information, see the LICENSE file.

25
babel.config.js Executable file
View File

@@ -0,0 +1,25 @@
module.exports = {
presets: [
"@babel/env",
[
"@babel/preset-typescript",
{
targets: {
node: "current"
}
}
]
],
plugins: [
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread"
],
env: {
test: {
plugins: [
"@babel/plugin-transform-runtime",
"@babel/plugin-transform-typescript"
]
}
}
}

View File

@@ -1,20 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import "jest-ts-auto-mock"

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Adyen Node API Library
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -26,18 +28,14 @@ module.exports = {
coveragePathIgnorePatterns: [
"<rootDir>/src/typings"
],
setupFiles: ["<rootDir>config.ts", "dotenv/config"],
testMatch: [
"**/src/__tests__/**/*.spec.ts"
unmockedModulePathPatterns: [
"/dist"
],
roots: ['<rootDir>/src'],
transform: {
".ts": "ts-jest"
},
globals: {
"ts-jest": {
compiler: "ttypescript",
transformIgnorePatterns: ['^.+\\\\.js$']
}
},
testMatch: [
"**/__tests__/*.ts"
],
testPathIgnorePatterns : [
"/node_modules",
"/dist"
]
};

11056
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,12 @@
{
"name": "@adyen/api-library",
"version": "8.2.0",
"version": "2.2.1-rc.4",
"description": "The Adyen API Library for NodeJS enables you to work with Adyen APIs.",
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"main": "dist/lib/src/index.js",
"types": "dist/lib/src/index.d.ts",
"module": "dist/lib-esm/src/index.js",
"engines": {
"node": ">=10"
"node": ">=8.1.1"
},
"repository": {
"type": "git",
@@ -24,41 +25,45 @@
},
"homepage": "https://github.com/Adyen/adyen-node-api-library#readme",
"scripts": {
"build": "tsc",
"clean": "rm -rf ./dist",
"build": "npm run clean && tsc && tsc -m es6 --outDir dist/lib-esm && webpack",
"lint": "eslint 'src/**/*.ts'",
"lint:fix": "eslint --fix 'src/**/*.ts'",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"release": "release-it"
"preversion": "npm test",
"version": "npm run build && git add -A dist",
"postversion": "git push && git push --tags && rm -rf build/temp",
"release": "release-it --no-npm.publish"
},
"author": "Ricardo Ambrogi",
"license": "MIT",
"devDependencies": {
"@types/jest": "26.0.23",
"@types/nock": "11.1.0",
"@typescript-eslint/eslint-plugin": "2.34.0",
"@typescript-eslint/parser": "2.34.0",
"acorn": "^8.0.1",
"coveralls": "3.1.0",
"dotenv": "^10.0.0",
"@babel/core": "7.8.3",
"@babel/plugin-proposal-class-properties": "7.8.3",
"@babel/plugin-proposal-object-rest-spread": "7.8.3",
"@babel/plugin-transform-runtime": "7.8.3",
"@babel/plugin-transform-typescript": "7.8.3",
"@babel/preset-env": "7.8.3",
"@babel/preset-typescript": "7.8.3",
"@babel/runtime": "7.8.3",
"@types/nock": "10.0.3",
"@typescript-eslint/eslint-plugin": "2.16.0",
"@typescript-eslint/parser": "2.16.0",
"babel-loader": "8.0.6",
"coveralls": "3.0.9",
"eslint": "6.8.0",
"jest": "25.5.4",
"jest-ts-auto-mock": "^2.0.0",
"kind-of": "^6.0.3",
"minimist": ">=1.2.3",
"nock": "13.1.0",
"release-it": "14.10.0",
"ts-auto-mock": "^2.6.5",
"ts-jest": "25.5.1",
"ts-loader": "8.0.10",
"ttypescript": "^1.5.10",
"typescript": "3.9.10"
"jest": "24.9.0",
"nock": "11.7.2",
"release-it": "12.4.3",
"ts-jest": "24.3.0",
"ts-loader": "6.2.1",
"typescript": "3.7.4",
"webpack": "4.41.5",
"webpack-cli": "3.3.10"
},
"dependencies": {
"https-proxy-agent": "5.0.0"
},
"optionalDependencies": {
"@types/node": "14.0.9"
"@types/node": "13.1.7",
"@types/jest": "24.0.25",
"https-proxy-agent": "4.0.0"
}
}

5
renovate.json Normal file
View File

@@ -0,0 +1,5 @@
{
"extends": [
"config:base"
]
}

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -27,108 +29,70 @@ import {
MessageType,
PaymentRequest,
PaymentTransaction,
ReversalReasonType,
ReversalRequest,
SaleData,
SaleToPOIRequest,
SaleToPoiRequest,
TerminalApiRequest,
TransactionIdentification
} from "../typings/terminal/models";
TransactionIdentification,
} from "../typings/terminal";
export const createClient = (apiKey = process.env.ADYEN_API_KEY): Client => {
export const createMockClientFromResponse = (): Client => {
const config: Config = new Config();
config.terminalApiCloudEndpoint = Client.TERMINAL_API_ENDPOINT_TEST;
config.terminalApiLocalEndpoint = "https://mocked_local_endpoint.com";
config.hmacKey = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
config.endpoint = Client.ENDPOINT_TEST;
config.checkoutEndpoint = Client.CHECKOUT_ENDPOINT_TEST;
config.marketPayEndpoint = Client.MARKETPAY_ENDPOINT_TEST;
config.apiKey = apiKey;
config.marketPayEndpoint = Client.MARKETPAY_ENDPOINT_TEST;
config.apiKey = "MOCKED_API_KEY";
return new Client({ config });
const client: Client = new Client({ config });
return client;
};
export const createBasicAuthClient = (): Client => {
return new Client({
username: process.env.ADYEN_USER!,
password: process.env.ADYEN_PASSWORD!,
environment: "TEST",
applicationName: "adyen-node-api-library"
});
};
const id = Math.floor(Math.random() * Math.floor(10000000)).toString();
const getMessageHeader = ({ messageCategory = MessageCategoryType.Payment }: { messageCategory?: MessageCategoryType } = {}): MessageHeader => ({
messageCategory,
messageClass: MessageClassType.Service,
messageType: MessageType.Request,
pOIID: process.env.ADYEN_TERMINAL_POIID!,
protocolVersion: "3.0",
saleID: id,
serviceID: id,
});
const timestamp = (): string => new Date().toISOString();
const transactionIdentification: TransactionIdentification = {
timeStamp: timestamp(),
transactionID: id,
};
const saleData: SaleData = {
saleTransactionID: transactionIdentification,
saleToAcquirerData: {
applicationInfo: {
merchantApplication: {
version: "1",
name: "test"
}
},
metadata: {
someMetaDataKey1: "YOUR_VALUE",
someMetaDataKey2: "YOUR_VALUE"
},
}
};
const amountsReq: AmountsReq = {
currency: "EUR",
requestedAmount: 1,
};
const paymentTransaction: PaymentTransaction = {
amountsReq,
};
const paymentRequest: PaymentRequest = {
paymentTransaction,
saleData,
};
const getReversalRequest = (poiTransaction: TransactionIdentification): ReversalRequest => ({
originalPOITransaction: {
pOITransactionID: {
transactionID: poiTransaction.transactionID,
timeStamp: poiTransaction.timeStamp
},
},
reversalReason: ReversalReasonType.MerchantCancel
});
const getSaleToPOIRequest = (messageHeader: MessageHeader, request: Partial<SaleToPOIRequest>): SaleToPOIRequest => ({
messageHeader,
...request
});
export const createTerminalAPIPaymentRequest = (): TerminalApiRequest => {
const messageHeader = getMessageHeader();
const saleToPOIRequest = getSaleToPOIRequest(messageHeader, { paymentRequest });
return { saleToPOIRequest };
};
export const createTerminalAPIRefundRequest = (transactionIdentification: TransactionIdentification): TerminalApiRequest => {
const messageHeader = getMessageHeader({ messageCategory: MessageCategoryType.Reversal });
const saleToPOIRequest = getSaleToPOIRequest(messageHeader, { reversalRequest: getReversalRequest(transactionIdentification) });
return { saleToPOIRequest };
const messageHeader: MessageHeader = {
messageCategory: MessageCategoryType.Payment,
messageClass: MessageClassType.Service,
messageType: MessageType.Request,
poiid: "P400Plus-123456789",
protocolVersion: "3.0",
saleId: "001",
serviceId: "001",
};
const timestamp = new Date().toISOString();
const transactionIdentification: TransactionIdentification = {
timeStamp: timestamp,
transactionId: "001",
};
const saleData: SaleData = {
saleTransactionId: transactionIdentification,
};
const amountsReq: AmountsReq = {
currency: "EUR",
requestedAmount: 1,
};
const paymentTransaction: PaymentTransaction = {
amountsReq: amountsReq,
};
const paymentRequest: PaymentRequest = {
paymentTransaction: paymentTransaction,
saleData: saleData,
};
const saleToPOIRequest: SaleToPoiRequest = {
messageHeader: messageHeader,
paymentRequest: paymentRequest,
};
const terminalApiRequest: TerminalApiRequest = {
saleToPoiRequest: saleToPOIRequest,
};
return terminalApiRequest;
};

View File

@@ -1,26 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const originKeysSuccess = JSON.stringify({
originKeys: {
"https://www.your-domain.com": "pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4xLmNvbQ.UEwIBmW9-c_uXo5wSEr2w8Hz8hVIpujXPHjpcEse3xI",
"https://www.your-domain2.com": "pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4yLmNvbQ.EP6eXBJKk0t7-QIUl6e_b1qMuMHGepxG_SlUqxAYrfY",
"https://www.your-domain3.com": "pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4zLmNvbQ.fUvflu-YIdZSsLEH8Qqmr7ksE4ag_NYiiMXK0s6aq_4",
},
});

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentMethodsSuccess = JSON.stringify({
paymentMethods: [

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentSessionError = {
statusCode: 422,

File diff suppressed because one or more lines are too long

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const paymentMethodsError = {
errorCode: "901",
errorType: "security",

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentDetailsError = {
statusCode: 422,

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentDetailsSuccess = JSON.stringify({
pspReference: "8515232733321252",

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentsError = JSON.stringify({
statusCode: 422,

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentsResultError = JSON.stringify({
statusCode: 422,

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentsResultMultibancoSuccess = {
additionalData: {

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentsResultSuccess = JSON.stringify({
pspReference: "8535253563623704",

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* tslint:disable */
export const paymentsSuccess = JSON.stringify({
additionalData: {
@@ -29,7 +10,6 @@ export const paymentsSuccess = JSON.stringify({
alias: "H167852639363479",
cardPaymentMethod: "visa",
cardIssuingCountry: "NL",
"recurring.recurringDetailReference": "8415883203388055",
},
fraudResult: {
accountScore: 0,

View File

@@ -0,0 +1,7 @@
export const originKeysSuccess = JSON.stringify({
originKeys: {
"https://www.your-domain1.com": "pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4xLmNvbQ.UEwIBmW9-c_uXo5wSEr2w8Hz8hVIpujXPHjpcEse3xI",
"https://www.your-domain2.com": "pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4yLmNvbQ.EP6eXBJKk0t7-QIUl6e_b1qMuMHGepxG_SlUqxAYrfY",
"https://www.your-domain3.com": "pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4zLmNvbQ.fUvflu-YIdZSsLEH8Qqmr7ksE4ag_NYiiMXK0s6aq_4",
},
});

View File

@@ -22,4 +22,4 @@
}
}
]
}
}

File diff suppressed because one or more lines are too long

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const disableSuccess = {
response: "[detail-successfully-disabled]",
};

View File

@@ -1,22 +1,3 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const listRecurringDetailsSuccess = {
creationDate: "2017-03-01T10:53:11.000",
details: [

View File

@@ -1,28 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const notifyShopperSuccess = {
"message": "Request Processed Successfully",
"resultCode": "Success",
"shopperNotificationReference": "9915003646742627",
"storedPaymentMethodId": "8415995487234100",
"pspReference": "9915003646742627",
"reference": "Example reference",
"displayedReference": "Example displayed reference"
};

View File

@@ -1,20 +1 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const asyncRes = "ok";

View File

@@ -1,23 +1,4 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const localSecuredRes = {
export const localSecuredRes = JSON.stringify({
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
@@ -28,11 +9,326 @@ export const localSecuredRes = {
SaleID: "325488592",
ServiceID: "325488592"
},
PaymentResponse: {}
paymentResponse: {
paymentReceipt: [
{
documentQualifier: "CashierReceipt",
outputContent: {
outputFormat: "Text",
outputText: [
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "key=header1"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "key=header2"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "name=MERCHANT%20COPY&key=merchantTitle"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Date&value=08%2f05%2f19&key=txdate"
},
{
endOfLineFlag: true,
text: "name=Time&value=15%3a25%3a15&key=txtime"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Card&value=%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a0010&key=pan"
},
{
endOfLineFlag: true,
text: "name=PAN%20seq.&value=01&key=panSeq"
},
{
endOfLineFlag: true,
text: "name=Pref.%20name&value=PPC%20MCD%2001%20v2%202&key=preferredName"
},
{
endOfLineFlag: true,
text: "name=Card%20type&value=mc&key=cardType"
},
{
endOfLineFlag: true,
text: "name=Payment%20method&value=mc&key=paymentMethod"
},
{
endOfLineFlag: true,
text: "name=Payment%20variant&value=mc&key=paymentMethodVariant"
},
{
endOfLineFlag: true,
text: "name=Entry%20mode&value=Contactless%20chip&key=posEntryMode"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=AID&value=A0000000041010&key=aid"
},
{
endOfLineFlag: true,
text: "name=MID&value=1000&key=mid"
},
{
endOfLineFlag: true,
text: "name=TID&value=P400Plus-275039202&key=tid"
},
{
endOfLineFlag: true,
text: "name=PTID&value=75039202&key=ptid"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Auth.%20code&value=123456&key=authCode"
},
{
endOfLineFlag: true,
text: "name=Tender&value=4r7i001557325515012&key=txRef"
},
{
endOfLineFlag: true,
text: "name=Reference&value=999&key=mref"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Type&value=GOODS_SERVICES&key=txtype"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "name=TOTAL&value=%e2%82%ac%c2%a01.00&key=totalAmount"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "name=APPROVED&key=approved"
}
]
},
requiredSignatureFlag: false
},
{
documentQualifier: "CustomerReceipt",
outputContent: {
outputFormat: "Text",
outputText: [
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "key=header1"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "key=header2"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "name=CARDHOLDER%20COPY&key=cardholderHeader"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Date&value=08%2f05%2f19&key=txdate"
},
{
endOfLineFlag: true,
text: "name=Time&value=15%3a25%3a15&key=txtime"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Card&value=%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a0010&key=pan"
},
{
endOfLineFlag: true,
text: "name=PAN%20seq.&value=01&key=panSeq"
},
{
endOfLineFlag: true,
text: "name=Pref.%20name&value=PPC%20MCD%2001%20v2%202&key=preferredName"
},
{
endOfLineFlag: true,
text: "name=Card%20type&value=mc&key=cardType"
},
{
endOfLineFlag: true,
text: "name=Payment%20method&value=mc&key=paymentMethod"
},
{
endOfLineFlag: true,
text: "name=Payment%20variant&value=mc&key=paymentMethodVariant"
},
{
endOfLineFlag: true,
text: "name=Entry%20mode&value=Contactless%20chip&key=posEntryMode"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=AID&value=A0000000041010&key=aid"
},
{
endOfLineFlag: true,
text: "name=MID&value=1000&key=mid"
},
{
endOfLineFlag: true,
text: "name=TID&value=P400Plus-275039202&key=tid"
},
{
endOfLineFlag: true,
text: "name=PTID&value=75039202&key=ptid"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Auth.%20code&value=123456&key=authCode"
},
{
endOfLineFlag: true,
text: "name=Tender&value=4r7i001557325515012&key=txRef"
},
{
endOfLineFlag: true,
text: "name=Reference&value=999&key=mref"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Type&value=GOODS_SERVICES&key=txtype"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "name=TOTAL&value=%e2%82%ac%c2%a01.00&key=totalAmount"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
characterStyle: "Bold",
endOfLineFlag: true,
text: "name=APPROVED&key=approved"
},
{
endOfLineFlag: true,
text: "key=filler"
},
{
endOfLineFlag: true,
text: "name=Please%20retain%20for%20your%20records&key=retain"
},
{
endOfLineFlag: true,
text: "name=Thank%20you&key=thanks"
}
]
},
requiredSignatureFlag: false
}
],
paymentResult: {
amountsResp: {
authorizedAmount: 1,
currency: "EUR"
},
onlineFlag: true,
paymentAcquirerData: {
acquirerPoiid: "P400Plus-275039202",
acquirerTransactionId: {
timeStamp: "2019-05-08T14:25:15.000Z",
transactionId: "8815573255107661"
},
approvalCode: "123456",
merchantId: "TestMerchantRenatoTest"
},
paymentInstrumentData: {
cardData: {
cardCountryCode: "056",
entryMode: [
"Contactless"
],
maskedPan: "541333 **** 0010",
paymentBrand: "mc",
sensitiveCardData: {
cardSeqNumb: "01",
expiryDate: "1225"
}
},
paymentInstrumentType: "Card"
}
},
poiData: {
poiReconciliationId: "1000",
poiTransactionId: {
timeStamp: "2019-05-08T14:25:15.000Z",
transactionId: "4r7i001557325515012.8815573255107661"
}
},
response: {
additionalResponse: "tid=75039202&AID=A0000000041010&transactionType=GOODS_SERVICES&backendGiftcardIndicator=false&expiryYear=2025&acquirerAccountCode=TestPmmAcquirerAccount&alias=K182596230843790&posOriginalAmountCurrency=EUR&giftcardIndicator=false&authorisedAmountValue=100&pspReference=8815573255107661&paymentMethodVariant=mc&cardHolderName=N%2fA&refusalReasonRaw=APPROVED&authorisationMid=1000&expiryDate=12%2f2025&applicationPreferredName=PPC%20MCD%2001%20v2%202&isCardCommercial=unknown&acquirerCode=TestPmmAcquirer&txtime=15%3a25%3a15&iso8601TxDate=2019-05-08T14%3a25%3a15.0000000%2b0000&cardType=mc&posOriginalAmountValue=100&offline=false&aliasType=Default&txdate=08-05-2019&paymentMethod=mc&cvcResult=0%20Unknown&startYear=2030&tc=A767D7547D930504&avsResult=0%20Unknown&cardIssueNumber=1&mid=1000&merchantReference=999&transactionReferenceNumber=8815573255107661&expiryMonth=12&cardSummary=0010&posTotalAmountValue=100&posAuthAmountCurrency=EUR&cardHolderVerificationMethodResults=1F0302&authCode=123456&cardIssuerCountryId=056&shopperCountry=NL&posEntryMode=CLESS_CHIP&startMonth=34&fundingSource=CREDIT&cardScheme=mc&cardBin=541333&posAuthAmountValue=100",
result: "Success"
},
saleData: {
saleTransactionId: {
timeStamp: "2019-05-08T14:24:48.598Z",
transactionId: "999"
}
}
}
}
};
});
export const localEncRes = {
export const localEncRes = JSON.stringify({
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
@@ -138,9 +434,9 @@ export const localEncRes = {
Nonce: "9iiJMpzKfYs3106ozIKNFQ==",
},
},
};
});
export const wrongEncRes = {
export const wrongEncRes = JSON.stringify({
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
@@ -246,4 +542,4 @@ export const wrongEncRes = {
Nonce: "9iiJMpzKfYs3106ozIKNFQ==",
},
},
};
});

View File

@@ -1,32 +1,13 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
export const syncRes = {
export const syncRes = JSON.stringify({
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
MessageClass: "Service",
MessageType: "Response",
POIID: process.env.ADYEN_TERMINAL_POIID,
POIID: "P400Plus-123456789",
ProtocolVersion: "3.0",
SaleID: "001",
ServiceID: "001",
ServiceID: "1234567890",
},
PaymentResponse: {
POIData: {
@@ -345,23 +326,4 @@ export const syncRes = {
},
},
},
};
export const syncRefund = {
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
MessageClass: "Service",
MessageType: "Response",
POIID: process.env.ADYEN_TERMINAL_POIID,
ProtocolVersion: "3.0",
SaleID: "001",
ServiceID: "001",
},
ReversalResponse: {
Response: {
Result: "Success"
}
}
}
};
});

View File

@@ -11,24 +11,34 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient } from "../__mocks__/base";
import {createMockClientFromResponse} from "../__mocks__/base";
import BinLookup from "../services/binLookup";
import Client from "../client";
import HttpClientException from "../httpClient/httpClientException";
const threeDSAvailabilitySuccess = {
binDetails: {
issuerCountry: "NL"
},
dsPublicKeys: [{
brand: "visa",
directoryServerId: "F013371337",
publicKey: "eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiI4VFBxZkFOWk4xSUEzcHFuMkdhUVZjZ1g4LUpWZ1Y0M2diWURtYmdTY0N5SkVSN3lPWEJqQmQyaTBEcVFBQWpVUVBXVUxZU1FsRFRKYm91bVB1aXVoeVMxUHN2NTM4UHBRRnEySkNaSERkaV85WThVZG9hbmlrU095c2NHQWtBVmJJWHA5cnVOSm1wTTBwZ0s5VGxJSWVHYlE3ZEJaR01OQVJLQXRKeTY3dVlvbVpXV0ZBbWpwM2d4SDVzNzdCR2xkaE9RUVlQTFdybDdyS0pLQlUwNm1tZlktUDNpazk5MmtPUTNEak02bHR2WmNvLThET2RCR0RKYmdWRGFmb29LUnVNd2NUTXhDdTRWYWpyNmQyZkppVXlqNUYzcVBrYng4WDl6a1c3UmlxVno2SU1qdE54NzZicmg3aU9Vd2JiWmoxYWF6VG1GQ2xEb0dyY2JxOV80Nnc9PSJ9"
}],
threeDS1Supported: true,
threeDS2CardRangeDetails: [],
threeDS2supported: false
threeDS2CardRangeDetails: [{
brandCode: "visa",
endRange: "411111111111",
startRange: "411111111111",
threeDS2Version: "2.1.0",
threeDSMethodURL: "https://pal-test.adyen.com/threeds2simulator/acs/startMethod.shtml"
}],
threeDS2supported: true
};
let client: Client;
@@ -36,23 +46,15 @@ let binLookup: BinLookup;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient();
client = createMockClientFromResponse();
binLookup = new BinLookup(client);
scope = nock(`${client.config.endpoint}${Client.BIN_LOOKUP_PAL_SUFFIX}${Client.BIN_LOOKUP_API_VERSION}`);
});
afterEach((): void => {
nock.cleanAll();
});
describe("Bin Lookup", function (): void {
test.each([false, true])("should succeed on get 3ds availability. isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
it("should succeed on get 3ds availability", async function (): Promise<void> {
const threeDSAvailabilityRequest: IBinLookup.ThreeDSAvailabilityRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
merchantAccount: "MOCK_MERCHANT_ACCOUNT",
brands: ["randomBrand"],
cardNumber: "4111111111111111"
};
@@ -62,11 +64,10 @@ describe("Bin Lookup", function (): void {
const response = await binLookup.get3dsAvailability(threeDSAvailabilityRequest);
expect(response).toEqual<IBinLookup.ThreeDSAvailabilityResponse>(threeDSAvailabilitySuccess);
expect(response).toEqual(threeDSAvailabilitySuccess);
});
test.each([false, true])("should fail with invalid merchant. isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
it("should fail with invalid merchant", async function (): Promise<void> {
const threeDSAvailabilityRequest: { [key: string]: undefined|string|[] } = {
merchantAccount: undefined,
cardNumber: "4111111111111",
@@ -84,13 +85,9 @@ describe("Bin Lookup", function (): void {
}
});
test.each([false, true])("should succeed on get cost estimate. isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
const expected = {
costEstimateAmount: {
currency: "EUR",
value: 10
},
it("should succeed on get cost estimate", async function (): Promise<void> {
const response = {
cardBin: {summary: "1111"},
resultCode: "Unsupported",
surchargeType: "ZERO"
};
@@ -101,7 +98,7 @@ describe("Bin Lookup", function (): void {
assume3DSecureAuthenticated: true
},
cardNumber: "411111111111",
merchantAccount: process.env.ADYEN_MERCHANT!,
merchantAccount: "MOCKED_MERCHANT_ACC",
merchantDetails: {
countryCode: "NL",
mcc: "7411",
@@ -111,9 +108,9 @@ describe("Bin Lookup", function (): void {
};
scope.post("/getCostEstimate")
.reply(200, expected);
.reply(200, response);
const response = await binLookup.getCostEstimate(costEstimateRequest);
const expected = await binLookup.getCostEstimate(costEstimateRequest);
expect(response).toEqual(expected);
});

View File

@@ -1,26 +1,7 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
/* eslint-disable @typescript-eslint/camelcase */
import checkServerIdentity from "../helpers/checkServerIdentity";
import { PeerCertificate } from "tls";
import {PeerCertificate} from "tls";
const createMockedCertificate = (CN: string): PeerCertificate => ({
subjectaltname: "Adyen B.V",
@@ -48,7 +29,6 @@ const createMockedCertificate = (CN: string): PeerCertificate => ({
valid_from: "Nov 19 15:03:32 2018 GMT",
valid_to: "Nov 11 15:03:32 2048 GMT",
fingerprint: "MOCKED_FINGERPRINT",
fingerprint256: "MOCKED_FINGERPRINT_256",
ext_key_usage: ["1.2.3.4.5.6.7.8"],
serialNumber: "1000",
raw: Buffer.from("test")

View File

@@ -11,54 +11,37 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import {createClient} from "../__mocks__/base";
import { createMockClientFromResponse } from "../__mocks__/base";
import {paymentMethodsSuccess} from "../__mocks__/checkout/paymentMethodsSuccess";
import {paymentsSuccess} from "../__mocks__/checkout/paymentsSuccess";
import {paymentDetailsSuccess} from "../__mocks__/checkout/paymentsDetailsSuccess";
import {paymentSessionSuccess} from "../__mocks__/checkout/paymentSessionSucess";
import {originKeysSuccess} from "../__mocks__/checkout/originkeysSuccess";
import {paymentsResultMultibancoSuccess} from "../__mocks__/checkout/paymentsResultMultibancoSuccess";
import {paymentsResultSuccess} from "../__mocks__/checkout/paymentsResultSucess";
import Client from "../client";
import Checkout from "../services/checkout";
import HttpClientException from "../httpClient/httpClientException";
import {
Amount,
CheckoutBalanceCheckRequest,
CheckoutBalanceCheckResponse,
CheckoutCancelOrderResponse,
CheckoutCreateOrderRequest,
CheckoutCreateOrderResponse,
CheckoutUtilityRequest,
CreatePaymentLinkRequest,
DetailsRequest,
PaymentLinkResource,
PaymentMethodsRequest,
PaymentRequest,
PaymentResponse,
PaymentSetupRequest,
PaymentVerificationRequest,
} from "../typings/checkout/models";
const merchantAccount = process.env.ADYEN_MERCHANT!;
const merchantAccount = "MagentoMerchantTest";
const reference = "Your order number";
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
function createAmountObject(currency: string, value: number): Amount {
function createAmountObject(currency: string, value: number): ICheckout.Amount {
return {
currency,
value,
};
}
function createPaymentsDetailsRequest(): DetailsRequest {
function createPaymentsDetailsRequest(): ICheckout.DetailsRequest {
return {
details: {
MD: "mdValue",
@@ -68,13 +51,14 @@ function createPaymentsDetailsRequest(): DetailsRequest {
};
}
export function createPaymentsCheckoutRequest(): PaymentRequest {
export function createPaymentsCheckoutRequest(): ICheckout.PaymentRequest {
const paymentMethodDetails = {
cvc: "737",
expiryMonth: "10",
expiryYear: "2018",
holderName: "John Smith",
number: "4111111111111111",
type: "scheme",
encryptedCardNumber: "test_4111111111111111",
encryptedExpiryMonth: "test_03",
encryptedExpiryYear: "test_2030",
encryptedSecurityCode: "test_737"
};
return {
@@ -83,60 +67,16 @@ export function createPaymentsCheckoutRequest(): PaymentRequest {
paymentMethod: paymentMethodDetails,
reference,
returnUrl: "https://your-company.com/...",
shopperReference: "shopperReference",
storePaymentMethod: true
};
}
function createPaymentSessionRequest(): PaymentSetupRequest {
function createPaymentSessionRequest(): ICheckout.PaymentSetupRequest {
return {
amount: createAmountObject("USD", 1000),
countryCode: "NL",
merchantAccount,
reference,
returnUrl: "https://your-company.com/...",
channel: PaymentSetupRequest.ChannelEnum.Web,
sdkVersion: "3.7.0"
};
}
function getPaymentLinkSuccess(expiresAt: string): PaymentLinkResource {
return {
amount: createAmountObject("USD", 1000),
expiresAt,
reference,
url: "paymentLinkResponse.url",
id: "mocked_id",
merchantAccount,
status: PaymentLinkResource.StatusEnum.Active
};
}
function createPaymentLinkRequest(): CreatePaymentLinkRequest {
return {
allowedPaymentMethods: ["scheme", "boletobancario"],
amount: createAmountObject("USD", 1000),
countryCode: "BR",
merchantAccount,
shopperReference: "shopperReference",
shopperEmail: "test@email.com",
shopperLocale: "pt_BR",
billingAddress: {
street: "Roque Petroni Jr",
postalCode: "59000060",
city: "São Paulo",
houseNumberOrName: "999",
country: "BR",
stateOrProvince: "SP"
},
deliveryAddress: {
street: "Roque Petroni Jr",
postalCode: "59000060",
city: "São Paulo",
houseNumberOrName: "999",
country: "BR",
stateOrProvince: "SP"
},
reference
};
}
@@ -145,98 +85,93 @@ let checkout: Checkout;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient();
client = createMockClientFromResponse();
scope = nock(`${client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}`);
checkout = new Checkout(client);
});
afterEach(() => {
nock.cleanAll();
});
describe("Checkout", (): void => {
test.each([false, true])("should make a payment. isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should make a payment", async (): Promise<void> => {
scope.post("/payments")
.reply(200, paymentsSuccess);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: PaymentResponse = await checkout.payments(paymentsRequest);
expect(paymentsResponse.pspReference).toBeTruthy();
const paymentsRequest: ICheckout.PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: ICheckout.PaymentResponse = await checkout.payments(paymentsRequest);
expect(paymentsResponse.pspReference).toEqual("8535296650153317");
});
test.each([false, true])("should return correct Exception, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should return correct Exception", async (): Promise<void> => {
try {
scope.post("/payments")
.reply(401);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const paymentsRequest: ICheckout.PaymentRequest = createPaymentsCheckoutRequest();
await checkout.payments(paymentsRequest);
} catch (e) {
expect(e instanceof HttpClientException).toBeTruthy();
}
});
test.each([false, true])("should have valid payment methods, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
const paymentMethodsRequest: PaymentMethodsRequest = {merchantAccount: "MagentoMerchantTest"};
it("should have valid payment methods", async (): Promise<void> => {
const paymentMethodsRequest: ICheckout.PaymentMethodsRequest = {merchantAccount: "MagentoMerchantTest"};
scope.post("/paymentMethods")
.reply(200, paymentMethodsSuccess);
const paymentMethodsResponse = await checkout.paymentMethods(paymentMethodsRequest);
if (paymentMethodsResponse && paymentMethodsResponse.paymentMethods) {
expect(paymentMethodsResponse.paymentMethods.length).toBeGreaterThan(0);
expect(paymentMethodsResponse.paymentMethods.length).toEqual(65);
expect(paymentMethodsResponse.paymentMethods[0].name).toEqual("AliPay");
} else {
fail();
}
});
test.each([false, true])("should have valid payment link, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should have valid payment link", async (): Promise<void> => {
const amount = createAmountObject("BRL", 1000);
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResource = getPaymentLinkSuccess(expiresAt);
const paymentLinkRequest: ICheckout.CreatePaymentLinkRequest = {
allowedPaymentMethods: ["scheme", "boletobancario"],
amount,
countryCode: "BR",
merchantAccount,
shopperReference: "shopperReference",
shopperEmail: "test@email.com",
shopperLocale: "pt_BR",
billingAddress: {
street: "Roque Petroni Jr",
postalCode: "59000060",
city: "São Paulo",
houseNumberOrName: "999",
country: "BR",
stateOrProvince: "SP"
},
deliveryAddress: {
street: "Roque Petroni Jr",
postalCode: "59000060",
city: "São Paulo",
houseNumberOrName: "999",
country: "BR",
stateOrProvince: "SP"
},
expiresAt,
reference
};
const paymentLinkSuccess: ICheckout.CreatePaymentLinkResponse = {
amount,
expiresAt,
reference,
url: "paymentLinkResponse.url"
};
scope.post("/paymentLinks").reply(200, paymentLinkSuccess);
const paymentSuccessLinkResponse = await checkout.paymentLinks(createPaymentLinkRequest());
expect(paymentSuccessLinkResponse).toBeTruthy();
const paymentSuccessLinkResponse = await checkout.paymentLinks(paymentLinkRequest);
expect(paymentLinkSuccess).toEqual(paymentSuccessLinkResponse);
});
test.each([isCI, true])("should get payment link, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResource = getPaymentLinkSuccess(expiresAt);
scope.post("/paymentLinks").reply(200, paymentLinkSuccess);
const paymentSuccessLinkResponse = await checkout.paymentLinks(createPaymentLinkRequest());
scope.get(`/paymentLinks/${paymentSuccessLinkResponse.id}`).reply(200, paymentLinkSuccess);
const paymentLink = await checkout.getPaymentLinks(paymentSuccessLinkResponse.id);
expect(paymentLink).toBeTruthy();
});
test.each([isCI, true])("should patch payment link, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
const expiresAt = "2019-12-17T10:05:29Z";
const paymentLinkSuccess: PaymentLinkResource = getPaymentLinkSuccess(expiresAt);
scope.post("/paymentLinks").reply(200, paymentLinkSuccess);
const paymentSuccessLinkResponse = await checkout.paymentLinks(createPaymentLinkRequest());
scope.patch(`/paymentLinks/${paymentSuccessLinkResponse.id}`).reply(200, { ...paymentLinkSuccess, status: "expired" });
const paymentLink = await checkout.updatePaymentLinks(paymentSuccessLinkResponse.id, "expired");
expect(paymentLink.status).toEqual("expired");
});
test.each([isCI, true])("should have payment details, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should have payment details", async (): Promise<void> => {
scope.post("/payments/details")
.reply(200, paymentDetailsSuccess);
@@ -244,28 +179,25 @@ describe("Checkout", (): void => {
expect(paymentsResponse.resultCode).toEqual("Authorised");
});
test.each([false, true])("should have payment session success, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should have payment session success", async (): Promise<void> => {
scope.post("/paymentSession")
.reply(200, paymentSessionSuccess);
const paymentSessionRequest: PaymentSetupRequest = createPaymentSessionRequest();
const paymentSessionRequest: ICheckout.PaymentSetupRequest = createPaymentSessionRequest();
const paymentSessionResponse = await checkout.paymentSession(paymentSessionRequest);
expect(paymentSessionResponse.paymentSession).not.toBeUndefined();
});
test.each([isCI, true])("should have payments result, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should have payments result", async (): Promise<void> => {
scope.post("/payments/result")
.reply(200, paymentsResultSuccess);
const paymentResultRequest: PaymentVerificationRequest = {
const paymentResultRequest: ICheckout.PaymentVerificationRequest = {
payload: "This is a test payload",
};
const paymentResultResponse = await checkout.paymentResult(paymentResultRequest);
expect(paymentResultResponse.resultCode).toEqual("Authorised");
});
test.each([false, true])("should have missing identifier on live, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should have missing identifier on live", async (): Promise<void> => {
client.setEnvironment("LIVE");
try {
new Checkout(client);
@@ -276,113 +208,19 @@ describe("Checkout", (): void => {
});
test.each([false, true])("should succeed on multibanco payment, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should succeed on multibanco payment", async (): Promise<void> => {
scope.post("/payments")
.reply(200, paymentsResultMultibancoSuccess);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: PaymentResponse = await checkout.payments(paymentsRequest);
const paymentsRequest: ICheckout.PaymentRequest = createPaymentsCheckoutRequest();
const paymentsResponse: ICheckout.PaymentResponse = await checkout.payments(paymentsRequest);
expect(paymentsResponse.pspReference).toEqual("8111111111111111");
expect(paymentsResponse.pspReference).toBeTruthy();
expect(paymentsResponse.additionalData).toBeTruthy();
});
test.each([false, true])("should get origin keys. isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
const checkoutUtility = new Checkout(client);
const originKeysRequest: CheckoutUtilityRequest = {
originDomains: ["https://www.your-domain.com"],
};
nock(`${client.config.checkoutEndpoint}`)
.post(`/${Client.CHECKOUT_API_VERSION}/originKeys`)
.reply(200, originKeysSuccess);
const originKeysResponse = await checkoutUtility.originKeys(originKeysRequest);
if (originKeysResponse.originKeys) {
return expect(originKeysResponse.originKeys["https://www.your-domain.com"].startsWith("pub.v2")).toBeTruthy();
if (paymentsResponse.additionalData) {
expect(paymentsResponse.additionalData["comprafacil.amount"]).toEqual("101.01");
expect(paymentsResponse.additionalData["comprafacil.deadline"]).toEqual("3");
expect(paymentsResponse.additionalData["comprafacil.entity"]).toEqual("12345");
}
fail("Error: originKeysResponse.originKeys is empty");
});
// TODO: add gift card to PaymentMethod and unmock test
test.each([true, true])("should get payment methods balance", async (isMock): Promise<void> => {
!isMock && nock.restore();
const paymentMethodsRequest: CheckoutBalanceCheckRequest = {
merchantAccount,
amount: createAmountObject("USD", 1000),
paymentMethod: { },
reference: "mocked_reference"
};
const paymentMethodsBalanceResponse: CheckoutBalanceCheckResponse = {
balance: {currency: "USD", value: 1000},
resultCode: CheckoutBalanceCheckResponse.ResultCodeEnum.Success
};
scope.post("/paymentMethods/balance")
.reply(200, paymentMethodsBalanceResponse);
const paymentsResponse: CheckoutBalanceCheckResponse = await checkout.paymentMethodsBalance(paymentMethodsRequest);
expect(paymentsResponse.balance.value).toEqual(1000);
});
test.each([false, true])("should create order", async (isMock): Promise<void> => {
!isMock && nock.restore();
const expiresAt = "2019-12-17T10:05:29Z";
const orderRequest: CheckoutCreateOrderRequest = {
amount: createAmountObject("USD", 1000),
merchantAccount,
reference
};
const orderResponse: CheckoutCreateOrderResponse = {
expiresAt,
orderData: "mocked_order_data",
remainingAmount: {currency: "USD", value: 500} ,
resultCode: CheckoutCreateOrderResponse.ResultCodeEnum.Success
};
scope.post("/orders")
.reply(200, orderResponse);
const response: CheckoutCreateOrderResponse = await checkout.orders(orderRequest);
expect(response).toBeTruthy();
});
test.each([false, true])("should cancel order", async (isMock): Promise<void> => {
!isMock && nock.restore();
const expiresAt = "2019-12-17T10:05:29Z";
const orderRequest: CheckoutCreateOrderRequest = {
amount: createAmountObject("USD", 1000),
merchantAccount,
reference
};
const orderResponse: CheckoutCreateOrderResponse = {
expiresAt,
orderData: "mocked_order_data",
remainingAmount: {currency: "USD", value: 500},
resultCode: CheckoutCreateOrderResponse.ResultCodeEnum.Success
};
scope.post("/orders")
.reply(200, orderResponse);
const createOrderResponse: CheckoutCreateOrderResponse = await checkout.orders(orderRequest);
const orderCancelResponse: CheckoutCancelOrderResponse = {
pspReference: "mocked_psp_ref",
resultCode: CheckoutCancelOrderResponse.ResultCodeEnum.Received
};
scope.post("/orders/cancel")
.reply(200, orderCancelResponse);
const response: CheckoutCancelOrderResponse = await checkout.ordersCancel({
order: {
orderData: createOrderResponse.orderData,
pspReference: createOrderResponse.pspReference!
},
merchantAccount
});
expect(response).toBeTruthy();
});
});

View File

@@ -0,0 +1,47 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen NodeJS API Library
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createMockClientFromResponse } from "../__mocks__/base";
import {originKeysSuccess} from "../__mocks__/checkoutUtility/originkeysSuccess";
import CheckoutUtility from "../services/checkoutUtility";
import Client from "../client";
describe("Checkout Utility", (): void => {
it("should get origin keys", async (): Promise<void> => {
const client = createMockClientFromResponse();
const checkoutUtility = new CheckoutUtility(client);
const originKeysRequest: ICheckoutUtility.CheckoutUtilityRequest = {
originDomains: ["www.test.com", "https://www.your-domain2.com"],
};
nock(`${client.config.checkoutEndpoint}`)
.post(`/${Client.CHECKOUT_UTILITY_API_VERSION}/originKeys`)
.reply(200, originKeysSuccess);
const originKeysResponse = await checkoutUtility.originKeys(originKeysRequest);
if (originKeysResponse.originKeys) {
return expect(originKeysResponse.originKeys["https://www.your-domain1.com"])
.toEqual("pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4xLmNvbQ.UEwIBmW9-c_uXo5wSEr2w8Hz8hVIpujXPHjpcEse3xI");
}
fail("Error: originKeysResponse.originKeys is empty");
});
});

View File

@@ -1,49 +1,22 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import HmacValidator from "../utils/hmacValidator";
import { AdditionalData, NotificationItem, NotificationRequestItem } from "../typings/notification/models";
import { ApiConstants } from "../constants/apiConstants";
import NotificationRequest from "../notification/notificationRequest";
import {NotificationRequestItem} from "../typings/notification";
import {ApiConstants} from "../constants/apiConstants";
const key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
const expectedSign = "ZNBPtI+oDyyRrLyD1XirkKnQgIAlFc07Vj27TeHsDRE=";
const notificationRequestItem: { NotificationRequestItem: NotificationRequestItem } = {
NotificationRequestItem : {
pspReference: "pspReference",
originalReference: "originalReference",
merchantAccountCode: "merchantAccount",
merchantReference: "reference",
amount: {currency: "EUR", value: 1000},
eventCode: NotificationRequestItem.EventCodeEnum.REPORTAVAILABLE,
eventDate: "2019-09-21T11:45:24.637Z",
paymentMethod: "VISA",
reason: "reason",
success: NotificationRequestItem.SuccessEnum.True,
additionalData: { [ApiConstants.HMAC_SIGNATURE]: expectedSign },
}
const expectedSign = "ipnxGCaUZ4l8TUW75a71/ghd2Fe5ffvX0pV4TLTntIc=";
const notificationRequestItem: NotificationRequestItem = {
pspReference: "pspReference",
originalReference: "originalReference",
merchantAccountCode: "merchantAccount",
merchantReference: "reference",
amount: {currency: "EUR", value: 1000},
eventCode: "EVENT",
eventDate: new Date("01-01-1970"),
paymentMethod: "VISA",
reason: "reason",
success: "true",
additionalData: { [ApiConstants.HMAC_SIGNATURE]: expectedSign },
};
const notification = new NotificationRequest({
live: "false",
notificationItems: [notificationRequestItem as unknown as NotificationItem]
});
describe("HMAC Validator", function (): void {
let hmacValidator: HmacValidator;
@@ -65,81 +38,22 @@ describe("HMAC Validator", function (): void {
expect(encrypted).toEqual("34oR8T1whkQWTv9P+SzKyp8zhusf9n0dpqrm9nsqSJs=");
});
it("should get correct data to sign", function (): void {
const data = hmacValidator.getDataToSign(notification.notificationItems![0]);
expect(data).toEqual("pspReference:originalReference:merchantAccount:reference:1000:EUR:REPORT_AVAILABLE:true");
const data = hmacValidator.getDataToSign(notificationRequestItem);
expect(data).toEqual("pspReference:originalReference:merchantAccount:reference:1000:EUR:EVENT:true");
});
it("should have valid hmac", function (): void {
const encrypted = hmacValidator.calculateHmac(notification.notificationItems![0], key);
const encrypted = hmacValidator.calculateHmac(notificationRequestItem, key);
expect(expectedSign).toEqual(encrypted);
expect(hmacValidator.validateHMAC(notification.notificationItems![0], key)).toBeTruthy();
expect(hmacValidator.validateHMAC(notificationRequestItem, key)).toBeTruthy();
});
it("should have invalid hmac", function (): void {
const invalidNotification = {
...notification.notificationItems![0],
additionalData: { [ApiConstants.HMAC_SIGNATURE as keyof AdditionalData]: "notValidSign" }
...notificationRequestItem,
additionalData: { [ApiConstants.HMAC_SIGNATURE]: "notValidSign" }
};
const result = hmacValidator.validateHMAC(invalidNotification, key);
expect(result).toBeFalsy();
});
it("should throw error with missing hmac signature", function(): void {
expect.assertions(1);
const notificationRequestItemNoAdditionalData: NotificationRequestItem = {
pspReference: "pspReference",
originalReference: "originalReference",
merchantAccountCode: "merchantAccount",
merchantReference: "reference",
amount: {currency: "EUR", value: 1000},
eventCode: NotificationRequestItem.EventCodeEnum.REPORTAVAILABLE,
eventDate: "2019-09-21T11:45:24.637Z",
paymentMethod: "VISA",
reason: "reason",
success: NotificationRequestItem.SuccessEnum.True,
additionalData: { },
};
try {
hmacValidator.validateHMAC(notificationRequestItemNoAdditionalData, key);
} catch(error) {
expect(error.message).toEqual(`Missing ${ApiConstants.HMAC_SIGNATURE}`);
}
});
it("should test hmac", function () {
const data = "countryCode:currencyCode:merchantAccount:merchantReference:paymentAmount:sessionValidity:skinCode:NL:EUR:MagentoMerchantTest2:TEST-PAYMENT-2017-02-01-14\\:02\\:05:199:2017-02-02T14\\:02\\:05+01\\:00:PKz2KML1";
const key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00";
const hmacValidator = new HmacValidator();
const encrypted = hmacValidator.calculateHmac(data, key);
expect(encrypted).toEqual("34oR8T1whkQWTv9P+SzKyp8zhusf9n0dpqrm9nsqSJs=");
});
it("should validate HMAC", function () {
expect(hmacValidator.validateHMAC(notification.notificationItems![0], key)).toBeTruthy();
});
it("should have valid notification request item HMAC", function () {
const expectedSign = "ipnxGCaUZ4l8TUW75a71/ghd2Fe5ffvX0pV4TLTntIc=";
const notificationRequestItem = { NotificationRequestItem: {
pspReference: "pspReference",
originalReference: "originalReference",
merchantAccountCode: "merchantAccount",
merchantReference: "reference",
amount: { currency: "EUR", value: 1000 },
eventCode: "EVENT",
success: "true",
additionalData: { [ApiConstants.HMAC_SIGNATURE]: expectedSign }
}} as unknown as NotificationItem;
const notification = new NotificationRequest({
live: "false",
notificationItems: [notificationRequestItem]
});
const data = hmacValidator.getDataToSign(notification.notificationItems![0]);
expect("pspReference:originalReference:merchantAccount:reference:1000:EUR:EVENT:true").toEqual(data);
const encrypted = hmacValidator.calculateHmac(notification.notificationItems![0], key);
expect(expectedSign).toEqual(encrypted);
expect(hmacValidator.validateHMAC(notification.notificationItems![0], key)).toBeTruthy();
notification.notificationItems![0].additionalData![ApiConstants.HMAC_SIGNATURE] = "notValidSign";
expect(hmacValidator.validateHMAC(notification.notificationItems![0], key)).toBeFalsy();
});
});

View File

@@ -1,27 +1,8 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock, { Interceptor } from "nock";
import nock, {Interceptor} from "nock";
import Client from "../client";
import Checkout from "../services/checkout";
import ApiException from "../services/exception/apiException";
import { createPaymentsCheckoutRequest } from "./checkout.spec";
import {createPaymentsCheckoutRequest} from "./checkout.spec";
import HttpClientException from "../httpClient/httpClientException";
beforeEach((): void => {
@@ -31,7 +12,7 @@ beforeEach((): void => {
type errorType = "HttpClientException" | "ApiException";
type testOptions = { errorType: errorType; errorMessageContains?: string; errorMessageEquals?: string };
const getResponse = async ({apiKey , environment }: { apiKey: string; environment: Environment}, cb: (scope: Interceptor) => testOptions): Promise<void> => {
const getResponse = async ({apiKey , environment }: { apiKey: string; environment: Environment}, cb: (scope: Interceptor) => testOptions) => {
const client = new Client({ apiKey, environment });
const checkout = new Checkout(client);
@@ -45,14 +26,14 @@ const getResponse = async ({apiKey , environment }: { apiKey: string; environmen
fail("request should fail");
} catch (e) {
expect(e instanceof ErrorException).toBeTruthy();
if (errorMessageEquals) expect(e.message).toEqual(errorMessageEquals);
if (errorMessageContains) expect(e.message.toLowerCase()).toContain(errorMessageContains);
if(errorMessageEquals) expect(e.message).toEqual(errorMessageEquals);
if(errorMessageContains) expect(e.message.toLowerCase()).toContain(errorMessageContains);
}
};
describe("HTTP Client", function (): void {
it.each`
apiKey | environment | withError | args | errorType | contains | equals
apiKey | environment | withError | args | errorType | contains | equals
${""} | ${"TEST"} | ${true} | ${["mocked_error_response"]} | ${"ApiException"} | ${"x-api-key"} | ${""}
${"MOCKED_API_KEY"} | ${"TEST"} | ${true} | ${["some_error"]} | ${"ApiException"} | ${""} | ${"some_error"}
${"API_KEY"} | ${"TEST"} | ${false} | ${[401, { status: 401, message: "Invalid Request", errorCode: "171", errorType: "validationError"}]} | ${"HttpClientException"} | ${""} | ${"HTTP Exception: 401. null: Invalid Request"}
@@ -66,4 +47,4 @@ describe("HTTP Client", function (): void {
return { errorType, errorMessageContains: contains, errorMessageEquals: equals };
});
});
});
});

View File

@@ -1,264 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient } from "../__mocks__/base";
import Modification from "../services/modification";
import Client from "../client";
const modificationResult: IPayouts.ModifyResponse = {
pspReference: "1234567890987654",
response: "[refund-received]"
};
const invalidModificationResult = {
"status": 422,
"errorCode": "167",
"message": "Original pspReference required for this operation",
"errorType": "validation"
};
const createModificationRequest = (): IPayments.ModificationRequest => {
return {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: "863620292981235A",
modificationAmount: {
value: 500 ,
currency: "EUR"
}
};
};
const createInvalidModificationRequest = (): IPayments.ModificationRequest => {
return {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: "invalidPspReference",
modificationAmount: {
value: 500 ,
currency: "EUR"
}
};
};
const createCancelRequest = (): IPayments.ModificationRequest => {
return {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: "862615382016087C"
};
};
const createInvalidCancelRequest = (): IPayments.ModificationRequest => {
return {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: "invalidPspReference"
};
};
let client: Client;
let modification: Modification;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient();
modification = new Modification(client);
scope = nock(`${client.config.endpoint}/pal/servlet/Payment/${Client.API_VERSION}`);
});
afterEach(() => {
nock.cleanAll();
});
describe("Modification", (): void => {
test.each([false, true])("should perform a refund, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/refund")
.reply(200, modificationResult);
const request = createModificationRequest();
try {
const result = await modification.refund(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([false, true])("should fail to perform a refund, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
expect.assertions(2);
scope.post("/refund")
.reply(422, invalidModificationResult);
const request = createInvalidModificationRequest();
try {
await modification.refund(request);
} catch (e) {
expect(e.statusCode).toBe(422);
expect(e.message).toContain("Original pspReference required for this operation");
}
});
test.each([false, true])("should perform a capture, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/capture")
.reply(200, modificationResult);
const request = createModificationRequest();
try {
const result = await modification.capture(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([false, true])("should fail to perform a capture, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
expect.assertions(2);
scope.post("/capture")
.reply(422, invalidModificationResult);
const request = createInvalidModificationRequest();
try {
await modification.capture(request);
} catch (e) {
expect(e.statusCode).toBe(422);
expect(e.message).toContain("Original pspReference required for this operation");
}
});
test.each([false, true])("should perform a cancelOrRefund, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/cancelOrRefund")
.reply(200, modificationResult);
const request = createCancelRequest();
try {
const result = await modification.cancelOrRefund(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([false, true])("should fail to perform a cancelOrRefund, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
expect.assertions(2);
scope.post("/cancelOrRefund")
.reply(422, invalidModificationResult);
const request = createInvalidCancelRequest();
try {
await modification.cancelOrRefund(request);
} catch (e) {
expect(e.statusCode).toBe(422);
expect(e.message).toContain("Original pspReference required for this operation");
}
});
test.each([false, true])("should perform a cancel, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/cancel")
.reply(200, modificationResult);
const request = createCancelRequest();
try {
const result = await modification.cancel(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([false, true])("should fail to perform a cancel, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
expect.assertions(2);
scope.post("/cancel")
.reply(422, invalidModificationResult);
const request = createInvalidCancelRequest();
try {
await modification.cancel(request);
} catch (e) {
expect(e.statusCode).toBe(422);
expect(e.message).toContain("Original pspReference required for this operation");
}
});
test.each([false, true])("should perform a technicalCancel, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/technicalCancel")
.reply(200, modificationResult);
const request = createCancelRequest();
try {
const result = await modification.technicalCancel(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([false, true])("should fail to perform a technicalCancel, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
expect.assertions(2);
scope.post("/technicalCancel")
.reply(422, invalidModificationResult);
const request = createInvalidCancelRequest();
try {
await modification.technicalCancel(request);
} catch (e) {
expect(e.statusCode).toBe(422);
expect(e.message).toContain("Original pspReference required for this operation");
}
});
test.each([false, true])("should perform a adjustAuthorisation, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/adjustAuthorisation")
.reply(200, modificationResult);
const request = createModificationRequest();
try {
const result = await modification.adjustAuthorisation(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([false, true])("should fail to perform a adjustAuthorisation, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
expect.assertions(2);
scope.post("/adjustAuthorisation")
.reply(422, invalidModificationResult);
const request = createInvalidModificationRequest();
try {
await modification.adjustAuthorisation(request);
} catch (e) {
expect(e.statusCode).toBe(422);
expect(e.message).toContain("Original pspReference required for this operation");
}
});
});

View File

@@ -1,32 +1,10 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import authorisationTrue from "../__mocks__/notification/authorisationTrue.json";
import captureTrue from "../__mocks__/notification/captureTrue.json";
import captureFalse from "../__mocks__/notification/captureFalse.json";
import refundTrue from "../__mocks__/notification/refundTrue.json";
import refundFalse from "../__mocks__/notification/refundFalse.json";
import NotificationRequest from "../notification/notificationRequest";
import { Notification, NotificationRequestItem } from "../typings/notification/models";
import NotificationEnum = NotificationRequestItem.EventCodeEnum;
import SuccessEnum = NotificationRequestItem.SuccessEnum;
import {Notification, NotificationEnum, NotificationRequestItem} from "../typings/notification";
describe("Notification Test", function (): void {
it("should return authorisation success", function (): void {
@@ -35,8 +13,8 @@ describe("Notification Test", function (): void {
if (notificationRequest.notificationItems) {
const notificationRequestItem: NotificationRequestItem = notificationRequest.notificationItems[0];
expect(NotificationEnum.AUTHORISATION).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === SuccessEnum.True).toBeTruthy();
expect(NotificationEnum.EVENT_CODE_AUTHORISATION).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === "true").toBeTruthy();
expect(notificationRequestItem.pspReference).toEqual("123456789");
} else {
fail();
@@ -49,8 +27,8 @@ describe("Notification Test", function (): void {
if (notificationRequest.notificationItems) {
const notificationRequestItem = notificationRequest.notificationItems[0];
expect(NotificationEnum.CAPTURE).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === SuccessEnum.True).toBeTruthy();
expect(NotificationEnum.EVENT_CODE_CAPTURE).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === "true").toBeTruthy();
expect(notificationRequestItem.pspReference).toEqual("PSP_REFERENCE");
expect(notificationRequestItem.originalReference).toEqual("ORIGINAL_PSP");
} else {
@@ -64,8 +42,8 @@ describe("Notification Test", function (): void {
if (notificationRequest.notificationItems) {
const notificationRequestItem = notificationRequest.notificationItems[0];
expect(NotificationEnum.CAPTURE).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === SuccessEnum.True).toBeFalsy();
expect(NotificationEnum.EVENT_CODE_CAPTURE).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === "true").toBeFalsy();
expect(notificationRequestItem.pspReference).toEqual("PSP_REFERENCE");
expect(notificationRequestItem.originalReference).toEqual("ORIGINAL_PSP");
} else {
@@ -79,8 +57,8 @@ describe("Notification Test", function (): void {
if (notificationRequest.notificationItems) {
const notificationRequestItem = notificationRequest.notificationItems[0];
expect(NotificationEnum.REFUND).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === SuccessEnum.True).toBeTruthy();
expect(NotificationEnum.EVENT_CODE_REFUND).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === "true").toBeTruthy();
expect(notificationRequestItem.pspReference).toEqual("PSP_REFERENCE");
expect(notificationRequestItem.originalReference).toEqual("ORIGINAL_PSP");
expect(notificationRequestItem.eventDate).toBeDefined();
@@ -95,8 +73,8 @@ describe("Notification Test", function (): void {
if (notificationRequest.notificationItems) {
const notificationRequestItem = notificationRequest.notificationItems[0];
expect(NotificationEnum.REFUND).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === SuccessEnum.True).toBeFalsy();
expect(NotificationEnum.EVENT_CODE_REFUND).toEqual(notificationRequestItem.eventCode);
expect(notificationRequestItem.success === "true").toBeFalsy();
expect(notificationRequestItem.pspReference).toEqual("PSP_REFERENCE");
expect(notificationRequestItem.originalReference).toEqual("ORIGINAL_PSP");
expect(notificationRequestItem.eventDate).toBeDefined();

View File

@@ -1,34 +1,15 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient } from "../__mocks__/base";
import {createMockClientFromResponse} from "../__mocks__/base";
import Payout from "../services/payout";
import Client from "../client";
import StoreDetailRequest = IPayouts.StoreDetailRequest;
import { ApiConstants } from "../constants/apiConstants";
import {ApiConstants} from "../constants/apiConstants";
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
const storeDetailAndSubmitThirdParty = JSON.stringify({
additionalData: {
fraudResultType: "GREEN",
fraudManualReview: "false",
},
pspReference: "8515131751004933",
resultCode: "[payout-submit-received]"
@@ -43,8 +24,8 @@ const storeDetail = JSON.stringify({
const amountAndReference = {
amount: {
value: 100,
currency: "EUR"
value: 1000,
currency: "USD"
},
reference: "randomReference",
};
@@ -56,43 +37,36 @@ const defaultData = {
shopperReference: "shopperReference",
};
const mockStoreDetailRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): IPayouts.StoreDetailRequest => ({
const mockStoreDetailRequest = (merchantAccount: string): IPayouts.StoreDetailRequest => ({
...defaultData,
card: {
cvc: "737",
expiryMonth: "03",
expiryYear: "2020",
number: "4111111111111111",
holderName: "John Smith"
},
entityType: "Company",
entityType: "NaturalPerson",
recurring: {
contract: "PAYOUT"
contract: "ONECLICK"
},
merchantAccount,
});
const mockSubmitRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): IPayouts.SubmitRequest => ({
const mockSubmitRequest = (merchantAccount: string): IPayouts.SubmitRequest => ({
selectedRecurringDetailReference: "LATEST",
recurring: {
contract: "PAYOUT"
contract: "ONECLICK"
},
...defaultData,
...amountAndReference,
merchantAccount,
});
const mockStoreDetailAndSubmitRequest = (merchantAccount?: string): IPayouts.StoreDetailAndSubmitRequest => ({
const mockStoreDetailAndSubmitRequest = (merchantAccount: string): IPayouts.StoreDetailAndSubmitRequest => ({
...amountAndReference,
...(mockStoreDetailRequest(merchantAccount)),
});
const mockPayoutRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!): IPayouts.PayoutRequest => ({
const mockPayoutRequest = (merchantAccount: string): IPayouts.PayoutRequest => ({
...amountAndReference,
...defaultData,
card: {
expiryMonth: "03",
expiryYear: "2030",
expiryMonth: "10",
expiryYear: "2020",
holderName: "John Smith",
number: "4111111111111111",
},
@@ -100,84 +74,23 @@ const mockPayoutRequest = (merchantAccount: string = process.env.ADYEN_MERCHANT!
});
let client: Client;
let clientStore: Client;
let clientReview: Client;
let payout: Payout;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient();
clientStore = createClient(process.env.ADYEN_STOREPAYOUT_APIKEY);
clientReview = createClient(process.env.ADYEN_REVIEWPAYOUT_APIKEY);
client = createMockClientFromResponse();
scope = nock(`${client.config.endpoint}/pal/servlet/Payout/${Client.API_VERSION}`);
payout = new Payout(client);
});
afterEach((): void => {
nock.cleanAll();
});
describe("PayoutTest", function (): void {
test.each([isCI, true])("should succeed on store detail and submit third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
const request: IPayouts.StoreDetailAndSubmitRequest = mockStoreDetailAndSubmitRequest();
scope.post("/storeDetailAndSubmitThirdParty").reply(200, storeDetailAndSubmitThirdParty);
it("should succeed on store detail and submit third party", async function (): Promise<void> {
const request: IPayouts.StoreDetailAndSubmitRequest = mockStoreDetailAndSubmitRequest(`${client.config.merchantAccount}`);
scope.post("/storeDetail").reply(200, storeDetailAndSubmitThirdParty);
const result = await payout.storeDetailAndSubmitThirdParty(request);
expect(result.resultCode).toEqual("[payout-submit-received]");
expect(result.pspReference).toBeTruthy();
});
test.each([false, true])("should succeed on store detail, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
scope.post("/storeDetail").reply(200, storeDetail);
const request: StoreDetailRequest = mockStoreDetailRequest();
const result = await payout.storeDetail(request);
expect("Success").toEqual(result.resultCode);
expect(result.pspReference).toBeTruthy();
expect(result.recurringDetailReference).toBeTruthy();
});
test.each([isCI, true])("should succeed on confirm third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
scope.post("/storeDetail").reply(200, storeDetail);
const storeRequest: StoreDetailRequest = mockStoreDetailRequest();
const storeResult = await payout.storeDetail(storeRequest);
payout = new Payout(clientReview);
scope.post("/confirmThirdParty")
.reply(200, {
pspReference: "8815131762537886",
response: "[payout-confirm-received]"
});
const request: IPayouts.ModifyRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: storeResult.pspReference
};
const result = await payout.confirmThirdParty(request);
expect(result.response).toEqual("[payout-confirm-received]");
expect(result.pspReference).toBeTruthy();
});
test.each([isCI, true])("should succeed on submit third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
scope.post("/submitThirdParty").reply(200, storeDetailAndSubmitThirdParty);
const request: IPayouts.SubmitRequest = mockSubmitRequest();
const result = await payout.submitThirdparty(request);
expect(result.resultCode).toEqual("[payout-submit-received]");
expect(result.pspReference).toBeTruthy();
expect(result.pspReference).toEqual("8515131751004933");
if (result.additionalData) {
expect(result.additionalData[ApiConstants.FRAUD_RESULT_TYPE]).toEqual("GREEN");
@@ -185,40 +98,74 @@ describe("PayoutTest", function (): void {
}
});
test.each([false, true])("should succeed on decline third party, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
payout = new Payout(clientStore);
it("should succeed on store detail", async function (): Promise<void> {
scope.post("/storeDetail").reply(200, storeDetail);
const storeRequest: StoreDetailRequest = mockStoreDetailRequest();
const storeResult = await payout.storeDetail(storeRequest);
const request: StoreDetailRequest = mockStoreDetailRequest("MOCKED_MERCHANT_ACC");
const result = await payout.storeDetail(request);
payout = new Payout(clientReview);
const request: IPayouts.ModifyRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
originalReference: storeResult.pspReference
};
scope.post("/declineThirdParty")
.reply(200, {
pspReference: "8815131762537886",
response: "[payout-decline-received]"
});
const result = await payout.declineThirdParty(request);
expect(result.response).toEqual("[payout-decline-received]");
expect(result.pspReference).toBeTruthy();
expect("Success").toEqual(result.resultCode);
expect("8515136787207087").toEqual(result.pspReference);
expect("8415088571022720").toEqual(result.recurringDetailReference);
});
test.each([isCI, true])("should succeed on payout, isMock: %p", async function (isMock): Promise<void> {
!isMock && nock.restore();
it("should succeed on confirm third party", async function (): Promise<void> {
scope.post("/confirmThirdParty")
.reply(200, {
pspReference: "8815131762537886",
response: "[payout-confirm-received]"
});
const request: IPayouts.ModifyRequest = {
merchantAccount: "MOCKED_MERCHANT_ACCOUNT",
originalReference: "reference"
};
const result = await payout.confirmThirdParty(request);
expect(result.response).toEqual("[payout-confirm-received]");
expect(result.pspReference).toEqual("8815131762537886");
});
it("should succeed on submit third party", async function (): Promise<void> {
scope.post("/submitThirdParty").reply(200, storeDetailAndSubmitThirdParty);
const request: IPayouts.SubmitRequest = mockSubmitRequest("MOCKED_MERCHANT_ACC");
const result = await payout.submitThirdparty(request);
expect(result.resultCode).toEqual("[payout-submit-received]");
expect(result.pspReference).toEqual("8515131751004933");
if (result.additionalData) {
expect(result.additionalData[ApiConstants.FRAUD_RESULT_TYPE]).toEqual("GREEN");
expect(result.additionalData[ApiConstants.FRAUD_MANUAL_REVIEW]).toEqual("false");
}
});
it("should succeed on decline third party", async function (): Promise<void> {
scope.post("/storeDetailAndSubmitThirdParty").reply(200, {
pspReference: "8815131762537886",
response: "[payout-confirm-received]"
});
const request: IPayouts.ModifyRequest = {
merchantAccount: "MOCKED_MERCHANT_ACC",
originalReference: "reference"
};
const result = await payout.declineThirdParty(request);
expect(result.response).toEqual("[payout-confirm-received]");
expect(result.pspReference).toEqual("8815131762537886");
});
it("should succeed on payout", async function (): Promise<void> {
scope.post("/payout").reply(200, {
pspReference: "8815131762537886",
resultCode: "Received",
});
const request = mockPayoutRequest();
const request = mockPayoutRequest("MOCKED_MERCHANT_ACC");
const result = await payout.payout(request);
expect(result.resultCode).toEqual("Received");
expect(result.pspReference).toBeTruthy();
expect(result.pspReference).toEqual("8815131762537886");
});
});

View File

@@ -1,532 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createMock } from "ts-auto-mock";
import { createBasicAuthClient } from "../__mocks__/base";
import { documentContent } from "../__mocks__/platforms/documentContent";
import { Client, Platforms } from "../index";
import * as A from "../typings/platformsAccount/models";
import F = IPlatformsFund;
import N = IPlatformsNotificationConfiguration;
import H = IPlatformsHostedOnboardingPage;
import AccountHolderDetails = A.AccountHolderDetails;
import NotificationConfigurationDetails = N.NotificationConfigurationDetails;
import HttpClientException from "../httpClient/httpClientException";
let client: Client;
let platforms: Platforms;
let scope: nock.Scope;
let accountHolder: A.CreateAccountHolderResponse;
let account: A.CreateAccountResponse;
let accountHolderToSuspend: A.CreateAccountHolderResponse;
let accountToClose: A.CreateAccountResponse;
let accountHolderToUnSuspend: A.CreateAccountHolderResponse;
let accountHolderToClose: A.CreateAccountHolderResponse;
let notificationConfigurationToRetrieve: N.GetNotificationConfigurationResponse;
const generateRandomCode = (): string => Math.floor(Math.random() * Date.now()).toString();
const accountHolderDetails: AccountHolderDetails = {
email: "random_email@example.com",
fullPhoneNumber: "312030291928",
webAddress: "http://example.com",
individualDetails: {
name: {
firstName: "John",
gender: A.ViasName.GenderEnum.Male,
lastName: "Smith"
}
},
address: {
country: "NL"
},
};
const notificationConfigurationDetails: NotificationConfigurationDetails = {
active: true,
notifyURL: "https://www.adyen.com/notification-handler",
eventConfigs: [
{
eventType: "ACCOUNT_HOLDER_VERIFICATION",
includeMode: "INCLUDE"
}
],
sslProtocol: "SSL"
};
const assertError = (e: HttpClientException): void => {
if (e.responseBody?.includes("Account code does not exist or invalid") || e.responseBody?.includes("Failed to retrieve account holder")) {
return;
}
fail(e);
};
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createBasicAuthClient();
client.config.password = process.env.ADYEN_MARKETPLACE_PASSWORD;
client.config.username = process.env.ADYEN_MARKETPLACE_USER;
scope = nock(client.config.marketPayEndpoint!);
platforms = new Platforms(client);
});
afterEach(() => {
nock.cleanAll();
});
describe("Platforms Test", function () {
describe("Account", function(): void {
describe("Accounts", function () {
const cases = [
["closeAccount", createMock<A.CloseAccountRequest>(), createMock<A.CloseAccountResponse>()],
["updateAccount", createMock<A.UpdateAccountRequest>(), createMock<A.UpdateAccountResponse>()],
["createAccount", createMock<A.CreateAccountRequest>(), createMock<A.CreateAccountResponse>()],
["uploadDocument", createMock<A.UploadDocumentRequest>(), createMock<A.GetUploadedDocumentsResponse>()],
["getUploadedDocuments", createMock<A.GetUploadedDocumentsRequest>(), createMock<A.GetUploadedDocumentsResponse>()],
["deleteBankAccounts", createMock<A.DeleteBankAccountRequest>(), createMock<A.GenericResponse>()],
["deletePayoutMethods", createMock<A.DeletePayoutMethodRequest>(), createMock<A.GenericResponse>()],
["deleteShareholders", createMock<A.DeleteShareholderRequest>(), createMock<A.GenericResponse>()],
["checkAccountHolder", createMock<A.PerformVerificationRequest>(), createMock<A.GenericResponse>()],
["createAccountHolder", createMock<A.CreateAccountRequest>(), createMock<A.CreateAccountHolderRequest>()],
["getAccountHolder", createMock<A.GetAccountHolderRequest>(), createMock<A.GetAccountHolderRequest>()],
["updateAccountHolder", createMock<A.UpdateAccountHolderRequest>(), createMock<A.UpdateAccountHolderResponse>()],
["updateAccountHolderState", createMock<A.UpdateAccountHolderStateRequest>(), createMock<A.GetAccountHolderStatusResponse>()],
["suspendAccountHolder", createMock<A.SuspendAccountHolderRequest>(), createMock<A.SuspendAccountHolderResponse>()],
["unSuspendAccountHolder", createMock<A.UnSuspendAccountHolderRequest>(), createMock<A.UnSuspendAccountHolderResponse>()],
["closeAccountHolder", createMock<A.CloseAccountHolderRequest>(), createMock<A.CloseAccountResponse>()],
];
test.each(cases)(
"should %p",
async (...args) => {
const service = platforms.Account;
scope.post(`/Account/${Client.MARKETPAY_ACCOUNT_API_VERSION}//${args[0]}`).reply(200, args[2]);
const result = await service[args[0] as string](args[1] as never);
expect(result).toMatchObject(args[2]);
}
);
});
});
describe("Fund", function () {
const cases = [
["accountHolderBalance", createMock<F.AccountHolderBalanceRequest>(), createMock<F.AccountHolderBalanceResponse>()],
["accountHolderTransactionList", createMock<F.AccountHolderTransactionListRequest>(), createMock<F.AccountHolderTransactionListResponse>()],
["payoutAccountHolder", createMock<F.PayoutAccountHolderRequest>(), createMock<F.PayoutAccountHolderResponse>()],
["transferFunds", createMock<F.TransferFundsRequest>(), createMock<F.TransferFundsResponse>()],
["refundFundsTransfer", createMock<F.RefundFundsTransferRequest>(), createMock<F.RefundFundsTransferResponse>()],
["setupBeneficiary", createMock<F.SetupBeneficiaryRequest>(), createMock<F.SetupBeneficiaryResponse>()],
["refundNotPaidOutTransfers", createMock<F.RefundNotPaidOutTransfersRequest>(), createMock<F.RefundNotPaidOutTransfersResponse>()],
];
test.each(cases)(
"should %p",
async (...args) => {
const fund = platforms.Fund;
scope.post(`/Fund/${Client.MARKETPAY_FUND_API_VERSION}//${args[0]}`).reply(200, args[2]);
const result = await fund[args[0] as string](args[1] as never);
expect(result).toMatchObject(args[2]);
}
);
});
describe("Notification Configuration", function() {
const cases = [
["createNotificationConfiguration", createMock<N.CreateNotificationConfigurationRequest>(), createMock<N.GetNotificationConfigurationResponse>()],
["getNotificationConfiguration", createMock<N.GetNotificationConfigurationRequest>(), createMock<N.GetNotificationConfigurationResponse>()],
["getNotificationConfigurationList", {}, createMock<N.GetNotificationConfigurationListResponse>()],
["testNotificationConfiguration", createMock<N.TestNotificationConfigurationRequest>(), createMock<N.TestNotificationConfigurationResponse>()],
["updateNotificationConfiguration", createMock<N.UpdateNotificationConfigurationRequest>(), createMock<N.GetNotificationConfigurationResponse>()],
["deleteNotificationConfigurations", createMock<N.DeleteNotificationConfigurationRequest>(), createMock<N.GenericResponse>()],
];
test.each(cases)(
"should %p",
async (...args) => {
const notificationConfiguration = platforms.NotificationConfiguration;
scope.post(`/Notification/${Client.MARKETPAY_NOTIFICATION_CONFIGURATION_API_VERSION}//${args[0]}`).reply(200, args[2]);
const result = await notificationConfiguration[args[0] as string](args[1] as never);
expect(result).toMatchObject(args[2]);
}
);
});
describe("Hop", function () {
const cases = [
["getOnboardingUrl", createMock<H.GetOnboardingUrlRequest>(), createMock<H.GetOnboardingUrlResponse>()]
];
test.each(cases)(
"should %p",
async (...args) => {
const hostedOnboardingPage = platforms.HostedOnboardingPage;
scope.post(`/Hop/${Client.MARKETPAY_HOP_API_VERSION}//${args[0]}`).reply(200, args[2]);
const result = await hostedOnboardingPage[args[0] as string](args[1] as never);
expect(result).toMatchObject(args[2]);
}
);
});
});
describe.skip("Platforms Test E2E", function(): void {
beforeAll(async (done) => {
accountHolder = await platforms.Account.createAccountHolder({
accountHolderCode: generateRandomCode(),
accountHolderDetails,
legalEntity: A.CreateAccountHolderRequest.LegalEntityEnum.Individual,
});
account = await platforms.Account.createAccount({
accountHolderCode: generateRandomCode(),
description: "This is a new account",
metadata: {meta: "data"},
payoutSchedule: A.CreateAccountRequest.PayoutScheduleEnum.Weekly,
});
accountHolderToSuspend = await platforms.Account.createAccountHolder({
accountHolderCode: generateRandomCode(),
accountHolderDetails,
legalEntity: A.CreateAccountHolderRequest.LegalEntityEnum.Individual,
});
accountToClose = await platforms.Account.createAccount({
accountHolderCode: generateRandomCode(),
description: "This is a new account",
metadata: {meta: "data"},
payoutSchedule: A.CreateAccountRequest.PayoutScheduleEnum.Weekly,
});
accountHolderToUnSuspend = await platforms.Account.createAccountHolder({
accountHolderCode: generateRandomCode(),
accountHolderDetails,
legalEntity: A.CreateAccountHolderRequest.LegalEntityEnum.Individual,
});
await platforms.Account.suspendAccountHolder({ accountHolderCode: accountHolderToUnSuspend.accountHolderCode});
accountHolderToClose = await platforms.Account.createAccountHolder({
accountHolderCode: generateRandomCode(),
accountHolderDetails,
legalEntity: A.CreateAccountHolderRequest.LegalEntityEnum.Individual,
});
notificationConfigurationToRetrieve = await platforms.NotificationConfiguration.createNotificationConfiguration({
configurationDetails: {
...notificationConfigurationDetails,
description: `${generateRandomCode()}`
}
});
done();
});
describe("Account", function(): void {
describe("Accounts E2E", function () {
it("should create account holder", async function() {
nock.restore();
try {
expect(accountHolder.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should get account holder", async function() {
nock.restore();
try {
const result = await platforms.Account.getAccountHolder({
accountHolderCode: accountHolder.accountHolderCode,
});
expect(result.accountHolderDetails.email).toEqual("random_email@example.com");
} catch (e) {
assertError(e);
}
});
it("should update account holder", async function() {
nock.restore();
try {
const result = await platforms.Account.updateAccountHolder({
accountHolderCode: accountHolder.accountHolderCode,
accountHolderDetails: {
...accountHolderDetails,
address: {
country: "BE"
}
}
});
expect(result.accountHolderDetails!.address?.country).toEqual("BE");
} catch (e) {
assertError(e);
}
});
it("should check account holder", async function() {
nock.restore();
try {
const result = await platforms.Account.checkAccountHolder({
accountHolderCode: accountHolder.accountHolderCode,
accountStateType: A.PerformVerificationRequest.AccountStateTypeEnum.Processing,
tier: 2
});
expect(result.resultCode).toEqual("Success");
} catch (e) {
assertError(e);
}
});
it("should create an account", async function() {
nock.restore();
try {
expect(account.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should upload verification document", async function() {
nock.restore();
try {
const result = await platforms.Account.uploadDocument({
documentContent,
documentDetail: {
accountHolderCode: account.accountHolderCode,
documentType: A.DocumentDetail.DocumentTypeEnum.IdCardFront,
description: "test document 000",
filename: "IDCardFront.png"
}
});
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should get uploaded verification documents", async function() {
nock.restore();
try {
await platforms.Account.uploadDocument({
documentContent,
documentDetail: {
accountHolderCode: account.accountHolderCode,
documentType: A.DocumentDetail.DocumentTypeEnum.IdCardFront,
description: "test document 000",
filename: "IDCardFront.png"
}
});
const result = await platforms.Account.getUploadedDocuments({
accountHolderCode: account.accountHolderCode,
});
expect(result.documentDetails![0].filename).toEqual("IDCardFront.png");
} catch (e) {
assertError(e);
}
});
it("should close account", async function() {
nock.restore();
try {
const result = await platforms.Account.closeAccount({
accountCode: accountToClose.accountCode
});
expect(result.status).toEqual("Closed");
} catch (e) {
assertError(e);
}
});
it("should suspend account holder", async function() {
nock.restore();
try {
const result = await platforms.Account.suspendAccountHolder({
accountHolderCode: accountHolderToSuspend.accountHolderCode,
});
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should unsuspend account holder", async function() {
nock.restore();
try {
const result = await platforms.Account.unSuspendAccountHolder({ accountHolderCode: accountHolderToUnSuspend.accountHolderCode });
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should update account holder state", async function() {
nock.restore();
try {
const result = await platforms.Account.updateAccountHolderState({
accountHolderCode: accountHolder.accountHolderCode,
disable: false,
stateType: A.UpdateAccountHolderStateRequest.StateTypeEnum.Payout
});
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should close account holder", async function() {
nock.restore();
try {
const result = await platforms.Account.closeAccountHolder({
accountHolderCode: accountHolderToClose.accountHolderCode
});
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
});
});
describe("Fund", function () {
it("should retrieve the balance of an account holder", async function() {
nock.restore();
try {
const result = await platforms.Fund.accountHolderBalance({
accountHolderCode: generateRandomCode()
});
expect(result.balancePerAccount![0].detailBalance).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should retrieve a list of transaction for an account holder's accounts", async function() {
nock.restore();
try {
const result = await platforms.Fund.accountHolderTransactionList({
accountHolderCode: generateRandomCode()
});
expect(result.accountTransactionLists![0].transactions).toBeDefined();
} catch (e) {
assertError(e);
}
});
it("should transfer funds between two accounts", async function() {
nock.restore();
try {
const result = await platforms.Fund.transferFunds({
sourceAccountCode: "8515883280985939",
destinationAccountCode: "8815883278206345",
amount: {
currency: "EUR",
value: 1
},
transferCode: "SUBSCRIPTION"
});
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
});
describe("Notification Configuration", function () {
let configurationID: number;
it("should retrieve all Notification Configurations", async function() {
nock.restore();
try {
const result = await platforms.NotificationConfiguration.getNotificationConfigurationList({});
const resultStr = JSON.stringify(result);
expect(resultStr.includes("pspReference")).toBeTruthy();
} catch (e) {
assertError(e);
}
});
it("should create a Notification Configuration", async function() {
nock.restore();
try {
const result = await platforms.NotificationConfiguration.createNotificationConfiguration({
configurationDetails: {
...notificationConfigurationDetails,
description: `${generateRandomCode()}`
}
});
expect(result.configurationDetails.active).toBeTruthy();
} catch (e) {
assertError(e);
}
});
it("should retrieve a Notification Configuration", async function() {
nock.restore();
try {
configurationID = notificationConfigurationToRetrieve.configurationDetails.notificationId!;
const result = await platforms.NotificationConfiguration.getNotificationConfiguration({
notificationId: configurationID
});
expect(result.configurationDetails.notifyURL).toEqual("https://www.adyen.com/notification-handler");
} catch (e) {
assertError(e);
}
});
it("should update a Notification Configuration", async function() {
nock.restore();
try {
const result = await platforms.NotificationConfiguration.updateNotificationConfiguration({
configurationDetails: {
eventConfigs: [
{
eventType: "ACCOUNT_HOLDER_VERIFICATION",
includeMode: "EXCLUDE"
},
{
"eventType": "ACCOUNT_CREATED",
"includeMode": "INCLUDE"
}
],
notifyURL: "https://www.adyen.com/notification-handler",
notificationId: configurationID
}
});
const accountHolderVerification = result.configurationDetails.eventConfigs.filter(event => event.eventType === "ACCOUNT_HOLDER_VERIFICATION")[0];
expect(accountHolderVerification.includeMode).toEqual("EXCLUDE");
} catch (e) {
assertError(e);
}
});
it("should delete a Notification Configuration", async function() {
nock.restore();
const notificationIds = [];
notificationIds.push(configurationID);
try {
const result = await platforms.NotificationConfiguration.deleteNotificationConfigurations({notificationIds});
expect(result.pspReference).toBeDefined();
} catch (e) {
assertError(e);
}
});
});
});

View File

@@ -1,164 +1,49 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient } from "../__mocks__/base";
import { disableSuccess } from "../__mocks__/recurring/disableSuccess";
import { listRecurringDetailsSuccess } from "../__mocks__/recurring/listRecurringDetailsSuccess";
import { notifyShopperSuccess } from "../__mocks__/recurring/notifyShopperSuccess";
import RecurringService from "../services/recurring";
import {createMockClientFromResponse} from "../__mocks__/base";
import {disableSuccess} from "../__mocks__/recurring/disableSuccess";
import {listRecurringDetailsSuccess} from "../__mocks__/recurring/listRecurringDetailsSuccess";
import Recurring from "../services/recurring";
import Client from "../client";
import { paymentsSuccess } from "../__mocks__/checkout/paymentsSuccess";
import { createPaymentsCheckoutRequest } from "./checkout.spec";
import Checkout from "../services/checkout";
import { PaymentRequest } from "../typings/checkout/models";
import {
ScheduleAccountUpdaterRequest,
ScheduleAccountUpdaterResult,
DisableRequest,
RecurringDetailsRequest,
Recurring,
NotifyShopperRequest
} from "../typings/recurring/models";
const createRecurringDetailsRequest = (): RecurringDetailsRequest => {
const createRecurringDetailsRequest = (): IRecurring.RecurringDetailsRequest => {
return {
merchantAccount: process.env.ADYEN_MERCHANT!,
recurring: { contract: Recurring.ContractEnum.Recurring },
shopperReference: "shopperReference",
merchantAccount: "MerchantAccount",
recurring: { contract: "ONECLICK" },
shopperReference: "test-123",
};
};
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
let client: Client;
let recurring: RecurringService;
let checkout: Checkout;
let recurring: Recurring;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient();
recurring = new RecurringService(client);
checkout = new Checkout(client);
client = createMockClientFromResponse();
recurring = new Recurring(client);
scope = nock(`${client.config.endpoint}/pal/servlet/Recurring/${Client.RECURRING_API_VERSION}`);
});
afterEach(() => {
nock.cleanAll();
});
describe("Recurring", (): void => {
test.each([false, true])("should test have recurring details list, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should test have recurring details list", async (): Promise<void> => {
scope.post("/listRecurringDetails")
.reply(200, listRecurringDetailsSuccess);
const request = createRecurringDetailsRequest();
try {
const result = await recurring.listRecurringDetails(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
const result = await recurring.listRecurringDetails(request);
expect(result).toEqual(listRecurringDetailsSuccess);
});
test.each([isCI, true])("should disable, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/payments")
.reply(200, paymentsSuccess);
const paymentsRequest: PaymentRequest = createPaymentsCheckoutRequest();
const res = await checkout.payments(paymentsRequest);
it("should disable", async (): Promise<void> => {
scope.post("/disable")
.reply(200, disableSuccess);
const request: DisableRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
shopperReference: "shopperReference",
recurringDetailReference: res.additionalData!["recurring.recurringDetailReference"]
const request: IRecurring.DisableRequest = {
merchantAccount: "MerchantAccount",
recurringDetailReference: "reference",
shopperReference: "test-123",
};
try {
const result = await recurring.disable(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
test.each([isCI, true])("should send pre-debit Notification, isMock %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/notifyShopper")
.reply(200, notifyShopperSuccess);
const notifyShopperRequest: NotifyShopperRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
shopperReference: "shopperReference",
storedPaymentMethodId: "8415995487234100",
amount: {
currency: "INR",
value: 1000
},
billingDate: "2021-03-16",
reference: "Example reference",
displayedReference: "Example displayed reference"
};
try {
const result = await recurring.notifyShopper(notifyShopperRequest);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
});
// TODO: register account for AccountUpdater and unmock test
test.each([true])("should schedule account updater, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
const scheduleAccountUpdaterSuccess: ScheduleAccountUpdaterResult = {
pspReference: "mocked_psp",
result: "SUCCESS"
};
scope.post("/scheduleAccountUpdater")
.reply(200, scheduleAccountUpdaterSuccess);
const request: ScheduleAccountUpdaterRequest = {
merchantAccount: process.env.ADYEN_MERCHANT!,
reference: "ref",
card: {
expiryMonth: "03",
expiryYear: "2030",
holderName: "John Smith",
number: "4111111111111111"
}
};
try {
const result = await recurring.scheduleAccountUpdater(request);
expect(result).toBeTruthy();
} catch (e) {
fail(e.message);
}
const result = await recurring.disable(request);
expect(result).toEqual(disableSuccess);
});
});

View File

@@ -1,53 +1,24 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient, createTerminalAPIPaymentRequest, createTerminalAPIRefundRequest } from "../__mocks__/base";
import { asyncRes } from "../__mocks__/terminalApi/async";
import { syncRefund, syncRes } from "../__mocks__/terminalApi/sync";
import {createMockClientFromResponse, createTerminalAPIPaymentRequest} from "../__mocks__/base";
import {asyncRes} from "../__mocks__/terminalApi/async";
import {syncRes} from "../__mocks__/terminalApi/sync";
import Client from "../client";
import TerminalCloudAPI from "../services/terminalCloudAPI";
import { TerminalApiResponse } from "../typings/terminal/models";
import {Convert, TerminalApiResponse} from "../typings/terminal";
let client: Client;
let terminalCloudAPI: TerminalCloudAPI;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient(process.env.ADYEN_TERMINAL_APIKEY);
client.config.merchantAccount = process.env.ADYEN_TERMINAL_MERCHANT;
client = createMockClientFromResponse();
terminalCloudAPI = new TerminalCloudAPI(client);
scope = nock(`${client.config.terminalApiCloudEndpoint}`);
});
afterEach((): void => {
nock.cleanAll();
});
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
describe("Terminal Cloud API", (): void => {
test.each([isCI, true])("should make an async payment request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
it("should make an async payment request", async (): Promise<void> => {
scope.post("/async").reply(200, asyncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
@@ -57,29 +28,13 @@ describe("Terminal Cloud API", (): void => {
expect(requestResponse).toEqual("ok");
});
test.each([isCI, true])("should make a sync payment request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/sync").reply(200, syncRes);
it("should make a sync payment request", async (): Promise<void> => {
const response = Convert.toTerminalApiResponse(syncRes);
scope.post("/sync").reply(200, response);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const terminalAPIResponse: TerminalApiResponse = await terminalCloudAPI.sync(terminalAPIPaymentRequest);
expect(terminalAPIResponse.saleToPOIResponse?.paymentResponse).toBeDefined();
expect(terminalAPIResponse.saleToPOIResponse?.messageHeader).toBeDefined();
});
test.each([isCI, true])("should make an async refund request, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/sync").reply(200, syncRes);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const terminalAPIResponse: TerminalApiResponse = await terminalCloudAPI.sync(terminalAPIPaymentRequest);
scope.post("/sync").reply(200, syncRefund);
const terminalAPIRefundRequest = createTerminalAPIRefundRequest(terminalAPIResponse.saleToPOIResponse?.paymentResponse?.pOIData.pOITransactionID!);
const terminalAPIRefundResponse = await terminalCloudAPI.sync(terminalAPIRefundRequest);
expect(terminalAPIRefundResponse.saleToPOIResponse?.reversalResponse).toBeDefined();
expect(terminalAPIResponse).toEqual(response);
});
});

View File

@@ -1,28 +1,9 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import nock from "nock";
import { createClient, createTerminalAPIPaymentRequest } from "../__mocks__/base";
import { localEncRes, wrongEncRes } from "../__mocks__/terminalApi/local";
import {createMockClientFromResponse, createTerminalAPIPaymentRequest} from "../__mocks__/base";
import {localEncRes, localSecuredRes, wrongEncRes} from "../__mocks__/terminalApi/local";
import Client from "../client";
import TerminalLocalAPI from "../services/terminalLocalAPI";
import { SecurityKey, TerminalApiResponse } from "../typings/terminal/models";
import {Convert, SecurityKey, TerminalApiResponse} from "../typings/terminal";
import NexoCryptoException from "../services/exception/nexoCryptoException";
let client: Client;
@@ -30,50 +11,42 @@ let terminalLocalAPI: TerminalLocalAPI;
let scope: nock.Scope;
beforeEach((): void => {
if (!nock.isActive()) {
nock.activate();
}
client = createClient();
client = createMockClientFromResponse();
terminalLocalAPI = new TerminalLocalAPI(client);
scope = nock(client.config.terminalApiLocalEndpoint + ":8443/nexo");
});
afterEach((): void => {
nock.cleanAll();
});
const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI);
describe("Terminal Local API", (): void => {
test.each([isCI, true])("should make a local payment, isMock: %p", async (isMock): Promise<void> => {
!isMock && nock.restore();
scope.post("/").reply(200, localEncRes);
it("should make a local payment", async (): Promise<void> => {
const securedResponse = Convert.toTerminalApiSecuredResponse(localEncRes);
const response = Convert.toTerminalApiResponse(localSecuredRes);
scope.post("/").reply(200, securedResponse);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const securityKey: SecurityKey = {
adyenCryptoVersion: 0,
adyenCryptoVersion: 1,
keyIdentifier: "CryptoKeyIdentifier12345",
keyVersion: 0,
keyVersion: 1,
passphrase: "p@ssw0rd123456",
};
const terminalApiResponse: TerminalApiResponse =
await terminalLocalAPI.request(terminalAPIPaymentRequest, securityKey);
expect(terminalApiResponse.saleToPOIResponse?.paymentResponse).toBeDefined();
expect(terminalApiResponse.saleToPOIResponse?.messageHeader).toBeDefined();
expect(response).toEqual(terminalApiResponse);
});
test.each([isCI, true])("should return NexoCryptoException, isMock: %p", async (isMock: boolean): Promise<void> => {
!isMock && nock.restore();
scope.post("/").reply(200, wrongEncRes);
it("should return NexoCryptoException", async (): Promise<void> => {
const securedResponse = Convert.toTerminalApiSecuredResponse(wrongEncRes);
scope.post("/").reply(200, securedResponse);
const terminalAPIPaymentRequest = createTerminalAPIPaymentRequest();
const securityKey: SecurityKey = {
adyenCryptoVersion: 0,
adyenCryptoVersion: 1,
keyIdentifier: "CryptoKeyIdentifier12345",
keyVersion: 0,
keyVersion: 1,
passphrase: "p@ssw0rd123456",
};

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,15 +11,17 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import Config from "./config";
import HttpURLConnectionClient from "./httpClient/httpURLConnectionClient";
import { version } from "../package.json";
import {version} from "../package.json";
import ClientInterface from "./httpClient/clientInterface";
type ClientParametersOverload =
@@ -52,20 +54,19 @@ class Client {
public static HPP_LIVE = "https://live.adyen.com/hpp";
public static MARKETPAY_ENDPOINT_TEST = "https://cal-test.adyen.com/cal/services";
public static MARKETPAY_ENDPOINT_LIVE = "https://cal-live.adyen.com/cal/services";
public static CHECKOUT_API_VERSION = "v67";
public static API_VERSION = "v64";
public static API_VERSION = "v51";
public static RECURRING_API_VERSION = "v49";
public static MARKETPAY_ACCOUNT_API_VERSION = "v6";
public static MARKETPAY_FUND_API_VERSION = "v6";
public static MARKETPAY_HOP_API_VERSION = "v6";
public static MARKETPAY_ACCOUNT_API_VERSION = "v5";
public static MARKETPAY_FUND_API_VERSION = "v5";
public static MARKETPAY_NOTIFICATION_API_VERSION = "v5";
public static MARKETPAY_NOTIFICATION_CONFIGURATION_API_VERSION = "v6";
public static LIB_NAME = "adyen-node-api-library";
public static LIB_VERSION: string = version;
public static CHECKOUT_ENDPOINT_TEST = "https://checkout-test.adyen.com/checkout";
public static CHECKOUT_ENDPOINT_LIVE_SUFFIX = "-checkout-live.adyenpayments.com/checkout";
public static CHECKOUT_API_VERSION = "v51";
public static BIN_LOOKUP_PAL_SUFFIX = "/pal/servlet/BinLookup/";
public static BIN_LOOKUP_API_VERSION = "v50";
public static CHECKOUT_UTILITY_API_VERSION = "v1";
public static TERMINAL_API_ENDPOINT_TEST = "https://terminal-api-test.adyen.com";
public static TERMINAL_API_ENDPOINT_LIVE = "https://terminal-api-live.adyen.com";
public static ENDPOINT_PROTOCOL = "https://";
@@ -111,7 +112,6 @@ class Client {
this.config.endpoint = Client.ENDPOINT_LIVE;
this.config.marketPayEndpoint = Client.MARKETPAY_ENDPOINT_LIVE;
this.config.hppEndpoint = Client.HPP_LIVE;
this.config.terminalApiCloudEndpoint = Client.TERMINAL_API_ENDPOINT_LIVE;
if (liveEndpointUrlPrefix) {
this.config.endpoint =
`${Client.ENDPOINT_PROTOCOL}${liveEndpointUrlPrefix}${Client.ENDPOINT_LIVE_SUFFIX}`;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -1,23 +1,4 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { PeerCertificate } from "tls";
import {PeerCertificate} from "tls";
export default function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined {
const { subject: { CN }} = cert;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -20,7 +22,7 @@
import Resource from "../services/resource";
import HttpClientException from "../httpClient/httpClientException";
import ApiException from "../services/exception/apiException";
import { IRequest } from "../typings/requestOptions";
import {IRequest} from "../typings/requestOptions";
async function getJsonResponse<T>(resource: Resource, jsonRequest: T | string, requestOptions?: IRequest.Options): Promise<string>;
async function getJsonResponse<T, R>(resource: Resource, jsonRequest: T | string, requestOptions?: IRequest.Options): Promise<R>;

View File

@@ -1,23 +1,4 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { ApplicationInfo } from "../typings/applicationInfo";
import {ApplicationInfo} from "../typings/applicationInfo";
interface AppInfo { applicationInfo?: ApplicationInfo }

View File

@@ -11,16 +11,18 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { AgentOptions } from "https";
import HttpClientException from "./httpClientException";
import ApiException from "../services/exception/apiException";
import { Config } from "../index";
import { IRequest } from "../typings/requestOptions";
import {Config} from "../index";
import {IRequest} from "../typings/requestOptions";
interface ClientInterface {
request(

View File

@@ -11,37 +11,31 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { IncomingHttpHeaders } from "http";
interface ExceptionInterface {
message: string;
statusCode?: number;
errorCode?: string;
responseHeaders?: IncomingHttpHeaders;
responseBody?: string;
}
import {IncomingHttpHeaders, IncomingMessage} from "http";
class HttpClientException implements Error {
public statusCode = 500;
public errorCode?: string;
public responseHeaders?: IncomingHttpHeaders;
public errorCode: string | undefined;
public responseHeaders: IncomingHttpHeaders | undefined;
public readonly message: string;
public readonly name: string;
public responseBody?: string;
public responseBody: IncomingMessage | undefined;
public constructor(props: ExceptionInterface) {
public constructor(message: string, statusCode?: number, errorCode?: string, responseHeaders?: IncomingHttpHeaders, responseBody?: IncomingMessage) {
this.name = "HttpClientException";
this.message = props.message;
if (props.responseHeaders) this.responseHeaders = props.responseHeaders;
if (props.responseBody) this.responseBody = props.responseBody;
if (props.errorCode) this.errorCode = props.errorCode;
if (props.statusCode) this.statusCode = props.statusCode;
this.message = message;
if(errorCode) this.errorCode = errorCode;
if(statusCode) this.statusCode = statusCode;
if(responseHeaders) this.responseHeaders = responseHeaders;
if(responseBody) this.responseBody = responseBody;
}
}

View File

@@ -11,27 +11,29 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { ClientRequest, IncomingHttpHeaders, IncomingMessage } from "http";
import { Agent, AgentOptions, request as httpsRequest } from "https";
import { HttpsProxyAgent } from "https-proxy-agent";
import {ClientRequest, IncomingMessage} from "http";
import {Agent, AgentOptions, request as httpsRequest} from "https";
import HttpsProxyAgent from "https-proxy-agent";
import * as fs from "fs";
import { URL } from "url";
import {URL} from "url";
import Client from "../client";
import Config from "../config";
import HttpClientException from "./httpClientException";
import checkServerIdentity from "../helpers/checkServerIdentity";
import { ApiError } from "../typings/apiError";
import {ApiError} from "../typings/apiError";
import ApiException from "../services/exception/apiException";
import ClientInterface from "./clientInterface";
import { ApiConstants } from "../constants/apiConstants";
import { IRequest } from "../typings/requestOptions";
import {ApiConstants} from "../constants/apiConstants";
import {IRequest} from "../typings/requestOptions";
class HttpURLConnectionClient implements ClientInterface {
private static CHARSET = "utf-8";
@@ -59,7 +61,7 @@ class HttpURLConnectionClient implements ClientInterface {
requestOptions.headers[ApiConstants.API_KEY] = apiKey;
} else {
const authString = `${config.username}:${config.password}`;
const authStringEnc = Buffer.from(authString, "utf8").toString("base64");
const authStringEnc = new Buffer(authString).toString("base64");
requestOptions.headers.Authorization = `Basic ${authStringEnc}`;
}
@@ -100,11 +102,7 @@ class HttpURLConnectionClient implements ClientInterface {
}
requestOptions.headers["Cache-Control"] = "no-cache";
if (!requestOptions.method) {
requestOptions.method = ApiConstants.METHOD_POST;
}
requestOptions.method = ApiConstants.METHOD_POST;
requestOptions.headers[ApiConstants.ACCEPT_CHARSET] = HttpURLConnectionClient.CHARSET;
requestOptions.headers[ApiConstants.USER_AGENT] = `${applicationName} ${Client.LIB_NAME}/${Client.LIB_VERSION}`;
@@ -120,49 +118,33 @@ class HttpURLConnectionClient implements ClientInterface {
connectionRequest.flushHeaders();
connectionRequest.on("response", (res: IncomingMessage): void => {
const response: { headers: IncomingHttpHeaders; body: string; statusCode: number | undefined } = {
statusCode: res.statusCode,
headers: res.headers,
body: ""
};
let resData = "";
const getException = (): HttpClientException => new HttpClientException(
`HTTP Exception: ${res.statusCode}. ${res.statusMessage}`,
res.statusCode,
undefined,
res.headers,
res,
);
let exception: HttpClientException | Error = getException();
const getException = (responseBody: string): HttpClientException => new HttpClientException({
message: `HTTP Exception: ${response.statusCode}. ${res.statusMessage}`,
statusCode: response.statusCode,
errorCode: undefined,
responseHeaders: response.headers,
responseBody,
});
let exception: HttpClientException | Error = getException(response.body.toString());
res.on("data", (chunk: string): void => {
response.body += chunk;
});
res.on("end", (): void => {
if (!res.complete) {
reject(new Error("The connection was terminated while the message was still being sent"));
}
if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
res.on("data", (data): void => {
if (res.statusCode && res.statusCode !== 200) {
try {
const formattedData: ApiError | {[key: string]: never} = JSON.parse(response.body);
const formattedData: ApiError = JSON.parse(data.toString() as string);
const isApiError = "status" in formattedData;
const isRequestError = "errors" in formattedData;
if (isApiError) {
exception = new HttpClientException({
message: `HTTP Exception: ${formattedData.status}. ${res.statusMessage}: ${formattedData.message}`,
statusCode: formattedData.status,
errorCode: formattedData.errorCode,
responseHeaders: res.headers,
responseBody: response.body,
});
exception = new HttpClientException(
`HTTP Exception: ${formattedData.status}. ${res.statusMessage}: ${formattedData.message}`,
formattedData.status,
formattedData.errorCode,
res.headers,
res,
);
} else if (isRequestError) {
exception = new Error(response.body);
} else {
exception = getException(response.body);
exception = new Error(data);
}
} catch (e) {
reject(exception);
@@ -171,7 +153,14 @@ class HttpURLConnectionClient implements ClientInterface {
}
}
resolve(response.body as string);
resData += data;
});
res.on("end", (): void => {
if (!res.complete) {
reject(new Error("The connection was terminated while the message was still being sent"));
}
resolve(resData);
});
res.on("error", reject);
@@ -196,7 +185,7 @@ class HttpURLConnectionClient implements ClientInterface {
};
} catch (e) {
return Promise.reject(new HttpClientException({ message: `Error loading certificate from path: ${e.message}` }));
return Promise.reject(new HttpClientException(`Error loading certificate from path: ${e.message}`));
}
}

View File

@@ -11,13 +11,15 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import "./typings";
// import "./typings";
export { default as Client } from "./client";
export { default as Config } from "./config";

View File

@@ -11,21 +11,18 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import {
Notification,
NotificationItem,
NotificationRequestItem,
ObjectSerializer
} from "../typings/notification/models";
import {Convert, Notification, NotificationItem, NotificationRequestItem} from "../typings/notification";
class NotificationRequest {
public constructor(json: Notification) {
const notification: Notification = ObjectSerializer.deserialize(json, "Notification");
const notification = Convert.toNotification(JSON.stringify(json));
this.notificationItemContainers = notification.notificationItems;
this.live = notification.live;
}
@@ -35,7 +32,7 @@ class NotificationRequest {
return undefined;
}
return this.notificationItemContainers.map((container): NotificationRequestItem => container.notificationRequestItem);
return this.notificationItemContainers.map((container): NotificationRequestItem => container.NotificationRequestItem);
}
public live: string;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,24 +11,26 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { Cipher, createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "crypto";
import {Cipher, createCipheriv, createDecipheriv, createHmac, randomBytes} from "crypto";
import NexoCryptoException from "../services/exception/nexoCryptoException";
import {
MessageHeader,
NexoDerivedKey,
SaleToPOISecuredMessage,
SaleToPoiSecuredMessage,
SecurityKey,
SecurityTrailer,
} from "../typings/terminal/models";
} from "../typings/terminal";
import InvalidSecurityKeyException from "./exception/invalidSecurityKeyException";
import NexoDerivedKeyGenerator from "./nexoDerivedKeyGenerator";
import { NexoEnum } from "../constants/nexoConstants";
import {NexoEnum} from "../constants/nexoConstants";
enum Modes {
ENCRYPT,
@@ -40,9 +42,9 @@ class NexoCrypto {
messageHeader: MessageHeader,
saleToPoiMessageJson: string,
securityKey: SecurityKey,
): SaleToPOISecuredMessage {
): SaleToPoiSecuredMessage {
const derivedKey: NexoDerivedKey = NexoDerivedKeyGenerator.deriveKeyMaterial(securityKey.passphrase);
const saleToPoiMessageByteArray = Buffer.from(saleToPoiMessageJson, "utf-8");
const saleToPoiMessageByteArray = Buffer.from(saleToPoiMessageJson, "ascii");
const ivNonce = NexoCrypto.generateRandomIvNonce();
const encryptedSaleToPoiMessage = NexoCrypto.crypt(saleToPoiMessageByteArray, derivedKey, ivNonce, Modes.ENCRYPT);
const encryptedSaleToPoiMessageHmac = NexoCrypto.hmac(saleToPoiMessageByteArray, derivedKey);
@@ -58,11 +60,11 @@ class NexoCrypto {
return {
messageHeader,
nexoBlob: encryptedSaleToPoiMessage.toString("base64"),
securityTrailer,
securityTrailer: securityTrailer,
};
}
public decrypt(saleToPoiSecureMessage: SaleToPOISecuredMessage, securityKey: SecurityKey): string {
public decrypt(saleToPoiSecureMessage: SaleToPoiSecuredMessage, securityKey: SecurityKey): string {
NexoCrypto.validateSecurityKey(securityKey);
const encryptedSaleToPoiMessageByteArray = Buffer.from(saleToPoiSecureMessage.nexoBlob, "base64");
@@ -74,15 +76,15 @@ class NexoCrypto {
const receivedHmac = Buffer.from(saleToPoiSecureMessage.securityTrailer.hmac, "base64");
this.validateHmac(receivedHmac, decryptedSaleToPoiMessageByteArray, derivedKey);
return decryptedSaleToPoiMessageByteArray.toString("utf-8");
return decryptedSaleToPoiMessageByteArray.toString("ascii");
}
private static validateSecurityKey(securityKey: SecurityKey): void {
const isValid = securityKey
&& securityKey.passphrase
&& securityKey.keyIdentifier
&& !isNaN(securityKey.keyVersion)
&& !isNaN(securityKey.adyenCryptoVersion);
&& securityKey.keyVersion
&& securityKey.adyenCryptoVersion;
if (!isValid) {
throw new InvalidSecurityKeyException("Invalid Security Key");
}
@@ -115,7 +117,9 @@ class NexoCrypto {
private validateHmac(receivedHmac: Buffer, decryptedMessage: Buffer, derivedKey: NexoDerivedKey): void {
const hmac = NexoCrypto.hmac(decryptedMessage, derivedKey);
if (!timingSafeEqual(hmac, receivedHmac)) {
const isValid = hmac.every((item, index): boolean => item === receivedHmac[index]);
if (!isValid) {
throw new NexoCryptoException("Hmac validation failed");
}
}

View File

@@ -11,15 +11,17 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import { pbkdf2Sync } from "crypto";
import { NexoDerivedKey } from "../typings/terminal/models";
import { NexoEnum } from "../constants/nexoConstants";
import {pbkdf2Sync} from "crypto";
import { NexoDerivedKey } from "../typings/terminal";
import {NexoEnum} from "../constants/nexoConstants";
class NexoDerivedKeyGenerator {
public static deriveKeyMaterial(passphrase: string): NexoDerivedKey {

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -26,35 +28,8 @@ import PaymentsDetails from "./resource/checkout/paymentsDetails";
import PaymentSession from "./resource/checkout/paymentSession";
import PaymentsResult from "./resource/checkout/paymentsResult";
import PaymentLinks from "./resource/checkout/paymentLinks";
import OriginKeys from "./resource/checkout/originKeys";
import setApplicationInfo from "../helpers/setApplicationInfo";
import { IRequest } from "../typings/requestOptions";
import {
PaymentRequest,
PaymentResponse,
PaymentMethodsRequest,
PaymentMethodsResponse,
PaymentLinkResource,
CreatePaymentLinkRequest,
DetailsRequest,
PaymentSetupRequest,
PaymentSetupResponse,
PaymentVerificationRequest,
PaymentVerificationResponse,
CheckoutUtilityRequest,
CheckoutUtilityResponse,
CheckoutBalanceCheckRequest,
CheckoutBalanceCheckResponse,
CheckoutCreateOrderRequest,
CheckoutCreateOrderResponse,
CheckoutCancelOrderRequest,
CheckoutCancelOrderResponse
} from "../typings/checkout/models";
import PaymentLinksId from "./resource/checkout/paymentLinksId";
import PaymentMethodsBalance from "./resource/checkout/paymentMethodsBalance";
import Orders from "./resource/checkout/orders";
import OrdersCancel from "./resource/checkout/ordersCancel";
import {IRequest} from "../typings/requestOptions";
class Checkout extends ApiKeyAuthenticatedService {
private readonly _payments: Payments;
@@ -63,11 +38,6 @@ class Checkout extends ApiKeyAuthenticatedService {
private readonly _paymentSession: PaymentSession;
private readonly _paymentsResult: PaymentsResult;
private readonly _paymentLinks: PaymentLinks;
private readonly _paymentLinksId: PaymentLinksId;
private readonly _originKeys: OriginKeys;
private readonly _paymentMethodsBalance: PaymentMethodsBalance;
private readonly _orders: Orders;
private readonly _ordersCancel: OrdersCancel;
public constructor(client: Client) {
super(client);
@@ -77,106 +47,54 @@ class Checkout extends ApiKeyAuthenticatedService {
this._paymentSession = new PaymentSession(this);
this._paymentsResult = new PaymentsResult(this);
this._paymentLinks = new PaymentLinks(this);
this._paymentLinksId = new PaymentLinksId(this);
this._originKeys = new OriginKeys(this);
this._paymentMethodsBalance = new PaymentMethodsBalance(this);
this._orders = new Orders(this);
this._ordersCancel = new OrdersCancel(this);
}
public payments(paymentsRequest: PaymentRequest, requestOptions?: IRequest.Options): Promise<PaymentResponse> {
return getJsonResponse<PaymentRequest, PaymentResponse>(
public payments(paymentsRequest: ICheckout.PaymentRequest, requestOptions?: IRequest.Options): Promise<ICheckout.PaymentResponse> {
return getJsonResponse<ICheckout.PaymentRequest, ICheckout.PaymentResponse>(
this._payments,
setApplicationInfo(paymentsRequest),
requestOptions,
);
}
public paymentMethods(paymentMethodsRequest: PaymentMethodsRequest): Promise<PaymentMethodsResponse> {
return getJsonResponse<PaymentMethodsRequest, PaymentMethodsResponse>(
public paymentMethods(paymentMethodsRequest: ICheckout.PaymentMethodsRequest): Promise<ICheckout.PaymentMethodsResponse> {
return getJsonResponse<ICheckout.PaymentMethodsRequest, ICheckout.PaymentMethodsResponse>(
this._paymentMethods,
paymentMethodsRequest,
);
}
public paymentLinks(paymentLinkRequest: CreatePaymentLinkRequest): Promise<PaymentLinkResource> {
return getJsonResponse<CreatePaymentLinkRequest, PaymentLinkResource>(
public paymentLinks(paymentLinkRequest: ICheckout.CreatePaymentLinkRequest): Promise<ICheckout.CreatePaymentLinkResponse> {
return getJsonResponse<ICheckout.CreatePaymentLinkRequest, ICheckout.CreatePaymentLinkResponse>(
this._paymentLinks,
paymentLinkRequest
);
}
public getPaymentLinks(linkId: string): Promise<PaymentLinkResource> {
this._paymentLinksId.id = linkId;
return getJsonResponse<{}, PaymentLinkResource>(
this._paymentLinksId,
{},
{ method: "GET" }
);
}
public updatePaymentLinks(linkId: string, status: "expired"): Promise<PaymentLinkResource> {
this._paymentLinksId.id = linkId;
return getJsonResponse<{}, PaymentLinkResource>(
this._paymentLinksId,
{ status },
{ method: "PATCH" }
);
}
public paymentsDetails(paymentsDetailsRequest: DetailsRequest, requestOptions?: IRequest.Options): Promise<PaymentResponse> {
return getJsonResponse<DetailsRequest, PaymentResponse>(
public paymentsDetails(paymentsDetailsRequest: ICheckout.DetailsRequest): Promise<ICheckout.PaymentResponse> {
return getJsonResponse<ICheckout.DetailsRequest, ICheckout.PaymentResponse>(
this._paymentsDetails,
paymentsDetailsRequest,
requestOptions
);
}
public paymentSession(
paymentSessionRequest: PaymentSetupRequest,
paymentSessionRequest: ICheckout.PaymentSetupRequest,
requestOptions?: IRequest.Options,
): Promise<PaymentSetupResponse> {
return getJsonResponse<PaymentSetupRequest, PaymentSetupResponse>(
): Promise<ICheckout.PaymentSetupResponse> {
return getJsonResponse<ICheckout.PaymentSetupRequest, ICheckout.PaymentSetupResponse>(
this._paymentSession,
paymentSessionRequest,
requestOptions,
);
}
public paymentResult(paymentResultRequest: PaymentVerificationRequest): Promise<PaymentVerificationResponse> {
return getJsonResponse<PaymentVerificationRequest, PaymentVerificationResponse>(
public paymentResult(paymentResultRequest: ICheckout.PaymentVerificationRequest): Promise<ICheckout.PaymentVerificationResponse> {
return getJsonResponse<ICheckout.PaymentVerificationRequest, ICheckout.PaymentVerificationResponse>(
this._paymentsResult,
paymentResultRequest,
);
}
public originKeys(originKeysRequest: CheckoutUtilityRequest): Promise<CheckoutUtilityResponse> {
return getJsonResponse<CheckoutUtilityRequest, CheckoutUtilityResponse>(
this._originKeys,
originKeysRequest,
);
}
public paymentMethodsBalance(paymentMethodsBalanceRequest: CheckoutBalanceCheckRequest): Promise<CheckoutBalanceCheckResponse> {
return getJsonResponse<CheckoutBalanceCheckRequest, CheckoutBalanceCheckResponse>(
this._paymentMethodsBalance,
paymentMethodsBalanceRequest,
);
}
public orders(ordersRequest: CheckoutCreateOrderRequest): Promise<CheckoutCreateOrderResponse> {
return getJsonResponse<CheckoutCreateOrderRequest, CheckoutCreateOrderResponse>(
this._orders,
ordersRequest,
);
}
public ordersCancel(ordersCancelRequest: CheckoutCancelOrderRequest): Promise<CheckoutCancelOrderResponse> {
return getJsonResponse<CheckoutCancelOrderRequest, CheckoutCancelOrderResponse>(
this._ordersCancel,
ordersCancelRequest,
);
}
}
export default Checkout;

View File

@@ -19,19 +19,25 @@
* See the LICENSE file for more info.
*/
import Client from "../../../client";
import Service from "../../../service";
import Resource from "../../resource";
import ApiKeyAuthenticatedService from "../apiKeyAuthenticatedService";
import Client from "../client";
import getJsonResponse from "../helpers/getJsonResponse";
import OriginKeys from "./resource/checkoutUtility/originKeys";
type Endpoints = "/getOnboardingUrl";
class CheckoutUtility extends ApiKeyAuthenticatedService {
private readonly _originKeys: OriginKeys;
class PlatformsHostedOnboardingPage extends Resource {
public constructor(service: Service, endpoint: Endpoints) {
super(
service,
`${service.client.config.marketPayEndpoint}/Hop/${Client.MARKETPAY_HOP_API_VERSION}/${endpoint}`,
public constructor(client: Client) {
super(client);
this._originKeys = new OriginKeys(this);
}
public originKeys(originKeysRequest: ICheckoutUtility.CheckoutUtilityRequest): Promise<ICheckoutUtility.CheckoutUtilityResponse> {
return getJsonResponse<ICheckoutUtility.CheckoutUtilityRequest, ICheckoutUtility.CheckoutUtilityResponse>(
this._originKeys,
originKeysRequest,
);
}
}
export default PlatformsHostedOnboardingPage;
export default CheckoutUtility;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -20,8 +22,8 @@
export { default as TerminalLocalAPI } from "./terminalLocalAPI";
export { default as TerminalCloudAPI } from "./terminalCloudAPI";
export { default as CheckoutAPI } from "./checkout";
export { default as CheckoutUtility } from "./checkoutUtility";
export { default as Recurring } from "./recurring";
export { default as Modification } from "./modification";
export { default as BinLookup } from "./binLookup";
export { default as Payout } from "./payout";
export { default as Platforms } from "./platforms";

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -26,8 +28,8 @@ import Capture from "./resource/modification/capture";
import Refund from "./resource/modification/refund";
import TechnicalCancel from "./resource/modification/technicalCancel";
import setApplicationInfo from "../helpers/setApplicationInfo";
import { ApplicationInfo } from "../typings/applicationInfo";
import { IRequest } from "../typings/requestOptions";
import {ApplicationInfo} from "../typings/applicationInfo";
import {IRequest} from "../typings/requestOptions";
interface AppInfo { applicationInfo?: ApplicationInfo }
type GenericRequest<T> = T & AppInfo;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -1,247 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import Service from "../service";
import Client from "../client";
import PlatformsAccount, { AccountTypesEnum } from "./resource/platforms/account";
import getJsonResponse from "./../helpers/getJsonResponse";
import PlatformsFund from "./resource/platforms/fund";
import PlatformsHostedOnboardingPage from "./resource/platforms/hop";
import PlatformsNotificationConfiguration from "./resource/platforms/notificationConfiguration";
import {
GetAccountHolderRequest,
GetUploadedDocumentsRequest,
GetAccountHolderResponse,
GetUploadedDocumentsResponse,
CreateAccountHolderRequest,
CreateAccountHolderResponse,
CloseAccountHolderRequest,
CloseAccountHolderResponse,
CreateAccountRequest,
CreateAccountResponse,
DeleteBankAccountRequest,
GenericResponse,
DeletePayoutMethodRequest,
UpdateAccountRequest,
UpdateAccountResponse,
UploadDocumentRequest,
UnSuspendAccountHolderRequest,
UnSuspendAccountHolderResponse,
CloseAccountRequest,
CloseAccountResponse,
SuspendAccountHolderRequest,
SuspendAccountHolderResponse,
UpdateAccountHolderRequest,
UpdateAccountHolderResponse,
DeleteShareholderRequest,
PerformVerificationRequest,
UpdateAccountHolderStateRequest,
GetAccountHolderStatusResponse
} from "../typings/platformsAccount/models";
type AccountType = AccountTypesEnum.Accounts;
type VerificationType = AccountTypesEnum.Verification;
type AccountHoldersType = AccountTypesEnum.AccountHolders;
type AccountsAccount = PlatformsAccount<AccountType>;
type AccountsVerification = PlatformsAccount<VerificationType>;
type AccountsAccountHolders = PlatformsAccount<AccountHoldersType>;
type PlatformsTypes = AccountsAccount | AccountsVerification | AccountsAccountHolders | PlatformsFund | PlatformsHostedOnboardingPage;
class Platforms extends Service {
/* PlatformsAccount */
// Accounts
private readonly _closeAccount: PlatformsAccount<AccountType>;
private readonly _updateAccount: PlatformsAccount<AccountType>;
private readonly _createAccount: PlatformsAccount<AccountType>;
// Verification
private readonly _uploadDocument: PlatformsAccount<VerificationType>;
private readonly _getUploadedDocuments: PlatformsAccount<VerificationType>;
private readonly _deleteBankAccounts: PlatformsAccount<VerificationType>;
private readonly _deletePayoutMethods: PlatformsAccount<VerificationType>;
private readonly _deleteShareholders: PlatformsAccount<VerificationType>;
private readonly _checkAccountHolder: PlatformsAccount<VerificationType>;
// Account Holders
private readonly _createAccountHolder: PlatformsAccount<AccountHoldersType>;
private readonly _getAccountHolder: PlatformsAccount<AccountHoldersType>;
private readonly _updateAccountHolder: PlatformsAccount<AccountHoldersType>;
private readonly _updateAccountHolderState: PlatformsAccount<AccountHoldersType>;
private readonly _suspendAccountHolder: PlatformsAccount<AccountHoldersType>;
private readonly _unSuspendAccountHolder: PlatformsAccount<AccountHoldersType>;
private readonly _closeAccountHolder: PlatformsAccount<AccountHoldersType>;
/* PlatformsFund */
private readonly _accountHolderBalance: PlatformsFund;
private readonly _accountHolderTransactionList: PlatformsFund;
private readonly _payoutAccountHolder: PlatformsFund;
private readonly _transferFunds: PlatformsFund;
private readonly _refundFundsTransfer: PlatformsFund;
private readonly _setupBeneficiary: PlatformsFund;
private readonly _refundNotPaidOutTransfers: PlatformsFund;
/* HOP */
private readonly _getOnboardingUrl: PlatformsHostedOnboardingPage;
/* Notification Configuration */
private readonly _createNotificationConfiguration: PlatformsNotificationConfiguration;
private readonly _getNotificationConfiguration: PlatformsNotificationConfiguration;
private readonly _getNotificationConfigurationList: PlatformsNotificationConfiguration;
private readonly _testNotificationConfiguration: PlatformsNotificationConfiguration;
private readonly _updateNotificationConfiguration: PlatformsNotificationConfiguration;
private readonly _deleteNotificationConfiguration: PlatformsNotificationConfiguration;
public constructor(client: Client) {
super(client);
// Account
this._closeAccount = new PlatformsAccount<AccountType>(this, "/closeAccount");
this._updateAccount = new PlatformsAccount<AccountType>(this, "/updateAccount");
this._createAccount = new PlatformsAccount<AccountType>(this, "/createAccount");
this._uploadDocument = new PlatformsAccount<VerificationType>(this, "/uploadDocument");
this._getUploadedDocuments = new PlatformsAccount<VerificationType>(this, "/getUploadedDocuments");
this._deleteBankAccounts = new PlatformsAccount<VerificationType>(this, "/deleteBankAccounts");
this._deletePayoutMethods = new PlatformsAccount<VerificationType>(this, "/deletePayoutMethods");
this._deleteShareholders = new PlatformsAccount<VerificationType>(this, "/deleteShareholders");
this._checkAccountHolder = new PlatformsAccount<VerificationType>(this, "/checkAccountHolder");
this._createAccountHolder = new PlatformsAccount<AccountHoldersType>(this, "/createAccountHolder");
this._getAccountHolder = new PlatformsAccount<AccountHoldersType>(this, "/getAccountHolder");
this._updateAccountHolder = new PlatformsAccount<AccountHoldersType>(this, "/updateAccountHolder");
this._updateAccountHolderState = new PlatformsAccount<AccountHoldersType>(this, "/updateAccountHolderState");
this._suspendAccountHolder = new PlatformsAccount<AccountHoldersType>(this, "/suspendAccountHolder");
this._unSuspendAccountHolder = new PlatformsAccount<AccountHoldersType>(this, "/unSuspendAccountHolder");
this._closeAccountHolder = new PlatformsAccount<AccountHoldersType>(this, "/closeAccountHolder");
// Fund
this._accountHolderBalance = new PlatformsFund(this, "/accountHolderBalance");
this._accountHolderTransactionList = new PlatformsFund(this, "/accountHolderTransactionList");
this._payoutAccountHolder = new PlatformsFund(this, "/payoutAccountHolder");
this._transferFunds = new PlatformsFund(this, "/transferFunds");
this._refundFundsTransfer = new PlatformsFund(this, "/refundFundsTransfer");
this._setupBeneficiary = new PlatformsFund(this, "/setupBeneficiary");
this._refundNotPaidOutTransfers = new PlatformsFund(this, "/refundNotPaidOutTransfers");
// HOP
this._getOnboardingUrl = new PlatformsHostedOnboardingPage(this, "/getOnboardingUrl");
// Notification Configuration
this._createNotificationConfiguration = new PlatformsNotificationConfiguration(this, "/createNotificationConfiguration");
this._getNotificationConfiguration = new PlatformsNotificationConfiguration(this, "/getNotificationConfiguration");
this._getNotificationConfigurationList = new PlatformsNotificationConfiguration(this, "/getNotificationConfigurationList");
this._testNotificationConfiguration = new PlatformsNotificationConfiguration(this, "/testNotificationConfiguration");
this._updateNotificationConfiguration = new PlatformsNotificationConfiguration(this, "/updateNotificationConfiguration");
this._deleteNotificationConfiguration = new PlatformsNotificationConfiguration(this, "/deleteNotificationConfigurations");
}
createRequest = <T extends PlatformsTypes, U, V>(service: T) => {
return (request: U): Promise<V> => getJsonResponse<U, V>(service, request);
}
public get Account(): {
getAccountHolder: (request: GetAccountHolderRequest) => Promise<GetAccountHolderResponse>;
getUploadedDocuments: (request: GetUploadedDocumentsRequest) => Promise<GetUploadedDocumentsResponse>;
createAccountHolder: (request: CreateAccountHolderRequest) => Promise<CreateAccountHolderResponse>;
closeAccountHolder: (request: CloseAccountHolderRequest) => Promise<CloseAccountHolderResponse>;
createAccount: (request: CreateAccountRequest) => Promise<CreateAccountResponse>;
deleteBankAccounts: (request: DeleteBankAccountRequest) => Promise<GenericResponse>;
deletePayoutMethods: (request: DeletePayoutMethodRequest) => Promise<GenericResponse>;
updateAccount: (request: UpdateAccountRequest) => Promise<UpdateAccountResponse>;
uploadDocument: (request: UploadDocumentRequest) => Promise<GetUploadedDocumentsResponse>;
unSuspendAccountHolder: (request: UnSuspendAccountHolderRequest) => Promise<UnSuspendAccountHolderResponse>;
closeAccount: (request: CloseAccountRequest) => Promise<CloseAccountResponse>;
suspendAccountHolder: (request: SuspendAccountHolderRequest) => Promise<SuspendAccountHolderResponse>;
updateAccountHolder: (request: UpdateAccountHolderRequest) => Promise<UpdateAccountHolderResponse>;
deleteShareholders: (request: DeleteShareholderRequest) => Promise<GenericResponse>;
checkAccountHolder: (request: PerformVerificationRequest) => Promise<GenericResponse>;
updateAccountHolderState: (request: UpdateAccountHolderStateRequest) => Promise<GetAccountHolderStatusResponse>;
} {
const closeAccount = this.createRequest<AccountsAccount, CloseAccountRequest, CloseAccountResponse>(this._closeAccount);
const updateAccount = this.createRequest<AccountsAccount, UpdateAccountRequest, UpdateAccountResponse>(this._updateAccount);
const createAccount = this.createRequest<AccountsAccount, CreateAccountRequest, CreateAccountResponse>(this._createAccount);
const uploadDocument = this.createRequest<AccountsVerification, UploadDocumentRequest, GetUploadedDocumentsResponse>(this._uploadDocument);
const getUploadedDocuments = this.createRequest<AccountsVerification, GetUploadedDocumentsRequest, GetUploadedDocumentsResponse>(this._getUploadedDocuments);
const deleteBankAccounts = this.createRequest<AccountsVerification, DeleteBankAccountRequest, GenericResponse>(this._deleteBankAccounts);
const deletePayoutMethods = this.createRequest<AccountsVerification, DeletePayoutMethodRequest, GenericResponse>(this._deletePayoutMethods);
const deleteShareholders = this.createRequest<AccountsVerification, DeleteShareholderRequest, GenericResponse>(this._deleteShareholders);
const createAccountHolder = this.createRequest<AccountsAccountHolders, CreateAccountHolderRequest, CreateAccountHolderResponse>(this._createAccountHolder);
const getAccountHolder = this.createRequest<AccountsAccountHolders, GetAccountHolderRequest, GetAccountHolderResponse>(this._getAccountHolder);
const updateAccountHolder = this.createRequest<AccountsAccountHolders, UpdateAccountHolderRequest, UpdateAccountHolderResponse>(this._updateAccountHolder);
const updateAccountHolderState = this.createRequest<AccountsAccountHolders, UpdateAccountHolderStateRequest, GetAccountHolderStatusResponse>(this._updateAccountHolderState);
const suspendAccountHolder = this.createRequest<AccountsAccountHolders, SuspendAccountHolderRequest, SuspendAccountHolderResponse>(this._suspendAccountHolder);
const unSuspendAccountHolder = this.createRequest<AccountsAccountHolders, UnSuspendAccountHolderRequest, UnSuspendAccountHolderResponse>(this._unSuspendAccountHolder);
const closeAccountHolder = this.createRequest<AccountsAccountHolders, CloseAccountHolderRequest, CloseAccountHolderResponse>(this._closeAccountHolder);
const checkAccountHolder = this.createRequest<AccountsVerification, PerformVerificationRequest, GenericResponse>(this._checkAccountHolder);
const accounts = { closeAccount, updateAccount, createAccount };
const verification = { uploadDocument, getUploadedDocuments, deleteBankAccounts, deletePayoutMethods, deleteShareholders, checkAccountHolder };
const accountHolders = { createAccountHolder, getAccountHolder, updateAccountHolder, updateAccountHolderState, suspendAccountHolder, unSuspendAccountHolder, closeAccountHolder};
return {...accounts, ...verification, ...accountHolders };
}
public get Fund(): {
refundNotPaidOutTransfers: (request: IPlatformsFund.RefundNotPaidOutTransfersRequest) => Promise<IPlatformsFund.RefundNotPaidOutTransfersResponse>;
accountHolderTransactionList: (request: IPlatformsFund.AccountHolderTransactionListRequest) => Promise<IPlatformsFund.AccountHolderTransactionListResponse>;
setupBeneficiary: (request: IPlatformsFund.SetupBeneficiaryRequest) => Promise<IPlatformsFund.SetupBeneficiaryResponse>;
transferFunds: (request: IPlatformsFund.TransferFundsRequest) => Promise<IPlatformsFund.TransferFundsResponse>;
refundFundsTransfer: (request: IPlatformsFund.RefundFundsTransferRequest) => Promise<IPlatformsFund.RefundFundsTransferResponse>;
payoutAccountHolder: (request: IPlatformsFund.PayoutAccountHolderRequest) => Promise<IPlatformsFund.PayoutAccountHolderResponse>;
accountHolderBalance: (request: IPlatformsFund.AccountHolderBalanceRequest) => Promise<IPlatformsFund.AccountHolderBalanceResponse>;
} {
const accountHolderBalance = this.createRequest<PlatformsFund, IPlatformsFund.AccountHolderBalanceRequest, IPlatformsFund.AccountHolderBalanceResponse>(this._accountHolderBalance);
const accountHolderTransactionList = this.createRequest<PlatformsFund, IPlatformsFund.AccountHolderTransactionListRequest, IPlatformsFund.AccountHolderTransactionListResponse>(this._accountHolderTransactionList);
const payoutAccountHolder = this.createRequest<PlatformsFund, IPlatformsFund.PayoutAccountHolderRequest, IPlatformsFund.PayoutAccountHolderResponse>(this._payoutAccountHolder);
const transferFunds = this.createRequest<PlatformsFund, IPlatformsFund.TransferFundsRequest, IPlatformsFund.TransferFundsResponse>(this._transferFunds);
const refundFundsTransfer = this.createRequest<PlatformsFund, IPlatformsFund.RefundFundsTransferRequest, IPlatformsFund.RefundFundsTransferResponse>(this._refundFundsTransfer);
const setupBeneficiary = this.createRequest<PlatformsFund, IPlatformsFund.SetupBeneficiaryRequest, IPlatformsFund.SetupBeneficiaryResponse>(this._setupBeneficiary);
const refundNotPaidOutTransfers = this.createRequest<PlatformsFund, IPlatformsFund.RefundNotPaidOutTransfersRequest, IPlatformsFund.RefundNotPaidOutTransfersResponse>(this._refundNotPaidOutTransfers);
return { accountHolderBalance, accountHolderTransactionList, payoutAccountHolder, refundFundsTransfer, transferFunds, setupBeneficiary, refundNotPaidOutTransfers };
}
public get HostedOnboardingPage(): { getOnboardingUrl: (request: IPlatformsHostedOnboardingPage.GetOnboardingUrlRequest) => Promise<IPlatformsHostedOnboardingPage.GetOnboardingUrlResponse> } {
const getOnboardingUrl = this.createRequest<PlatformsHostedOnboardingPage, IPlatformsHostedOnboardingPage.GetOnboardingUrlRequest, IPlatformsHostedOnboardingPage.GetOnboardingUrlResponse>(this._getOnboardingUrl);
return { getOnboardingUrl };
}
public get NotificationConfiguration(): {
createNotificationConfiguration: (request: IPlatformsNotificationConfiguration.CreateNotificationConfigurationRequest) => Promise<IPlatformsNotificationConfiguration.GetNotificationConfigurationResponse>;
updateNotificationConfiguration: (request: IPlatformsNotificationConfiguration.UpdateNotificationConfigurationRequest) => Promise<IPlatformsNotificationConfiguration.GetNotificationConfigurationResponse>;
getNotificationConfiguration: (request: IPlatformsNotificationConfiguration.GetNotificationConfigurationRequest) => Promise<IPlatformsNotificationConfiguration.GetNotificationConfigurationResponse>;
testNotificationConfiguration: (request: IPlatformsNotificationConfiguration.TestNotificationConfigurationRequest) => Promise<IPlatformsNotificationConfiguration.TestNotificationConfigurationResponse>;
getNotificationConfigurationList: (request: {}) => Promise<IPlatformsNotificationConfiguration.GetNotificationConfigurationListResponse>;
deleteNotificationConfigurations: (request: IPlatformsNotificationConfiguration.DeleteNotificationConfigurationRequest) => Promise<IPlatformsNotificationConfiguration.GenericResponse>;
} {
const createNotificationConfiguration = this.createRequest<PlatformsHostedOnboardingPage, IPlatformsNotificationConfiguration.CreateNotificationConfigurationRequest, IPlatformsNotificationConfiguration.GetNotificationConfigurationResponse>(this._createNotificationConfiguration);
const getNotificationConfiguration = this.createRequest<PlatformsHostedOnboardingPage, IPlatformsNotificationConfiguration.GetNotificationConfigurationRequest, IPlatformsNotificationConfiguration.GetNotificationConfigurationResponse>(this._getNotificationConfiguration);
const getNotificationConfigurationList = this.createRequest<PlatformsHostedOnboardingPage, {}, IPlatformsNotificationConfiguration.GetNotificationConfigurationListResponse>(this._getNotificationConfigurationList);
const testNotificationConfiguration = this.createRequest<PlatformsHostedOnboardingPage, IPlatformsNotificationConfiguration.TestNotificationConfigurationRequest, IPlatformsNotificationConfiguration.TestNotificationConfigurationResponse>(this._testNotificationConfiguration);
const updateNotificationConfiguration = this.createRequest<PlatformsHostedOnboardingPage, IPlatformsNotificationConfiguration.UpdateNotificationConfigurationRequest, IPlatformsNotificationConfiguration.GetNotificationConfigurationResponse>(this._updateNotificationConfiguration);
const deleteNotificationConfigurations = this.createRequest<PlatformsHostedOnboardingPage, IPlatformsNotificationConfiguration.DeleteNotificationConfigurationRequest, IPlatformsNotificationConfiguration.GenericResponse>(this._deleteNotificationConfiguration);
return { createNotificationConfiguration, getNotificationConfiguration, getNotificationConfigurationList, testNotificationConfiguration, updateNotificationConfiguration, deleteNotificationConfigurations };
}
}
export default Platforms;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -22,60 +24,30 @@ import getJsonResponse from "../helpers/getJsonResponse";
import Service from "../service";
import Disable from "./resource/recurring/disable";
import ListRecurringDetails from "./resource/recurring/listRecurringDetails";
import ScheduleAccountUpdater from "./resource/recurring/scheduleAccountUpdater";
import NotifyShopper from "./resource/recurring/notifyShopper";
import {
RecurringDetailsRequest,
RecurringDetailsResult,
DisableRequest,
DisableResult,
ScheduleAccountUpdaterRequest,
ScheduleAccountUpdaterResult,
NotifyShopperRequest,
NotifyShopperResult
} from "../typings/recurring/models";
class Recurring extends Service {
private readonly _listRecurringDetails: ListRecurringDetails;
private readonly _disable: Disable;
private readonly _scheduleAccountUpdater: ScheduleAccountUpdater;
private readonly _notifyShopper: NotifyShopper
public constructor(client: Client) {
super(client);
this._listRecurringDetails = new ListRecurringDetails(this);
this._disable = new Disable(this);
this._scheduleAccountUpdater = new ScheduleAccountUpdater(this);
this._notifyShopper = new NotifyShopper(this);
}
public listRecurringDetails(request: RecurringDetailsRequest): Promise<RecurringDetailsResult> {
return getJsonResponse<RecurringDetailsRequest, RecurringDetailsResult>(
public listRecurringDetails(request: IRecurring.RecurringDetailsRequest): Promise<IRecurring.RecurringDetailsResult> {
return getJsonResponse<IRecurring.RecurringDetailsRequest, IRecurring.RecurringDetailsResult>(
this._listRecurringDetails,
request,
);
}
public disable(request: DisableRequest): Promise<DisableResult> {
return getJsonResponse<DisableRequest, DisableResult>(
public disable(request: IRecurring.DisableRequest): Promise<IRecurring.DisableResult> {
return getJsonResponse<IRecurring.DisableRequest, IRecurring.DisableResult>(
this._disable,
request,
);
}
public scheduleAccountUpdater(request: ScheduleAccountUpdaterRequest): Promise<ScheduleAccountUpdaterResult> {
return getJsonResponse<ScheduleAccountUpdaterRequest, ScheduleAccountUpdaterResult>(
this._scheduleAccountUpdater,
request,
);
}
public notifyShopper(request: NotifyShopperRequest): Promise<NotifyShopperResult> {
return getJsonResponse<NotifyShopperRequest, NotifyShopperResult>(
this._notifyShopper,
request
);
}
}
export default Recurring;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
@@ -22,7 +24,7 @@ import Service from "../service";
import HttpClientException from "../httpClient/httpClientException";
import ApiException from "./exception/apiException";
import ClientInterface from "../httpClient/clientInterface";
import { IRequest } from "../typings/requestOptions";
import {IRequest} from "../typings/requestOptions";
abstract class Resource {
protected endpoint: string;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -1,33 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import Client from "../../../client";
import Service from "../../../service";
import Resource from "../../resource";
class Orders extends Resource {
public constructor(service: Service) {
super(
service,
`${service.client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}/orders`,
);
}
}
export default Orders;

View File

@@ -1,33 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import Client from "../../../client";
import Service from "../../../service";
import Resource from "../../resource";
class OrdersCancel extends Resource {
public constructor(service: Service) {
super(
service,
`${service.client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}/orders/cancel`,
);
}
}
export default OrdersCancel;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -1,40 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import Client from "../../../client";
import Service from "../../../service";
import Resource from "../../resource";
class PaymentLinksId extends Resource {
static _id: string;
public constructor(service: Service) {
super(
service,
`${service.client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}/paymentLinks`,
);
}
public set id(id: string) {
PaymentLinksId._id = id;
this.endpoint = `${this.endpoint}/${PaymentLinksId._id}`;
}
}
export default PaymentLinksId;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -1,33 +0,0 @@
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
import Client from "../../../client";
import Service from "../../../service";
import Resource from "../../resource";
class PaymentMethodsBalance extends Resource {
public constructor(service: Service) {
super(
service,
`${service.client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}/paymentMethods/balance`,
);
}
}
export default PaymentMethodsBalance;

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

View File

@@ -11,8 +11,10 @@
* ######
* #############
* ############
*
* Adyen NodeJS API Library
* Copyright (c) 2020 Adyen B.V.
*
* Copyright (c) 2019 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/

Some files were not shown because too many files have changed in this diff Show More