@smartsoft001/paypal 1.1.90 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "../../../.eslintrc.json",
3
+ "ignorePatterns": ["!**/*"],
4
+ "rules": {
5
+ "import/order": "off"
6
+ },
7
+ "overrides": [
8
+ {
9
+ "files": ["*.json"],
10
+ "parser": "jsonc-eslint-parser"
11
+ }
12
+ ]
13
+ }
package/README.md CHANGED
@@ -1,7 +1,32 @@
1
- # shared-paypal
1
+ # 📦 @smartsoft001/paypal
2
2
 
3
- This library was generated with [Nx](https://nx.dev).
3
+ ![npm](https://img.shields.io/npm/v/@smartsoft001/paypal) ![downloads](https://img.shields.io/npm/dm/@smartsoft001/paypal)
4
4
 
5
- ## Running unit tests
5
+ ## 🚀 Usage
6
6
 
7
- Run `ng test shared-paypal` to execute the unit tests via [Jest](https://jestjs.io).
7
+ `npm i @smartsoft001/paypal`
8
+
9
+ ## 🛠️ Services & Methods
10
+
11
+ ### PaypalService
12
+
13
+ Methods:
14
+
15
+ <table>
16
+ <tr>
17
+ <td>create</td>
18
+ <td>Initiates a PayPal payment</td>
19
+ </tr>
20
+ <tr>
21
+ <td>confirm</td>
22
+ <td>Executes a previously created PayPal payment after user approval</td>
23
+ </tr>
24
+ <tr>
25
+ <td>getStatus</td>
26
+ <td>Fetches the current status of a PayPal transaction</td>
27
+ </tr>
28
+ <tr>
29
+ <td>refund</td>
30
+ <td>Processes a refund for a completed PayPal transaction</td>
31
+ </tr>
32
+ </table>
package/jest.config.ts ADDED
@@ -0,0 +1,27 @@
1
+ /* eslint-disable */
2
+ export default {
3
+ displayName: 'shared-paypal',
4
+ globals: {},
5
+ testEnvironment: 'node',
6
+ transform: {
7
+ '^.+\\.[tj]sx?$': [
8
+ 'ts-jest',
9
+ {
10
+ tsConfig: '<rootDir>/tsconfig.spec.json',
11
+ },
12
+ ],
13
+ },
14
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
15
+ coverageDirectory: '../../../coverage/libs/shared/paypal',
16
+ preset: '../../../jest.preset.js',
17
+ /* TODO: Update to latest Jest snapshotFormat
18
+ * By default Nx has kept the older style of Jest Snapshot formats
19
+ * to prevent breaking of any existing tests with snapshots.
20
+ * It's recommend you update to the latest format.
21
+ * You can do this by removing snapshotFormat property
22
+ * and running tests with --update-snapshot flag.
23
+ * Example: From within the project directory, run "nx test --update-snapshot"
24
+ * More info: https://jestjs.io/docs/upgrading-to-jest29#snapshot-format
25
+ */
26
+ snapshotFormat: { escapeString: true, printBasicPrototype: true },
27
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@smartsoft001/paypal",
3
- "version": "1.1.90",
4
- "description": "This library was generated with [Nx](https://nx.dev).",
3
+ "version": "1.2.0",
4
+ "description": "Utils for paypal",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/emiljuchnikowski/smartsoft.git"
@@ -11,32 +11,5 @@
11
11
  "bugs": {
12
12
  "url": "https://github.com/emiljuchnikowski/smartsoft/issues"
13
13
  },
14
- "homepage": "https://github.com/emiljuchnikowski/smartsoft#readme",
15
- "dependencies": {
16
- "@angular/common": "16.1.3",
17
- "@angular/core": "16.1.3",
18
- "@angular/platform-browser-dynamic": "16.1.3",
19
- "@nestjs/axios": "3.0.0",
20
- "@nestjs/common": "^10.0.5",
21
- "@nestjs/core": "^10.0.5",
22
- "flatted": "^3.2.4",
23
- "guid-typescript": "1.0.9",
24
- "lodash": "^4.17.20",
25
- "md5": "2.3.0",
26
- "paypal-rest-sdk": "^1.8.1",
27
- "reflect-metadata": "0.1.13",
28
- "rxjs": "7.8.1",
29
- "typeorm": "0.3.17"
30
- },
31
- "peerDependencies": {
32
- "@smartsoft001/domain-core": "1.1.90",
33
- "@smartsoft001/models": "1.1.90",
34
- "@smartsoft001/trans-domain": "1.1.90",
35
- "@smartsoft001/users": "1.1.90",
36
- "@smartsoft001/utils": "1.1.90",
37
- "util": "0.12.5",
38
- "tslib": "2.5.3"
39
- },
40
- "main": "./src/index.js",
41
- "types": "./src/index.d.ts"
14
+ "homepage": "https://github.com/emiljuchnikowski/smartsoft#readme"
42
15
  }
package/project.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "shared-paypal",
3
+ "$schema": "../../../node_modules/nx/schemas/project-schema.json",
4
+ "sourceRoot": "packages/shared/paypal/src",
5
+ "projectType": "library",
6
+ "generators": {},
7
+ "targets": {
8
+ "lint": {
9
+ "executor": "@nx/eslint:lint",
10
+ "outputs": ["{options.outputFile}"],
11
+ "options": {
12
+ "lintFilePatterns": [
13
+ "packages/shared/paypal/**/*.{ts,tsx,js,jsx}",
14
+ "packages/shared/paypal/package.json"
15
+ ]
16
+ }
17
+ },
18
+ "test": {
19
+ "executor": "@nx/jest:jest",
20
+ "options": {
21
+ "jestConfig": "packages/shared/paypal/jest.config.ts",
22
+ "passWithNoTests": true
23
+ },
24
+ "outputs": ["{workspaceRoot}/coverage/packages/shared/paypal"]
25
+ },
26
+ "build": {
27
+ "executor": "@nx/esbuild:esbuild",
28
+ "outputs": ["{options.outputPath}"],
29
+ "options": {
30
+ "outputPath": "dist/packages/shared/paypal",
31
+ "tsConfig": "packages/shared/paypal/tsconfig.lib.json",
32
+ "packageJson": "packages/shared/paypal/package.json",
33
+ "main": "packages/shared/paypal/src/index.ts",
34
+ "assets": ["packages/shared/paypal/*.md"]
35
+ }
36
+ },
37
+ "deploy": {
38
+ "executor": "ngx-deploy-npm:deploy",
39
+ "options": {
40
+ "access": "public",
41
+ "distFolderPath": "dist/packages/shared/paypal"
42
+ },
43
+ "dependsOn": ["build"]
44
+ }
45
+ },
46
+ "tags": ["scope:shared", "type:util"]
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './lib/paypal.config';
2
+ export * from './lib/paypal.service';
@@ -0,0 +1,17 @@
1
+ export class PaypalConfig {
2
+ constructor(
3
+ public clientId: string,
4
+ public clientSecret: string,
5
+ public currencyCode: string,
6
+ public returnUrl: string,
7
+ public apiUrl: string,
8
+ public cancelUrl: string,
9
+ public test?: boolean,
10
+ ) {}
11
+ }
12
+
13
+ export const PAYPAL_CONFIG_PROVIDER = 'PAYPAL_CONFIG_PROVIDER';
14
+
15
+ export abstract class IPaypalConfigProvider {
16
+ abstract get(data: any): Promise<PaypalConfig>;
17
+ }
@@ -0,0 +1,191 @@
1
+ import { Test, TestingModule } from '@nestjs/testing';
2
+ import { HttpService } from '@nestjs/axios';
3
+ import { ModuleRef } from '@nestjs/core';
4
+ import { Trans } from '@smartsoft001/trans-domain';
5
+
6
+ import { PaypalService } from './paypal.service';
7
+ import { PaypalConfig } from './paypal.config';
8
+
9
+ // Mock the module before importing it
10
+ jest.mock('paypal-rest-sdk', () => ({
11
+ payment: {
12
+ create: jest.fn(),
13
+ execute: jest.fn(),
14
+ get: jest.fn(),
15
+ },
16
+ sale: {
17
+ refund: jest.fn(),
18
+ },
19
+ configure: jest.fn(),
20
+ sdkVersion: '1.8.1',
21
+ userAgent: 'PayPalSDK/PayPal-node-SDK 1.8.1',
22
+ }));
23
+
24
+ //eslint-disable-next-line
25
+ import * as paypal from 'paypal-rest-sdk'; // Needs to be mocked first
26
+
27
+ const mockHttpService = {
28
+ post: jest.fn(),
29
+ get: jest.fn(),
30
+ };
31
+
32
+ const mockModuleRef = {
33
+ get: jest.fn(),
34
+ };
35
+
36
+ const mockPaypalConfig = {
37
+ clientId: 'mock-client-id',
38
+ clientSecret: 'mock-client-secret',
39
+ currencyCode: 'USD',
40
+ apiUrl: 'https://mock.api.url',
41
+ cancelUrl: 'https://mock.cancel.url',
42
+ test: true,
43
+ };
44
+
45
+ describe('paypal: PaypalService', () => {
46
+ let service: PaypalService;
47
+
48
+ beforeEach(async () => {
49
+ const module: TestingModule = await Test.createTestingModule({
50
+ providers: [
51
+ PaypalService,
52
+ { provide: PaypalConfig, useValue: mockPaypalConfig },
53
+ { provide: HttpService, useValue: mockHttpService },
54
+ { provide: ModuleRef, useValue: mockModuleRef },
55
+ ],
56
+ }).compile();
57
+
58
+ service = module.get<PaypalService>(PaypalService);
59
+ });
60
+
61
+ afterEach(() => {
62
+ jest.clearAllMocks();
63
+ });
64
+
65
+ describe('create', () => {
66
+ it('should create a payment and return orderId and redirectUrl', async () => {
67
+ const mockPayment = {
68
+ id: 'test-payment-id',
69
+ links: [{ rel: 'approval_url', href: 'https://approval.url' }],
70
+ };
71
+
72
+ (paypal.payment.create as jest.Mock).mockImplementation(
73
+ (data, config, callback) => {
74
+ callback(null, mockPayment);
75
+ },
76
+ );
77
+
78
+ const result = await service.create({
79
+ id: 'test-id',
80
+ name: 'test-name',
81
+ amount: 1000,
82
+ email: 'test@example.com',
83
+ clientIp: '127.0.0.1',
84
+ data: {},
85
+ });
86
+
87
+ expect(result).toEqual({
88
+ orderId: 'test-payment-id',
89
+ redirectUrl: 'https://approval.url',
90
+ });
91
+ });
92
+ });
93
+
94
+ describe('confirm', () => {
95
+ it('should execute a payment and return the result', async () => {
96
+ const mockPayment = { id: 'test-payment-id', state: 'approved' };
97
+
98
+ (paypal.payment.execute as jest.Mock).mockImplementation(
99
+ (paymentId, data, config, callback) => {
100
+ callback(null, mockPayment);
101
+ },
102
+ );
103
+
104
+ const result = await service.confirm(
105
+ 'test-payer-id',
106
+ 'test-payment-id',
107
+ 10,
108
+ {},
109
+ );
110
+
111
+ expect(result).toEqual(mockPayment);
112
+ });
113
+ });
114
+
115
+ describe('getStatus', () => {
116
+ it('should return the status and data of a payment', async () => {
117
+ const mockPayment = { state: 'COMPLETED' };
118
+
119
+ (paypal.payment.get as jest.Mock).mockImplementation(
120
+ (paymentId, config, callback) => {
121
+ callback(null, mockPayment);
122
+ },
123
+ );
124
+
125
+ const result = await service.getStatus({
126
+ data: {},
127
+ history: [
128
+ {
129
+ status: 'started',
130
+ data: { orderId: 'test-order-id' },
131
+ },
132
+ ],
133
+ } as Trans<any>);
134
+
135
+ expect(result).toEqual({ status: 'completed', data: mockPayment });
136
+ });
137
+ });
138
+
139
+ describe('refund', () => {
140
+ it('should process a refund and return the result', async () => {
141
+ const mockRefund = { id: 'test-refund-id', state: 'completed' };
142
+
143
+ (paypal.sale.refund as jest.Mock).mockImplementation(
144
+ (saleId, data, config, callback) => {
145
+ callback(null, mockRefund);
146
+ },
147
+ );
148
+
149
+ const result = await service.refund(
150
+ {
151
+ amount: 1000,
152
+ data: {},
153
+ history: [
154
+ {
155
+ status: 'completed',
156
+ data: {
157
+ customData: {
158
+ transactions: [
159
+ {
160
+ related_resources: [
161
+ {
162
+ sale: { id: 'test-sale-id' },
163
+ },
164
+ ],
165
+ },
166
+ ],
167
+ },
168
+ },
169
+ },
170
+ ],
171
+ } as Trans<any>,
172
+ 'test comment',
173
+ );
174
+
175
+ expect(result).toEqual(mockRefund);
176
+ });
177
+
178
+ it('should throw an error when transaction ID is not found', async () => {
179
+ await expect(
180
+ service.refund(
181
+ {
182
+ amount: 1000,
183
+ data: {},
184
+ history: [],
185
+ } as unknown as Trans<any>,
186
+ 'test comment',
187
+ ),
188
+ ).rejects.toThrow('Paypal transaction ID not found for refund');
189
+ });
190
+ });
191
+ });
@@ -0,0 +1,265 @@
1
+ import { HttpService } from '@nestjs/axios';
2
+ import { Injectable, Logger } from '@nestjs/common';
3
+ import { ModuleRef } from '@nestjs/core';
4
+ import {
5
+ ITransPaymentSingleService,
6
+ Trans,
7
+ TransStatus,
8
+ } from '@smartsoft001/trans-domain';
9
+ import * as paypal from 'paypal-rest-sdk';
10
+
11
+ import {
12
+ IPaypalConfigProvider,
13
+ PAYPAL_CONFIG_PROVIDER,
14
+ PaypalConfig,
15
+ } from './paypal.config';
16
+
17
+ @Injectable()
18
+ export class PaypalService implements ITransPaymentSingleService {
19
+ constructor(
20
+ private readonly httpService: HttpService,
21
+ private config: PaypalConfig,
22
+ private moduleRef: ModuleRef,
23
+ ) {}
24
+
25
+ async create(obj: {
26
+ id: string;
27
+ name: string;
28
+ amount: number;
29
+ firstName?: string;
30
+ lastName?: string;
31
+ email?: string;
32
+ contactPhone?: string;
33
+ clientIp: string;
34
+ data: any;
35
+ }): Promise<{ orderId: string; redirectUrl: string }> {
36
+ const config = await this.getConfig(obj.data);
37
+
38
+ const data = {
39
+ intent: 'sale',
40
+ payer: {
41
+ payment_method: 'paypal',
42
+ },
43
+ redirect_urls: {
44
+ return_url: config.apiUrl + 'paypal/' + obj.id + '/confirm',
45
+ cancel_url: config.cancelUrl,
46
+ },
47
+ transactions: [
48
+ {
49
+ item_list: {
50
+ items: [
51
+ {
52
+ name: obj.name,
53
+ sku: obj.id,
54
+ price: obj.amount / 100,
55
+ currency: config.currencyCode,
56
+ quantity: 1,
57
+ },
58
+ ],
59
+ },
60
+ amount: {
61
+ currency: config.currencyCode,
62
+ total: obj.amount / 100,
63
+ },
64
+ description: obj.name,
65
+ },
66
+ ],
67
+ };
68
+
69
+ const result: { id: any; links: any[] } = await new Promise((res, rej) => {
70
+ paypal.payment.create(
71
+ data as any,
72
+ this.getEnv(config) as any,
73
+ (error: any, payment: any) => {
74
+ if (error) {
75
+ rej(error);
76
+ } else {
77
+ res(payment);
78
+ }
79
+ },
80
+ );
81
+ });
82
+
83
+ return {
84
+ redirectUrl: result.links.find(
85
+ (l: { rel: string }) => l.rel === 'approval_url',
86
+ ).href,
87
+ orderId: result.id,
88
+ };
89
+ }
90
+
91
+ async confirm(
92
+ payerId: any,
93
+ paymentId: any,
94
+ amount: number,
95
+ externalData: any,
96
+ ): Promise<any> {
97
+ const config = await this.getConfig(externalData);
98
+
99
+ const data = {
100
+ payer_id: payerId,
101
+ transactions: [
102
+ {
103
+ amount: {
104
+ currency: config.currencyCode,
105
+ total: amount,
106
+ },
107
+ },
108
+ ],
109
+ };
110
+
111
+ return await new Promise<void>((res, rej) => {
112
+ paypal.payment.execute(
113
+ paymentId,
114
+ data,
115
+ this.getEnv(config) as any,
116
+ (error: any, payment: any) => {
117
+ if (error) {
118
+ rej(error);
119
+ } else {
120
+ res(payment);
121
+ }
122
+ },
123
+ );
124
+ });
125
+ }
126
+
127
+ async getStatus<T>(
128
+ trans: Trans<T>,
129
+ ): Promise<{ status: TransStatus; data: any }> {
130
+ const orderId = this.getOrderId(trans) ?? '';
131
+ const config = await this.getConfig(trans.data);
132
+
133
+ const payment: { state: string } = await new Promise((res, rej) => {
134
+ paypal.payment.get(
135
+ orderId,
136
+ this.getEnv(config) as any,
137
+ (error: any, result: any) => {
138
+ if (error) {
139
+ rej(error);
140
+ } else {
141
+ res(result);
142
+ }
143
+ },
144
+ );
145
+ });
146
+
147
+ return {
148
+ status: this.getStatusFromExternal(payment.state),
149
+ data: payment,
150
+ };
151
+ }
152
+
153
+ async refund(trans: Trans<any>, comment: string): Promise<any> {
154
+ const orderId = this.getOrderId(trans);
155
+ const config = await this.getConfig(trans.data);
156
+ const transactionId = this.getTransactionId(trans);
157
+
158
+ if (!transactionId) {
159
+ throw new Error('Paypal transaction ID not found for refund');
160
+ }
161
+
162
+ const refundData = {
163
+ amount: {
164
+ total: (trans.amount / 100).toString(),
165
+ currency: config.currencyCode,
166
+ },
167
+ description: comment,
168
+ };
169
+
170
+ return new Promise((resolve, reject) => {
171
+ paypal.sale.refund(
172
+ transactionId,
173
+ refundData,
174
+ this.getEnv(config) as any,
175
+ (error: any, refund: any) => {
176
+ if (error) {
177
+ reject(error);
178
+ } else {
179
+ resolve(refund);
180
+ }
181
+ },
182
+ );
183
+ });
184
+ }
185
+
186
+ private getOrderId(trans: Trans<any>): string | null {
187
+ const historyItem = trans.history.find((x) => x.status === 'started');
188
+
189
+ if (!historyItem) {
190
+ console.warn('Transaction without start status');
191
+ return null;
192
+ }
193
+
194
+ return historyItem.data.orderId;
195
+ }
196
+
197
+ private getStatusFromExternal(status: string): any {
198
+ status = status.toUpperCase();
199
+
200
+ switch (status) {
201
+ case 'COMPLETED':
202
+ return 'completed';
203
+ case 'VOIDED':
204
+ return 'canceled';
205
+ case 'CREATED':
206
+ return 'pending';
207
+ case 'SAVED':
208
+ return 'pending';
209
+ case 'APPROVED':
210
+ return 'completed';
211
+ default:
212
+ return status;
213
+ }
214
+ }
215
+
216
+ private async getConfig(data: any): Promise<PaypalConfig> {
217
+ try {
218
+ const provider: IPaypalConfigProvider = this.moduleRef.get(
219
+ PAYPAL_CONFIG_PROVIDER,
220
+ { strict: false },
221
+ );
222
+ return await provider.get(data);
223
+ } catch (e) {
224
+ Logger.warn('PayPal config provider not found', PaypalService.name);
225
+ }
226
+
227
+ return this.config;
228
+ }
229
+
230
+ private getEnv(config: PaypalConfig): {
231
+ mode: any;
232
+ client_id: any;
233
+ client_secret: any;
234
+ } {
235
+ return {
236
+ mode: config.test ? 'sandbox' : 'live',
237
+ client_id: config.clientId,
238
+ client_secret: config.clientSecret,
239
+ };
240
+ }
241
+
242
+ private getApiUrl(config: PaypalConfig): string {
243
+ return config.test
244
+ ? 'https://api-m.sandbox.paypal.com/'
245
+ : 'https://api-m.paypal.com/';
246
+ }
247
+
248
+ private getTransactionId(trans: Trans<any>): string {
249
+ const historyItem = trans.history.find(
250
+ (i) =>
251
+ i.status === 'completed' &&
252
+ i.data &&
253
+ i.data.customData &&
254
+ i.data.customData.transactions &&
255
+ i.data.customData.transactions.length &&
256
+ i.data.customData.transactions[0].related_resources &&
257
+ i.data.customData.transactions[0].related_resources.length &&
258
+ i.data.customData.transactions[0].related_resources[0].sale,
259
+ );
260
+
261
+ return historyItem
262
+ ? historyItem.data.customData.transactions[0].related_resources[0].sale.id
263
+ : null;
264
+ }
265
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "files": [],
4
+ "include": [],
5
+ "references": [
6
+ {
7
+ "path": "./tsconfig.lib.json"
8
+ },
9
+ {
10
+ "path": "./tsconfig.spec.json"
11
+ }
12
+ ]
13
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../../dist/out-tsc",
5
+ "declaration": true,
6
+ "types": ["node"]
7
+ },
8
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
9
+ "include": ["src/**/*.ts"]
10
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../../dist/out-tsc",
5
+ "module": "commonjs",
6
+ "types": ["jest", "node"]
7
+ },
8
+ "include": [
9
+ "**/*.spec.ts",
10
+ "**/*.test.ts",
11
+ "**/*.spec.tsx",
12
+ "**/*.test.tsx",
13
+ "**/*.spec.js",
14
+ "**/*.test.js",
15
+ "**/*.spec.jsx",
16
+ "**/*.test.jsx",
17
+ "**/*.d.ts",
18
+ "jest.config.ts"
19
+ ]
20
+ }
package/src/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from "./lib/paypal.config";
2
- export * from "./lib/paypal.service";
package/src/index.js DELETED
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./lib/paypal.config"), exports);
5
- tslib_1.__exportStar(require("./lib/paypal.service"), exports);
6
- //# sourceMappingURL=index.js.map
package/src/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../libs/shared/paypal/src/index.ts"],"names":[],"mappings":";;;AAAA,8DAAoC;AACpC,+DAAqC"}
@@ -1,13 +0,0 @@
1
- export declare class PaypalConfig {
2
- clientId: string;
3
- clientSecret: string;
4
- currencyCode: string;
5
- returnUrl: string;
6
- apiUrl: string;
7
- cancelUrl: string;
8
- test?: boolean;
9
- }
10
- export declare const PAYPAL_CONFIG_PROVIDER = "PAYPAL_CONFIG_PROVIDER";
11
- export declare abstract class IPaypalConfigProvider {
12
- abstract get(data: any): Promise<PaypalConfig>;
13
- }
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IPaypalConfigProvider = exports.PAYPAL_CONFIG_PROVIDER = exports.PaypalConfig = void 0;
4
- class PaypalConfig {
5
- }
6
- exports.PaypalConfig = PaypalConfig;
7
- exports.PAYPAL_CONFIG_PROVIDER = "PAYPAL_CONFIG_PROVIDER";
8
- class IPaypalConfigProvider {
9
- }
10
- exports.IPaypalConfigProvider = IPaypalConfigProvider;
11
- //# sourceMappingURL=paypal.config.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"paypal.config.js","sourceRoot":"","sources":["../../../../../../libs/shared/paypal/src/lib/paypal.config.ts"],"names":[],"mappings":";;;AAAA,MAAa,YAAY;CAQxB;AARD,oCAQC;AAEY,QAAA,sBAAsB,GAAG,wBAAwB,CAAC;AAE/D,MAAsB,qBAAqB;CAE1C;AAFD,sDAEC"}
@@ -1,36 +0,0 @@
1
- import { ModuleRef } from "@nestjs/core";
2
- import { HttpService } from "@nestjs/axios";
3
- import { ITransPaymentSingleService, Trans, TransStatus } from "@smartsoft001/trans-domain";
4
- import { PaypalConfig } from "./paypal.config";
5
- export declare class PaypalService implements ITransPaymentSingleService {
6
- private readonly httpService;
7
- private config;
8
- private moduleRef;
9
- constructor(httpService: HttpService, config: PaypalConfig, moduleRef: ModuleRef);
10
- create(obj: {
11
- id: string;
12
- name: string;
13
- amount: number;
14
- firstName?: string;
15
- lastName?: string;
16
- email?: string;
17
- contactPhone?: string;
18
- clientIp: string;
19
- data: any;
20
- }): Promise<{
21
- orderId: string;
22
- redirectUrl: string;
23
- }>;
24
- confirm(payerId: any, paymentId: any, amount: number, externalData: any): Promise<any>;
25
- getStatus<T>(trans: Trans<T>): Promise<{
26
- status: TransStatus;
27
- data: any;
28
- }>;
29
- refund(trans: Trans<any>, comment: string): Promise<any>;
30
- private getOrderId;
31
- private getStatusFromExternal;
32
- private getConfig;
33
- private getEnv;
34
- private getApiUrl;
35
- private getTransactionId;
36
- }
@@ -1,196 +0,0 @@
1
- "use strict";
2
- var PaypalService_1;
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.PaypalService = void 0;
5
- const tslib_1 = require("tslib");
6
- const common_1 = require("@nestjs/common");
7
- const paypal = require("paypal-rest-sdk");
8
- const core_1 = require("@nestjs/core");
9
- const axios_1 = require("@nestjs/axios");
10
- const paypal_config_1 = require("./paypal.config");
11
- let PaypalService = exports.PaypalService = PaypalService_1 = class PaypalService {
12
- constructor(httpService, config, moduleRef) {
13
- this.httpService = httpService;
14
- this.config = config;
15
- this.moduleRef = moduleRef;
16
- }
17
- async create(obj) {
18
- const config = await this.getConfig(obj.data);
19
- const data = {
20
- intent: "sale",
21
- payer: {
22
- payment_method: "paypal",
23
- },
24
- redirect_urls: {
25
- return_url: config.apiUrl + "paypal/" + obj.id + "/confirm",
26
- cancel_url: config.cancelUrl,
27
- },
28
- transactions: [
29
- {
30
- item_list: {
31
- items: [
32
- {
33
- name: obj.name,
34
- sku: obj.id,
35
- price: obj.amount / 100,
36
- currency: config.currencyCode,
37
- quantity: 1,
38
- },
39
- ],
40
- },
41
- amount: {
42
- currency: config.currencyCode,
43
- total: obj.amount / 100,
44
- },
45
- description: obj.name,
46
- },
47
- ],
48
- };
49
- const result = await new Promise((res, rej) => {
50
- paypal.payment.create(data, this.getEnv(config), function (error, payment) {
51
- if (error) {
52
- rej(error);
53
- }
54
- else {
55
- res(payment);
56
- }
57
- });
58
- });
59
- return {
60
- redirectUrl: result.links.find((l) => l.rel === "approval_url").href,
61
- orderId: result.id,
62
- };
63
- }
64
- async confirm(payerId, paymentId, amount, externalData) {
65
- const config = await this.getConfig(externalData);
66
- const data = {
67
- payer_id: payerId,
68
- transactions: [
69
- {
70
- amount: {
71
- currency: config.currencyCode,
72
- total: amount,
73
- },
74
- },
75
- ],
76
- };
77
- return await new Promise((res, rej) => {
78
- paypal.payment.execute(paymentId, data, this.getEnv(config), (error, payment) => {
79
- if (error) {
80
- rej(error);
81
- }
82
- else {
83
- res(payment);
84
- }
85
- });
86
- });
87
- }
88
- async getStatus(trans) {
89
- const orderId = this.getOrderId(trans);
90
- const config = await this.getConfig(trans.data);
91
- const payment = await new Promise((res, rej) => {
92
- paypal.payment.get(orderId, this.getEnv(config), (error, result) => {
93
- if (error) {
94
- rej(error);
95
- }
96
- else {
97
- res(result);
98
- }
99
- });
100
- });
101
- return {
102
- status: this.getStatusFromExternal(payment.state),
103
- data: payment,
104
- };
105
- }
106
- refund(trans, comment) {
107
- return Promise.reject('Revolut not support');
108
- // const orderId = this.getOrderId(trans);
109
- // const config = await this.getConfig(trans.data);
110
- //
111
- // const token = await new Promise((res, rej) => {
112
- // paypal.generateToken(this.getEnv(config), (error, result) => {
113
- // if (error) {
114
- // rej(error);
115
- // } else {
116
- // res(result);
117
- // }
118
- // });
119
- // });
120
- //
121
- // const { data } = await this.httpService.post(
122
- // `${ this.getApiUrl(config) }v1/payments/sale/${ this.getTransactionId(trans) }/refund`, {},
123
- // {
124
- // headers: {
125
- // "Content-Type": "application/json",
126
- // Authorization: token,
127
- // "X-Requested-With": "XMLHttpRequest",
128
- // },
129
- // maxRedirects: 0,
130
- // }).toPromise();
131
- //
132
- // return data;
133
- }
134
- getOrderId(trans) {
135
- const historyItem = trans.history.find((x) => x.status === "started");
136
- if (!historyItem) {
137
- console.warn("Transaction without start status");
138
- return null;
139
- }
140
- return historyItem.data.orderId;
141
- }
142
- getStatusFromExternal(status) {
143
- status = status.toUpperCase();
144
- switch (status) {
145
- case "COMPLETED":
146
- return "completed";
147
- case "VOIDED":
148
- return "canceled";
149
- case "CREATED":
150
- return "pending";
151
- case "SAVED":
152
- return "pending";
153
- case "APPROVED":
154
- return "completed";
155
- default:
156
- return status;
157
- }
158
- }
159
- async getConfig(data) {
160
- try {
161
- const provider = this.moduleRef.get(paypal_config_1.PAYPAL_CONFIG_PROVIDER, { strict: false });
162
- return await provider.get(data);
163
- }
164
- catch (e) {
165
- common_1.Logger.warn('PayPal config provider not found', PaypalService_1.name);
166
- }
167
- return this.config;
168
- }
169
- getEnv(config) {
170
- return {
171
- mode: config.test ? "sandbox" : "live",
172
- client_id: config.clientId,
173
- client_secret: config.clientSecret,
174
- };
175
- }
176
- getApiUrl(config) {
177
- return config.test ? 'https://api-m.sandbox.paypal.com/' : 'https://api-m.paypal.com/';
178
- }
179
- getTransactionId(trans) {
180
- const historyItem = trans.history.find((i) => i.status === "completed"
181
- && i.data && i.data.customData
182
- && i.data.customData.transactions
183
- && i.data.customData.transactions.length
184
- && i.data.customData.transactions[0].related_resources
185
- && i.data.customData.transactions[0].related_resources.length
186
- && i.data.customData.transactions[0].related_resources[0].sale);
187
- return historyItem ? historyItem.data.customData.transactions[0].related_resources[0].sale.id : null;
188
- }
189
- };
190
- exports.PaypalService = PaypalService = PaypalService_1 = tslib_1.__decorate([
191
- (0, common_1.Injectable)(),
192
- tslib_1.__metadata("design:paramtypes", [axios_1.HttpService,
193
- paypal_config_1.PaypalConfig,
194
- core_1.ModuleRef])
195
- ], PaypalService);
196
- //# sourceMappingURL=paypal.service.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"paypal.service.js","sourceRoot":"","sources":["../../../../../../libs/shared/paypal/src/lib/paypal.service.ts"],"names":[],"mappings":";;;;;AAAA,2CAAoD;AACpD,0CAA0C;AAC1C,uCAAuC;AACvC,yCAA0C;AAQ1C,mDAIyB;AAGlB,IAAM,aAAa,6CAAnB,MAAM,aAAa;IACxB,YACmB,WAAwB,EACjC,MAAoB,EACpB,SAAoB;QAFX,gBAAW,GAAX,WAAW,CAAa;QACjC,WAAM,GAAN,MAAM,CAAc;QACpB,cAAS,GAAT,SAAS,CAAW;IAC1B,CAAC;IAEL,KAAK,CAAC,MAAM,CAAC,GAUZ;QACC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAE9C,MAAM,IAAI,GAAG;YACX,MAAM,EAAE,MAAM;YACd,KAAK,EAAE;gBACL,cAAc,EAAE,QAAQ;aACzB;YACD,aAAa,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AAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,IAAI,CACjE,CAAC;QAEF,OAAO,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACvG,CAAC;CACF,CAAA;wBAxNY,aAAa;IADzB,IAAA,mBAAU,GAAE;6CAGqB,mBAAW;QACzB,4BAAY;QACT,gBAAS;GAJnB,aAAa,CAwNzB"}
package/test-setup.js DELETED
@@ -1 +0,0 @@
1
- //# sourceMappingURL=test-setup.js.map
package/test-setup.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"test-setup.js","sourceRoot":"","sources":["../../../../libs/shared/paypal/test-setup.ts"],"names":[],"mappings":""}
File without changes