Git Product home page Git Product logo

ewallet-rest-api's Introduction

E-Wallet Rest Api

E-Wallet Rest Api Example. Using Node.js, Express and MongoDB.

Requirements

Getting Started

Clone the repo:

git clone https://github.com/mmucito/ewallet-rest-api.git
cd ewallet-rest-api

Install yarn:

npm install -g yarn

Install dependencies:

yarn

Set environment variables:

cp .env.example .env

Running Locally

yarn dev

Running in Production

yarn start

API Reference

https://ewallet-rest-api.herokuapp.com/v1/docs/

API Endpoint

https://ewallet-rest-api.herokuapp.com/

API Postman Collection for Testing

https://github.com/mmucito/ewallet-rest-api/blob/master/ewallet.postman_collection.json

Testing Locally...

First you need to Create a Customer

curl -X POST \
  http://localhost:3000/v1/auth/register \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: 030c9874-23c0-367b-7e2b-aea506e851c4' \
  -d 'email=jhon_doe%40gmail.com&password=123456&name=Jhon%20Doe'

Login

curl -X POST \
  http://localhost:3000/v1/auth/login \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: b309972f-4942-d788-30a0-df86f4f1b854' \
  -d 'email=jhon_doe%40gmail.com&password=123456'

Get eWallet Balance

curl -X GET \
  http://localhost:3000/v1/ewallet/balance \
  -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDc3NDM4MTgsImlhdCI6MTUwNzc0MjkxOCwic3ViIjoiNTlkZTUzZDVhYzM5ZmQ1ODQ3MGRjODI4In0.mUry4SFaWRqRrBmNF1RBBnJMvcvJBYAktqczpMj8r2w' \
  -H 'cache-control: no-cache' \
  -H 'postman-token: 6df0eb80-e0fc-5f47-4b72-2f3f165eeaaf'

Make a Deposit to your eWallet

curl -X POST \
  http://localhost:3000/v1/ewallet/deposit \
  -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDc3NDM4MTgsImlhdCI6MTUwNzc0MjkxOCwic3ViIjoiNTlkZTUzZDVhYzM5ZmQ1ODQ3MGRjODI4In0.mUry4SFaWRqRrBmNF1RBBnJMvcvJBYAktqczpMj8r2w' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: 66218aae-19ee-3761-e0c0-53823d0d4820' \
  -d 'amount=10&card=4111111111111111'

Note: You can simulate a Payment Rejected by the PaymentGateway using this card 4242424242424242

Get eWallet Transactions

curl -X GET \
  http://localhost:3000/v1/ewallet/transactions \
  -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDc3NDM4MTgsImlhdCI6MTUwNzc0MjkxOCwic3ViIjoiNTlkZTUzZDVhYzM5ZmQ1ODQ3MGRjODI4In0.mUry4SFaWRqRrBmNF1RBBnJMvcvJBYAktqczpMj8r2w' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: ff68cdff-9fac-9647-4594-70315ab1f4cd'

Make a Transfer to another eWallet

curl -X POST \
  http://localhost:3000/v1/ewallet/transfer \
  -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDc3NjYyOTgsImlhdCI6MTUwNzc2NTM5OCwic3ViIjoiNTlkZWE4ZDA2YzkyYmQ2ZTdkZjZiMzMwIn0.PGSdiEpPG43ihnJldKFY-MMqNzaGb4PwOylUbA05AVY' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: 78116228-4061-257a-f47c-37033d474596' \
  -d 'amount=100&destinationAccountNumber=1001'

Note: Every Transaction will generate a fee that will be discounted from the eWallet Balance and will be credited to the Master Account according to this table.

Amount | Percent | Fixed rate |---|---|---|---|---| x <= 1,000 | 3.0% | $8.00 1,000 > x <= 5,000 | 2.5% | $6.00 5,000 > x <= 10,000. | 2.0% | $4.00 10,000 > x | 1.0% | $3.00

Triggers a Withdrawal from your eWallet

curl -X POST \
  http://localhost:3000/v1/ewallet/withdrawal \
  -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDc3NzI5NjAsImlhdCI6MTUwNzc3MjA2MCwic3ViIjoiNTlkZWE4ZDA2YzkyYmQ2ZTdkZjZiMzMwIn0.SF8OdwKfT-fiWbkhUgnTKWfyeZCY_p3ek4j2dPVukuc' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: d2292d62-cefd-e7b9-311a-12fe92795c79' \
  -d 'amount=1500&card=4111111111111111'

Note: You can simulate a Failure on the Withdrawal Gateway using this card 4242424242424242

Master Account Info

Login

curl -X POST \
  http://localhost:3000/v1/auth/login \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: 4e2b3f90-343e-7643-89a3-957dc0ba36c7' \
  -d 'email=master_account%40bank.com&password=master'

Get Master Account Balance

