├── .gitignore ├── .npmignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── assets └── readme.png ├── package-lock.json ├── package.json ├── src ├── __test__ │ └── ncp_client.test.ts ├── index.ts ├── ncp_client.ts └── types.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | .vscode -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | coverage 3 | .vscode 4 | .travis.yml 5 | LICENSE 6 | __test__ 7 | tsconfig.json -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - stable 4 | install: 5 | - npm install 6 | script: 7 | - npm test 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ## [1.3.0](https://github.com/Bumkeyy/node-sens/compare/v1.2.4...v1.3.0) (2020-11-17) 6 | 7 | 8 | ### Features 9 | 10 | * standard-version 적용 ([1bf25d6](https://github.com/Bumkeyy/node-sens/commit/1bf25d64136e71f2d5865500edd161e04f020217)) 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kibeom Kwon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # node-sens 2 | 3 | [![npm version](https://badge.fury.io/js/node-sens.svg)](https://badge.fury.io/js/node-sens) ![travisci](https://travis-ci.com/Bumkeyy/node-sens.svg?branch=master) ![GitHub Release Date](https://img.shields.io/github/release-date/bumkeyy/Node-sens) 4 | 5 | Simple & Easy Notification Service client in NAVER CLOUD PLATFORM 6 | 7 | ![readme](/assets/readme.png) 8 | 9 | Naver Cloud Platform에서 제공하는 SENS client 입니다. 10 | 11 | [SMS API v2](https://apidocs.ncloud.com/ko/ai-application-service/sens/sms_v2/)와 sync되어 있습니다. 12 | 13 | ## Installation 14 | 15 | ```sh 16 | npm install node-sens --save 17 | yarn add node-sens 18 | ``` 19 | 20 | ## Usage 21 | 22 | ```typescript 23 | import { NCPClient } from 'node-sens'; 24 | 25 | const ncp = new NCPClient({ 26 | phoneNumber: '01012345678', 27 | serviceId: 'serviceId', 28 | secretKey: 'secretKey', 29 | accessKey: 'accessKey', 30 | }); 31 | ``` 32 | 33 | #### Parameter Type 34 | 35 | - `phoneNumber` (string): 발신 전화번호 36 | - `serviceId` (string): 프로젝트의 서비스 id 37 | - `secretKey` (string): 프로젝트 계정의 secretKey 38 | - `accessKey` (string): 프로젝트 계정의 accessKey 39 | 40 | ```typescript 41 | const { success, msg, status } = await ncp.sendSMS({ 42 | to: '01012345678', 43 | content: 'Hello SENS', 44 | }); 45 | 46 | const { success, msg, status } = await ncp.sendSMS({ 47 | to: '01012345678', 48 | content: 'Hello SENS', 49 | countryCode: '82', 50 | }); 51 | ``` 52 | 53 | #### Parameter Type 54 | 55 | - `to` (string): 수신 전화번호 56 | - `content` (string): 보낼 내용 57 | - `countryCode`(optional) : 국가 코드 (default : 82) 58 | 59 | #### Return Type 60 | 61 | - `promise` : `promise`를 반환합니다. 62 | 63 | PromiseReturnType: 64 | - `success` (boolean) : `true`시 성공, `false`시 실패 65 | - `msg` (string) : 성공시 `Accepted`, 실패시 `error message` 66 | - `status` (number) : status code 67 | 68 | ## Status Code 69 | 70 | | HTTP Status | Desc | 71 | | :---------: | :-------------------: | 72 | | 202 | Accept (요청 완료) | 73 | | 400 | Bad Request | 74 | | 401 | Unauthorized | 75 | | 403 | Forbidden | 76 | | 404 | Not Found | 77 | | 429 | Too Many Requests | 78 | | 500 | Internal Server Error | 79 | 80 | ## Test 81 | 82 | ```sh 83 | npm run test 84 | ``` 85 | 86 | ## CONTRIBUTING 87 | 88 | 해당 코드에 버그나 이슈는 언제나 환영입니다 :smile: 89 | -------------------------------------------------------------------------------- /assets/readme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bumkeyy/node-sens/1badd041c5e624de56847efaf65e5ef96078fd48/assets/readme.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-sens", 3 | "version": "1.3.0", 4 | "description": "Simple & Easy Notification Service client in NAVER CLOUD PLATFORM", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "scripts": { 8 | "test": "jest", 9 | "build": "tsc", 10 | "prebuild": "rm -rf dist", 11 | "release": "standard-version" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/Bumkeyy/node-sens.git" 16 | }, 17 | "author": "bumkeyy ", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/Bumkeyy/node-sens/issues" 21 | }, 22 | "homepage": "https://github.com/Bumkeyy/node-sens#readme", 23 | "devDependencies": { 24 | "@types/jest": "^26.0.8", 25 | "coveralls": "^3.1.0", 26 | "istanbul": "^0.4.5", 27 | "jest": "^26.2.2", 28 | "standard-version": "^9.0.0", 29 | "ts-jest": "^26.1.4", 30 | "typescript": "^3.9.7" 31 | }, 32 | "dependencies": { 33 | "axios": "^0.21.1", 34 | "crypto": "^1.0.1" 35 | }, 36 | "jest": { 37 | "transform": { 38 | "^.+\\.ts$": "ts-jest" 39 | }, 40 | "testRegex": "\\.test\\.ts$", 41 | "moduleFileExtensions": [ 42 | "ts", 43 | "tsx", 44 | "js", 45 | "json" 46 | ], 47 | "globals": { 48 | "ts-jest": { 49 | "diagnostics": true 50 | } 51 | } 52 | }, 53 | "keywords": [ 54 | "http", 55 | "sms", 56 | "naver", 57 | "ncp", 58 | "platform", 59 | "client", 60 | "node" 61 | ] 62 | } 63 | -------------------------------------------------------------------------------- /src/__test__/ncp_client.test.ts: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | import { NCPClient } from '../ncp_client'; 3 | 4 | jest.mock('axios'); 5 | 6 | const to = '000'; 7 | const content = 'test message'; 8 | const phoneNumber = 'phonenumber'; 9 | const serviceId = 'serviceId'; 10 | const secretKey = 'secretKey'; 11 | const accessKey = 'accessKey'; 12 | 13 | describe('NCP Client', () => { 14 | let ncp: NCPClient; 15 | 16 | beforeEach(() => axios.mockClear()); 17 | 18 | beforeAll(() => { 19 | ncp = new NCPClient({ 20 | phoneNumber, 21 | serviceId, 22 | secretKey, 23 | accessKey, 24 | }); 25 | }); 26 | 27 | test('create NCP Client', () => { 28 | expect( 29 | () => 30 | new NCPClient({ 31 | phoneNumber, 32 | serviceId, 33 | secretKey, 34 | accessKey, 35 | }) 36 | ).not.toThrow(); 37 | }); 38 | 39 | test('send SMS success', async () => { 40 | axios.mockImplementationOnce(() => 41 | Promise.resolve({ 42 | status: 202, 43 | statusText: 'Accepted', 44 | }) 45 | ); 46 | const { success, msg, status } = await ncp.sendSMS({ 47 | to, 48 | content, 49 | }); 50 | expect(success).toBe(true); 51 | expect(msg).toBe('Accepted'); 52 | expect(status).toBe(202); 53 | }); 54 | 55 | test('Authentication Failed, This account is not allowed', async () => { 56 | axios.mockImplementationOnce(() => 57 | Promise.reject({ 58 | response: { 59 | status: 401, 60 | statusText: 'Unauthorized', 61 | }, 62 | }) 63 | ); 64 | const { success, msg, status } = await ncp.sendSMS({ 65 | to, 66 | content, 67 | }); 68 | expect(success).toBe(false); 69 | expect(msg).toBe('Unauthorized'); 70 | expect(status).toBe(401); 71 | }); 72 | 73 | test('PhoneNumber is not found', async () => { 74 | axios.mockImplementationOnce(() => 75 | Promise.reject({ 76 | response: { 77 | status: 404, 78 | statusText: 'Not Found', 79 | }, 80 | }) 81 | ); 82 | const { success, msg, status } = await ncp.sendSMS({ 83 | to, 84 | content, 85 | }); 86 | 87 | expect(success).toBe(false); 88 | expect(msg).toBe('Not Found'); 89 | expect(status).toBe(404); 90 | }); 91 | }); 92 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { NCPClient } from './ncp_client'; 2 | -------------------------------------------------------------------------------- /src/ncp_client.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import crypto from 'crypto'; 3 | import { NCPClientOptions, prepareSignatureReturnType, sendSMSReturnType, sendSMSType } from './types'; 4 | 5 | export class NCPClient { 6 | private phoneNumber: string; 7 | private serviceId: string; 8 | private secretKey: string; 9 | private accessKey: string; 10 | 11 | private url: string; 12 | private method: string; 13 | 14 | /** 15 | * 16 | * Constructs an instance of NCPClient. 17 | * 18 | * @param phoneNumber 발신 전화번호 19 | * 20 | * @param serviceId 프로젝트의 서비스 id 21 | * 22 | * @param secretKey 프로젝트 계정의 secretKey 23 | * 24 | * @param accessKey 프로젝트 계정의 accessKey 25 | */ 26 | constructor(options: NCPClientOptions) { 27 | const { phoneNumber, serviceId, secretKey, accessKey } = options; 28 | this.phoneNumber = phoneNumber; 29 | this.serviceId = serviceId; 30 | this.secretKey = secretKey; 31 | this.accessKey = accessKey; 32 | this.url = `https://sens.apigw.ntruss.com/sms/v2/services/${this.serviceId}/messages`; 33 | this.method = 'POST'; 34 | } 35 | 36 | /** 37 | * 38 | * SMS를 보내는 함수 39 | * 40 | * @param to 수신 전화번호 41 | * @param content 전달할 내용 42 | * @param countryCode 국가 코드 (default 82) 43 | * 44 | * @returns Promise with success(boolean), msg(string), status(number) 45 | * 46 | */ 47 | public async sendSMS({ 48 | to, 49 | content, 50 | countryCode = '82' 51 | }: sendSMSType): Promise { 52 | try { 53 | const {timestamp, signature} = this.prepareSignature() 54 | const response = await axios({ 55 | method: 'POST', 56 | url: this.url, 57 | headers: { 58 | 'Content-Type': 'application/json; charset=utf-8', 59 | 'x-ncp-iam-access-key': this.accessKey, 60 | 'x-ncp-apigw-timestamp': timestamp, 61 | 'x-ncp-apigw-signature-v2': signature, 62 | }, 63 | data: { 64 | type: 'SMS', 65 | contentType: 'COMM', 66 | countryCode, 67 | from: this.phoneNumber, 68 | content, 69 | messages: [ 70 | { 71 | to: `${to}`, 72 | }, 73 | ], 74 | }, 75 | }); 76 | 77 | if (response.status === 202) { 78 | return { 79 | success: true, 80 | status: response.status, 81 | msg: response.statusText, 82 | }; 83 | } else { 84 | return { 85 | success: false, 86 | status: response.status, 87 | msg: response.statusText, 88 | }; 89 | } 90 | } catch (error) { 91 | return { 92 | success: false, 93 | msg: error.response.statusText || 'Internal Server Error', 94 | status: error.response.status || 500, 95 | }; 96 | } 97 | } 98 | 99 | /** 100 | * 101 | * API 시그니처를 생성하는 함수 102 | * 103 | * @returns timestamp(string), signature(string) 104 | */ 105 | private prepareSignature(): prepareSignatureReturnType { 106 | const space = ' '; 107 | const newLine = '\n'; 108 | const message = []; 109 | const hmac = crypto.createHmac('sha256', this.secretKey); 110 | const url2 = `/sms/v2/services/${this.serviceId}/messages`; 111 | const timestamp = Date.now().toString(); 112 | 113 | message.push(this.method); 114 | message.push(space); 115 | message.push(url2); 116 | message.push(newLine); 117 | message.push(timestamp); 118 | message.push(newLine); 119 | message.push(this.accessKey); 120 | 121 | return { 122 | timestamp, 123 | signature: hmac.update(message.join('')).digest('base64') 124 | }; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | export type NCPClientOptions = { 2 | phoneNumber: string; 3 | serviceId: string; 4 | secretKey: string; 5 | accessKey: string; 6 | }; 7 | 8 | export type sendSMSType = { 9 | to: string; 10 | content: string; 11 | countryCode?: string; 12 | }; 13 | 14 | export type sendSMSReturnType = { 15 | success: boolean; 16 | msg: string; 17 | status: number; 18 | }; 19 | 20 | export type prepareSignatureReturnType = { 21 | timestamp: string; 22 | signature: string; 23 | }; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es5", 8 | /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 9 | "module": "commonjs", 10 | /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 11 | // "lib": [], /* Specify library files to be included in the compilation. */ 12 | // "allowJs": true, /* Allow javascript files to be compiled. */ 13 | // "checkJs": true, /* Report errors in .js files. */ 14 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 15 | "declaration": true, 16 | /* Generates corresponding '.d.ts' file. */ 17 | // "declarationMap": true, 18 | /* Generates a sourcemap for each corresponding '.d.ts' file. */ 19 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 20 | // "outFile": "./", /* Concatenate and emit output to single file. */ 21 | "outDir": "dist", 22 | /* Redirect output structure to the directory. */ 23 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 24 | // "composite": true, /* Enable project compilation */ 25 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 26 | // "removeComments": true, /* Do not emit comments to output. */ 27 | // "noEmit": true, /* Do not emit outputs. */ 28 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 29 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 30 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 31 | 32 | /* Strict Type-Checking Options */ 33 | "strict": true, 34 | /* Enable all strict type-checking options. */ 35 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 36 | // "strictNullChecks": true, /* Enable strict null checks. */ 37 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 38 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 39 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 40 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 41 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 42 | 43 | /* Additional Checks */ 44 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 45 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 46 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 47 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 48 | 49 | /* Module Resolution Options */ 50 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 51 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 52 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 53 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 54 | // "typeRoots": [], /* List of folders to include type definitions from. */ 55 | // "types": [], /* Type declaration files to be included in compilation. */ 56 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 57 | "esModuleInterop": true, 58 | /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 59 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 60 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 61 | 62 | /* Source Map Options */ 63 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 64 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 65 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 66 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 67 | 68 | /* Experimental Options */ 69 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 70 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 71 | 72 | /* Advanced Options */ 73 | "skipLibCheck": true, 74 | /* Skip type checking of declaration files. */ 75 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 76 | }, 77 | "include": ["./src/**/*"], 78 | "exclude": ["./src/__test__"] 79 | } --------------------------------------------------------------------------------