Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
praveenkumarct authored and leungkinghin-ct committed Feb 14, 2024
0 parents commit 9cb9257
Show file tree
Hide file tree
Showing 70 changed files with 14,796 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .github/dependabot.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/processor"
schedule:
interval: "daily"
open-pull-requests-limit: 10
- package-ecosystem: "npm"
directory: "/enabler"
schedule:
interval: "daily"
open-pull-requests-limit: 10
44 changes: 44 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: CI

on: [push]

jobs:
build-enabler:
name: Build the application for enabler
runs-on: ubuntu-latest
env:
CTP_REGION: ${{ secrets.CTP_REGION }}
defaults:
run:
working-directory: enabler
steps:
- name: Checkout
uses: actions/checkout@v3

- name: Use Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: '16.x'

- name: Install modules
run: npm ci

build-processor:
name: Build the application for processor
runs-on: ubuntu-latest
env:
CTP_REGION: ${{ secrets.CTP_REGION }}
defaults:
run:
working-directory: processor
steps:
- name: Checkout
uses: actions/checkout@v3

- name: Use Node.js 18.x
uses: actions/setup-node@v3
with:
node-version: '18.x'

- name: Install modules
run: npm ci
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Code Editor directories and files
.idea
.env
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 commercetools

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# connect-payment-integration-template
This repository provides a [connect](https://docs.commercetools.com/connect) template for payment integration connector. This boilerplate code acts as a starting point for integration with external payment service provider.

## Template Features
- Typescript language supported.
- Uses Fastify as web server framework.
- Uses [commercetools SDK](https://docs.commercetools.com/sdk/js-sdk-getting-started) for the commercetools-specific communication.
- Uses [connect payment SDK](https://github.com/commercetools/connect-payments-sdk) to manage request context, sessions and JWT authentication.
- Includes local development utilities in npm commands to build, start, test, lint & prettify code.

## Prerequisite
#### 1. commercetools composable commerce API client
Users are expected to create API client responsible for payment management in composable commerce project. Details of the API client are taken as input as environment variables/ configuration for connect such as `CTP_PROJECT_KEY` , `CTP_CLIENT_ID`, `CTP_CLIENT_SECRET`, `CTP_SCOPE`, `CTP_REGION`. For details, please read [Deployment Configuration](./README.md#deployment-configuration).
In addition, please make sure the API client should have enough scope to be able to manage payment. For details, please refer to [Running Application](./processor/README.md#running-application)

#### 2. various URLs from commercetools composable commerce
Various URLs from commercetools platform are required to be configured so that the connect application can handle session and authentication process for endpoints.
Their values are taken as input as environment variables/ configuration for connect with variable names `CTP_API_URL`, `CTP_AUTH_URL` and `CTP_SESSION_URL`.

## Getting started
The template contains two modules :
- Enabler: Acts as a wrapper implementation in which frontend components from PSPs embedded. It gives control to checkout product on when and how to load the connector frontend based on business configuration. In cases connector is used directly and not through Checkout product, the connector library can be loaded directly on frontend than the PSP one.
- Processor : Acts as backend services which is middleware to 3rd party PSPs to be responsible for managing transactions with PSPs and updating payment entity in composable commerce. `connect-payment-sdk` will be offered to be used in connector to manage request context, sessions and other tools necessary to transact.

Regarding the development of processor module, please refer to the following documentations:
- [Development of Processor](./processor/README.md)

#### 1. Develop your specific needs
To proceed payment operations via external PSPs, users need to extend this connector with the following task
- API communication: Implementation to communicate between this connector application and the external system using libraries provided by PSPs. Please remember that the payment requests might not be sent to PSPs successfully in a single attempt. It should have needed retry and recovery mechanism.

#### 2. Register as connector in commercetools Connect
Follow guidelines [here](https://docs.commercetools.com/connect/getting-started) to register the connector for public/private use.

## Deployment Configuration
In order to deploy your customized connector application on commercetools Connect, it needs to be published. For details, please refer to [documentation about commercetools Connect](https://docs.commercetools.com/connect/concepts)
In addition, in order to support connect, the tax integration connector template has a folder structure as listed below
```
├── enabler
│ ├── src
│ ├── test
│ └── package.json
├── processor
│ ├── src
│ ├── test
│ └── package.json
└── connect.yaml
```

Connect deployment configuration is specified in `connect.yaml` which is required information needed for publishing of the application. Following is the deployment configuration used by full ingestion and incremental updater modules
```
deployAs:
- name: processor
applicationType: service
endpoint: /
configuration:
securedConfiguration:
- key: CTP_PROJECT_KEY
description: Commercetools project key
- key: CTP_CLIENT_ID
description: Commercetools client ID
- key: CTP_CLIENT_SECRET
description: Commercetools client secret
- key: CTP_SCOPE
description: Commercetools client scope
- key: CTP_REGION
description: Region of Commercetools project
- key: CTP_AUTH_URL
description: Commercetools Auth URL
- key: CTP_API_URL
description: Commercetools API URL
- key: CTP_SESSION_URL
description: Session API URL
- name: enabler
applicationType: service
endpoint: /enabler
configuration:
securedConfiguration:
- key: CTP_REGION
description: Region of Commercetools project
```

Here you can see the details about various variables in configuration
- CTP_PROJECT_KEY: The key of commercetools composable commerce project.
- CTP_CLIENT_ID: The client ID of your commercetools composable commerce user account. It is used in commercetools client to communicate with commercetools composable commerce via SDK.
- CTP_CLIENT_SECRET: The client secret of commercetools composable commerce user account. It is used in commercetools client to communicate with commercetools composable commerce via SDK.
- CTP_SCOPE: The scope constrains the endpoints to which the commercetools client has access, as well as the read/write access right to an endpoint.
- CTP_REGION: As the commercetools composable commerce APIs are provided in six different region, it defines the region which your commercetools composable commerce user account belongs to.
- CTP_AUTH_URL: The URL for authentication in commercetools platform. It is used to generate OAuth 2.0 token which is required in every API call to commercetools composable commerce. The default value is `https://auth.europe-west1.gcp.commercetools.com`. For details, please refer to documentation [here](https://docs.commercetools.com/tutorials/api-tutorial#authentication).
- CTP_API_URL: The URL for commercetools composable commerce API. Default value is `https://api.europe-west1.gcp.commercetools.com`.
- CTP_SESSION_URL: The URL for session creation in commercetools platform. Connectors relies on the session created to be able to share information between enabler and processor. The default value is `https://session-dev.europe-west1.gcp.commercetools.com`.
29 changes: 29 additions & 0 deletions connect.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
deployAs:
- name: processor
applicationType: service
endpoint: /
configuration:
securedConfiguration:
- key: CTP_PROJECT_KEY
description: Commercetools project key
- key: CTP_CLIENT_ID
description: Commercetools client ID
- key: CTP_CLIENT_SECRET
description: Commercetools client secret
- key: CTP_SCOPE
description: Commercetools client scope
- key: CTP_REGION
description: Region of Commercetools project
- key: CTP_AUTH_URL
description: Commercetools Auth URL
- key: CTP_API_URL
description: Commercetools API URL
- key: CTP_SESSION_URL
description: Session API URL
- name: enabler
applicationType: service
endpoint: /
configuration:
securedConfiguration:
- key: CTP_REGION
description: Region of Commercetools project
7 changes: 7 additions & 0 deletions enabler/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
VITE_CTP_AUTH_URL=https://auth.[region].commercetools.com
VITE_CTP_API_URL=https://api.[region].commercetools.com
VITE_CTP_SESSION_URL=https://session.[region].commercetools.com
VITE_CTP_CLIENT_ID=[composable-commerce-client-id]
VITE_CTP_CLIENT_SECRET=[composable-commerce-client-secret]
VITE_CTP_PROJECT_KEY=[composable-commerce-project-key]
VITE_PROCESSOR_URL=http://localhost:8080
24 changes: 24 additions & 0 deletions enabler/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.env
21 changes: 21 additions & 0 deletions enabler/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Payment Integration Enabler
This module provides an application based on [commercetools Connect](https://docs.commercetools.com/connect), which acts a wrapper implementation to cover frontend components provided by Payment Service Providers (PSPs)

PSPs provide libraries that can be used on client side to load on browser or other user agent which securely load DOM elements for payment methods and/or payment fields inputs. These libraries take control on saving PAN data of customer and reduce PCI scopes of the seller implementation. Now, with the usage of `enabler`, it allows the control to checkout product on when and how to load the `enabler` as connector UI based on business configuration. In cases connector is used directly and not through Checkout product, this connector UI can be loaded directly on frontend than the libraries provided by PSPs.


## Getting Started
Please run following npm commands under `enabler` folder for development work in local environment.

#### Install dependencies
```
$ npm install
```
#### Build the application in local environment. NodeJS source codes are then generated under dist folder
```
$ npm run build
```
#### Build development site in local environment. The location of the site is http://127.0.0.1:3000/
```
$ npm run dev
```
1 change: 1 addition & 0 deletions enabler/decs.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module '*.scss';
71 changes: 71 additions & 0 deletions enabler/dev-utils/session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const projectKey = __VITE_CTP_PROJECT_KEY__;

const fetchAdminToken = async () => {
const myHeaders = new Headers();

myHeaders.append('Authorization', `Basic ${btoa(`${__VITE_CTP_CLIENT_ID__}:${__VITE_CTP_CLIENT_SECRET__}`)}`);
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');

var urlencoded = new URLSearchParams();
urlencoded.append('grant_type', 'client_credentials');
//urlencoded.append('scope', __VITE_ADMIN_SCOPE__);

const response = await fetch(`${__VITE_CTP_AUTH_URL__}/oauth/token`, {
body: urlencoded,
headers: myHeaders,
method: 'POST',
redirect: 'follow',
});

const token = await response.json();

if (response.status !== 200) {
console.log({
title: 'Token fetch failed',
message: `Error ${response.status} while fetching token`,
});
return;
} else {
console.log({
title: 'Token fetched',
message: `Token fetched: ${token.access_token}`,
});
}
console.log("Token fetched:", token)
return token.access_token;
}

const getSessionId = async(cartId) => {
const accessToken = await fetchAdminToken();

const sessionMetadata = {
allowedPaymentMethods: ['card'], // add here your allowed methods for development purposes
};

const url = `${__VITE_CTP_SESSION_URL__}/${projectKey}/sessions`

const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
cart: {
cartRef: {
id: cartId,
}
},
metadata: sessionMetadata,
}),
});
const data = await res.json();

if (!res.ok) {
console.error("Not able to create session:", url, data)
throw new Error("Not able to create session")
}

console.log("Session created:", data)
return data.id;
}
Loading

0 comments on commit 9cb9257

Please sign in to comment.