curl -X GET \
  http://localhost:3000/v1/ewallet/balance \
  -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDc3NDM4MTgsImlhdCI6MTUwNzc0MjkxOCwic3ViIjoiNTlkZTUzZDVhYzM5ZmQ1ODQ3MGRjODI4In0.mUry4SFaWRqRrBmNF1RBBnJMvcvJBYAktqczpMj8r2w' \
  -H 'cache-control: no-cache' \
  -H 'postman-token: 6df0eb80-e0fc-5f47-4b72-2f3f165eeaaf'

Lint

# lint code with ESLint
yarn lint

# try to fix ESLint errors
yarn lint:fix

Test

# run all tests with Mocha
yarn test

Validate

# run lint and tests
yarn validate

Logs

# show logs in production
pm2 logs

Documentation

# generate and open api documentation
yarn docs

Docker

# run container locally
yarn docker:dev
or
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up

# run container in production
yarn docker:prod
or
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up

# run tests
yarn docker:test
or
docker-compose -f docker-compose.yml -f docker-compose.test.yml up

Deploy

Set your server ip:

DEPLOY_SERVER=127.0.0.1

Replace my Docker username with yours:

nano deploy.sh

Run deploy script:

yarn deploy
or
sh ./deploy.sh

License

This project is licensed under the MIT License

Using express-rest-es2017-boilerplate as a Starter Seed.

ewallet-rest-api's People

Contributors

mmucito avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ewallet-rest-api's Issues

MongoDB connection error: Error: slash in host identifier

Hello, I'm running your node.js project with mongodb, express, but I get this error when I start the server:

MongoDB connection error: Error: slash in host identifier
[nodemon] app crashed - waiting for file changes before starting ...

this is my files:
mongoose.js file:

const { mongo, env } = require('./vars');

// set mongoose Promise to Bluebird
mongoose.Promise = Promise;

// Exit application on error
mongoose.connection.on('error', (err) => {
  console.error(`MongoDB connection error: ${err}`);
  process.exit(-1);
});

// print mongoose logs in dev env
if (env === 'development') {
  mongoose.set('debug', true);
}

/**
* Connect to mongo db
*
* @returns {object} Mongoose connection
* @public
*/
exports.connect = () => {
  mongoose.connect(mongo.uri, {
    keepAlive: 1,
    useMongoClient: true,
  });
  return mongoose.connection;
};

my var.js file:

const path = require('path');

// import .env variables
require('dotenv-safe').load({
  path: path.join(__dirname, '../../.env'),
  sample: path.join(__dirname, '../../.env.example'),
});

module.exports = {
  env: process.env.NODE_ENV,
  port: process.env.PORT,
  jwtSecret: process.env.JWT_SECRET,
  jwtExpirationInterval: process.env.JWT_EXPIRATION_MINUTES,
  masterAccount: process.env.MASTER_ACCOUNT_NUMBER,
  masterAccountPassword: process.env.MASTER_ACCOUNT_PASSWORD,
  mongo: {
    uri: process.env.NODE_ENV === 'test'
      ? process.env.MONGO_URI_TESTS
      : process.env.MONGO_URI,
  },
  logs: process.env.NODE_ENV === 'production' ? 'combined' : 'dev',
};

the index.js file:

Promise = require('bluebird'); // eslint-disable-line no-global-assign
const { port, env } = require('./config/vars');
const app = require('./config/express');
const mongoose = require('./config/mongoose');

// open mongoose connection
mongoose.connect();

// listen to requests
app.listen(port, () => console.info(`server started on port ${port} (${env})`));

/**
* Exports express
* @public
*/
module.exports = app;

thanks for you help

I have an 401 error (Unauthorized) with this API

I am integrating my API into my ionic view, so I would like to integrate my money transfer endpoint from one leaf port to another but I get a 401 error.

Here is my source code:


Ionic Source Code of Transfer:

  • This is my Service Allet:

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';
import { StorageService } from './storage.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class WalletService {

  constructor(
    private httpService: HttpService,
    private storageService: StorageService,
    private router: Router
  ) { }

  transfert(data: any): Observable<any>{
    return this.httpService.post("ewallet/transfer", data);
  }
}
  • My httpService:

import { environment } from './../../environments/environment.prod';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { headersToString } from "selenium-webdriver/http";

@Injectable({
  providedIn: 'root'
})
export class HttpService {  
  httpOptions = {
    headers: new HttpHeaders({ 
      'Content-Type': 'application/json'
    }),
    withCredintials: false
  };

  constructor(
    private http: HttpClient
  ) {}

  post(serviceName: string, data: any){
    const url = environment.apiUrl + serviceName;
    return this.http.post(url,data, this.httpOptions);
  }

  getById(serviceName: string, id: string){
    const url = environment.apiUrl + serviceName;
    return this.http.get(url+"/"+id);
  }

  getAll(serviceName: string){
    const url = environment.apiUrl + serviceName;
    return this.http.get(url);
  }

  update(serviceName: string, id: string, data: any){
    const url = environment.apiUrl + serviceName;
    return this.http.put(url+"/"+id, data, this.httpOptions);
  }

