Giter Site home page Giter Site logo

express-starter-kit's Introduction


Logo

Salla Apps Starter Kit

An awesome starter template to create your Salla Apps today!
Explore our blogs »

Report Bug · Request Feature . </Salla Developers>

Table of Contents
  1. Overview
  2. Getting Started
  3. Usage
  4. Configure Authorization Modes
  5. Authorization Service
  6. Webhooks
  7. Commands
  8. Contributing
  9. License

Overview

This is a starter App to create ExpressJS application equipped with the required auth processes and webhooks/actions that help you to create your Salla App which works with the Salla APIs. Your App later can be published to the Salla App Store and be available for installation to any of Salla Merchants Stores.

What can you use this starter App for?

  • Create a Salla App from scratch, e.g. chatbot app or shipping service app, or any amazing app from your idea.
  • Modify/Customize any of your previous Apps in order to take the advantages given by this starter App.

(back to top)

Getting Started

The starter App comes with an easy 1-command step that does the complete setup for your starter App. To be ready, you will need some prerequisites which will be listed hereafter.

Prerequisites

  • Create a Partner account at Salla Partner Portal

  • Create your App in Salla Partner Portal

    From your App dashboard at Salla Partner Portal, you will be able to get your App's Client ID, Client Secret Key and Webhook Secret Key which you will use later duraing the setup process.

  • For EpxressJS compatibility : NodeJS >= 12.x.x, Node Package Manager and it support any Database [MySQL,MongoDB,PostgreSQL]

That is all!

Installation

The installation process is straightforward as you will see in the below steps.

  1. In your MySql Database: create a database with any name for example express.
  2. Install Salla CLI via NPM: npm install @salla.sa/cli -g where you will be able to run the salla binary commands such as salla app create and salla app create-webhook <event.name>

(back to top)

Usage

With Salla CLI installed, run the following command to create your Express starter app project: salla app create and follow on-screen instructions.

List of existing apps assocaited to your account will be displayed as well as an option to create your app on Salla Partners Portal. Afterwards, you will be presented with easy-to fill in information to create your app.

Salla App Create Command

(back to top)

> If you are using [Easy mode.](#auth-modes.easy) the access token will push to the action ([`app.store.authorize`](app\template\Actions\app\store.authorize.js)) via webhook > > If you are using [Custom mode.](#auth-modes.custom) the browser will redirect you again to the [`store.authorize.js file`](app\template\Actions\app\store.authorize.js).

Output URLs

URL Description
Local App Url The local link for your App.
Remote App Url The online link to your App. It will be always synced with the local Url
Webhook Url The Url link that connects your App with any action that may happen at the Merchant store, e.g. \ncreate new product.
OAuth Callback Url The App entry page where the access token is generated; Note that this Url is available only for the Custom mode auth.

(back to top)

Configure Authorization Modes

While creating your App in the Salla Partners Portal, you will see that Salla provids two methods for the OAuth protocol, which are the Easy Mode and the Custom Mode.

During the setup process, the default OAuth protocol will be set to the Easy Mode, which can be configured from the file .env. All of the setup's values/keys are stored in the .env file as we can see in the below image.

salla-express-starter-kit

Easy Mode

This mode is the default mode for the authorization, which means that the access token is generated automatically at Salla's side back to you. You may refer to the class StoreAuthorize which is defined inside app\template\Actions\app\store.authorize.js to get more details on how to receive and manage the access token

Custom Mode

A callback Url is the Url that is triggered when the App has been granted authorization. This should be a valid Url to which the merchant's browser is redirected. In this mode, you will need to set a custom callback url from the App dashboard at the Salla Partner Portal. This callback url will redirect the merchants who are interested in using your app into your App entry page where the access token is generated.

The custom url will redirect the merchant to the Store Dashboard in order to access the Store where he needs your App to be installed.


Authorization Service

This project comes with a simple singleton authorization service to help you with managing the access and refresh tokens

const express = require("express");
const passport = require("passport");
const SallaAPIFactory = require("@salla.sa/passport-strategy");
const app = express();

const port = 8081;

// we initialize our Salla API
const SallaAPI = new SallaAPIFactory({
  clientID: "CLIENT_ID", // The client ID assigned to you by Salla in Salla Partner Portal
  clientSecret: "CLIENT_SECRET", // The client password assigned to you by Salla in Salla Partner Portal
  callbackURL: "http://localhost:8081/oauth/callback", // the /oauth/callback in your service
});

// Use the Salla Strategy within Passport.
passport.use(SallaAPI.getPassportStrategy());

// save token and user data to your selected database
SallaAPI.onAuth((accessToken, refreshToken, expiresin, user) => {
  /*
accessToken
refreshToken
expires*in
user
\*/
});

//when your user login to your application you can retrieve the access token and use
//it to access the Salla APIs from SallaAPI.setAccessToken .

SallaAPI.setAccessToken(
  ACCESS_TOKEN_FROM_DATABASE,
  REFRESH_TOKEN_FROM_DATABASE,
  EXPIRES_IN_FROM_DATABASE,
  USER_PROFILE_FROM_DATABASE
);

// we set salla express middleware
app.use((req, res, next) => SallaAPI.setExpressVerify(req, res, next));

// GET /
// render the index page

app.get("/", function (req, res) {
  res.send({ user: req.user });
});

// GET /oauth/redirect
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in salla authentication will involve redirecting
// the user to accounts.salla.sa. After authorization, salla will redirect the user
// back to this application at /oauth/callback
app.get("/oauth/redirect", passport.authenticate("salla"));

// GET /oauth/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get(
  "/oauth/callback",
  passport.authenticate("salla", { failureRedirect: "/login" }),
  function (req, res) {
    res.redirect("/");
  }
);

app.listen(port, function () {
  console.log("App is listening on port " + port);
});

Refreshing a Token

Access tokens expire after one week. Once expired, you will have to refresh a user’s access token. you can easily request a new access token via the current refresh token for any user like this

const SallaAPI = require("@salla.sa/passport-strategy");

SallaAPI.requestNewAccessToken(SallaAPI.getRefreshToken())
  .then(({ accessToken, newRefreshToken }) => {
    // save new access token and refresh token to your database
  })
  .catch((err) => res.send(err));

Webhooks

Webhooks simplify the communication between your App and Salla APIs. In this way, you will be notified whenever your app receives payload/data from the Salla APIs. These webhooks are triggered along with many actions such as an order or product being created, a customer logs in, a coupon is applied, and much more.

Salla already defined a list of the webhooks/actions that are triggered automatically. The predefined webhooks/actions can be found in the folder app/Actions.

Commands

Setup command

The setup file can be found in src.

salla app create

Create new Webhook/Action command

The predefined Webhooks, events/actions, can be found in folder app/Actions.

You may define your own new webhook/action the way fits your App's requirments.

salla app create-webhook <event.name>

Contributing

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

(back to top)

express-starter-kit's People

Contributors

kernelcode avatar

Watchers

James Cloos avatar

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.