  modify(serviceName: string, id: string, data: any){
    const url = environment.apiUrl + serviceName + id;
    return this.http.patch(url, data, this.httpOptions);
  }

  delete(serviceName: string, id: string){
    const url = environment.apiUrl + serviceName;
    return this.http.delete(url+"/"+id, this.httpOptions);
  }
}
  • My typescript file:

import { ContactService } from './../services/contact.service';
import { AuthConstants } from 'src/app/config/auth-constant';
import { StorageService } from 'src/app/services/storage.service';
import { SuccessmodalPage } from './../modals/successmodal/successmodal.page';
import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { WalletService } from '../services/wallet.service';

@Component({
  selector: 'app-requestreview',
  templateUrl: './requestreview.page.html',
  styleUrls: ['./requestreview.page.scss'],
})
export class RequestreviewPage implements OnInit {
  public typee: any;
  public title: any;
  public amount: string;
  public contact: any;
  public authUser: any;
  public data: any = {
    name: '',
    email: ''
  };

  public dataTransfert = {
    amount: '',
    destinationAccountNumber: ''
  }

  constructor(
    public modalCtrl: ModalController, 
    private route: ActivatedRoute,
    private storageService: StorageService,
    private authService: AuthService,
    private walletService: WalletService,
    private contactService: ContactService
  ) { }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.typee = params["type"];
    });

    //get auth user informations
    this.authService.userData$.subscribe((res: any) =>{
      this.authUser = res;
      console.log(res.customer.accountNumber);
    });

    //get contact datas
    this.contactService.contactData$
      .subscribe(data => (this.contact = data));

    //get amount data
    this.contactService.amountData$
      .subscribe(data => (this.amount = data));
    //set title
    this.setTitle();

    console.log('données a transferer: ',this.getData());
  }

  getData(){
    this.dataTransfert.amount = this.amount;
    this.dataTransfert.destinationAccountNumber = this.contact.accountNumber;

    return this.dataTransfert;
  }

  transfert(){
    this.walletService.transfert(this.getData()).subscribe((res: any) =>{
      this.showModal();
    });
    
  }

  setTitle() {
    if (this.typee == 'request') {
      this.title = "Review and Request";
    }

    if (this.typee == 'send') {
      this.title = "Review and Send";
    }
  }

  async showModal() {
    const modal = await this.modalCtrl.create({
      component: SuccessmodalPage,
      backdropDismiss: true
    });

    return await modal.present();
  }
}

(On the server) My node.js code:

  • My Route:

router
  .route('/transfer')
  /**
   * @api {post} v1/ewallet/transfer eWallet Transfer
   * @apiDescription Make a transfer to another eWallet
   * @apiVersion 1.0.0
   * @apiName Transfer
   * @apiGroup eWallet
   * @apiPermission customer
   *
   * @apiHeader {String} Authorization Customer's access token
   *
   * @apiParam  {Number{0...50000}}       amount       Decimal whith two fraction digits.
   * @apiParam  {Number}             destinationAccountNumber  Transaction's destinationAccountNumber
   *
   * @apiSuccess {Object}  transaction       Transaction.
   * @apiSuccess  {String}  transaction.id     Transaction's id
   * @apiSuccess  {Number}  transaction.accountNumber   Transaction's accountNumber
   * @apiSuccess  {Number}  transaction.destinationAccountNumber   Transaction's destinationAccountNumber
   * @apiSuccess  {String}  transaction.operation  Transaction's type of operation (deposit, withdrawal, transfer, fee)
   * @apiSuccess  {Number}  transaction.amount     Transaction's amount
   * @apiSuccess  {Number}  transaction.reference     Transaction's reference
   * @apiSuccess  {Date}    transaction.createdAt      Timestamp
   *
   * @apiSuccess {Object}  customer       Customer.
   * @apiSuccess  {String}  customer.id             Customer's id
   * @apiSuccess  {Number}  customer.accountNumber  Customer's accountNumber
   * @apiSuccess  {String}  customer.name           Customer's name
   * @apiSuccess  {String}  customer.email          Customer's email
   * @apiSuccess  {String}  customer.role           Customer's role
   * @apiSuccess  {Date}    customer.createdAt      Timestamp
   *
   * @apiError (Bad Request 400)   ValidationError  Some parameters may contain invalid values
   * @apiError (Unauthorized 401)  Unauthorized     Only authenticated customers can create the data
   * @apiError (Forbidden 403)     Forbidden        Only admins can create the data
   */
  .post(authorize(), validate(walletTransfer), controllerWallet.transfer); //authorize(), walletTransfer, 

  • The Controller Function:

/**
 * eWallet Transfer
 * @public
 */
exports.transfer = async (req, res, next) => {
  try {    
    const transferResponse = await transferService.transfer(req.customer.accountNumber, req.body.amount, req.body.destinationAccountNumber);    
    res.json(transferResponse);    
    
  } catch (error) {
    next(error);
  }
};

Any help is appreciated, thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.