Category Archives: PHP

Do you want to build a PHP application under a couple of hours but clueless where to begin? We have a basic tutorial where we’ll walk you through building a PHP application, including how to upload and launch your application.

So what are you waiting for? Let’s get started!

Build your PHP Application using our StarterAPI: The following steps will give you a basic idea on how to integrate the API for building your application.

  1. Download our Starter PHP Application
  2. Configure the application
  3. Deploy on server
  4. Launch your application

To interact with our API Server, there is a PHP composer library called “wavelabs_php_api“. The source code and documentation of this library are available here. This library is published in the Composer.org under MIT license. You can get the latest one using the following command:

PHP composer install wavelabs/php-client-api

1. Download Our Starter PHP Application

Download the application from PHP Application.

2. Configure the Application

Register yourself on NBOS website. Create your tenant. Grab the client id, secret and update in /application/config/constants.php

defined('API_HOST_URL') OR define('API_HOST_URL', "http://api.qa1.nbos.in/");
defined('API_CLIENT_ID') OR define('API_CLIENT_ID', "api-client");
defined('API_CLIENT_SECRET') OR define('API_CLIENT_SECRET', "api-secret");

3. Upload App On Hosting Server

Deploy your code on the server.
If you are doing it locally, move this folder to the document root of apache.

4. Launch Your Application

Open your browser and try your domain.
http://<yourdomain_name>/

PHP APP

And there you go, it’s all done. You’ve successfully launched your first PHP application into the market.

As you probably know, eCommerce portal with OAuth2 development can be broken up into three main areas:

  • Setup eCommerce portal using OpenCart
  • Installing vQmod extension for OpenCart
  • Add REST API with OAuth2.0 to OpenCart

Setup eCommerce portal using OpenCart

Setup eCommerce portal using OpenCart. Here is a link for reference.

Installing vQmod extension for OpenCart

“vQmod” (aka Virtual Quick Mod) is an override system designed to avoid having to change OpenCart core files.

How to install vQmod using Autoinstaller

1) Download the latest version that has “opencart” in the title from the download area.

  1. Using FTP, upload the “vqmod” folder from the zip to the root of your opencart store.
  2. Be sure the vqmod folder and the vqmod/vqcache folders are writable (either 755 or 777).
    • Also be sure index.php and admin/index.php are writable.
      • If you’re not sure, then try 755.
      • If you get errors about permissions, then try 777.

NOTE: 777 permissions are dangerous and should only be used as a last resort. If your hosting requires this, consult your hosting to let them know this shouldn’t be necessary

  1. Goto http://www.yoursite.com/vqmod/install
  2. You should get a success message. If not, check the above permissions, and try again
  3. Load your store homepage and verify that it works.
  4. Using FTP, verify that there are new “vq” files in the “vqmod/vqcache” folder.
  5. If yes, then you are ready to start downloading or creating vQmod scripts, otherwise ask for assistance.

Done!

  • DO NOT DELETE THE INSTALL FOLDER!
  • YOU MUST RUN THE INSTALLER EVERY TIME YOU UPGRADE OPENCART!!
  • THERE IS NO DANGER OF RE-RUNNING THE INSTALLER!

How to install vQmod manually?

1) Download the latest version that has “OpenCart” in the title.

  1. Using FTP, upload the “vqmod” folder from the zip to the root of your OpenCart store.
  2. Be sure the vqmod folder and the vqmod/vqcache folders are writable (either 755 or 777).
    • Also be sure index.php and admin/index.php are writable.
      • If not sure which you need, first try 755.
      • If you get errors about permissions, then try 777.
  3. Edit your index.php file.
  4. FIND

  5. REPLACE WITH

Note the affiliate library file may not exist on older systems. Basically any require_once(DIR_SYSTEM . 'library/xxxxxxxx.php'); needs to be changed to use the VQMod::modCheck above in the same format. This also applies to any additional require_once files in the next step

  1. Edit your admin/index.php file
  2. FIND

  3. REPLACE WITH

  4. Load your store homepage and verify if it works.
  5. Using FTP, verify that there are new “vq” files in the “vqmod/vqcache” folder.
  6. If yes, then you are ready to start downloading or creating vQmod scripts.

Done!

Add REST API with OAuth2.0 to OpenCart

OpenCart Rest API is a full featured API that allows you to set up your own rest services within minutes.

You can download it here.
The upload folder contains all files for this module.
You will notice that the folders are in the same structure as your OpenCart installation.

1. Navigate to your opencart root folder using an FTP program.
2. Upload all folders of extension to your opencart installation folder.
3. Execute these SQL statements in phpMyAdmin or whatever client you use for managing your database.

4. Go to your admin area in Extensions->Modules and enable your REST API extension.
You have to fill the Order id field (you can find it in the order email)
You have to fill the client id, client secret fields and TTL. This is needed for authentication with the API.

5. Paste into your opencart root folder .htaccess file after “RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]”
RewriteRule .* – [E=HTTP_Authorization:%{HTTP:Authorization}]

6. Paste into your opencart root folder .htaccess file after “RewriteBase /”

Now we’re able to run Mobile Apps using our own E-Commerce website REST and OAuth2.0 API.

In this post, we’ll learn how to deploy and use REST OAuth2.0 API server using PHP.
Here, REST API using OAuth2

The generic need for any application would be to have some public API’s that can be accessed without any security, & some secured using token associated with clientId/secretKey & some secured using token associated with user credentials.

We will walk thru the implementation in the following sequence.

      1. Implement OAuth2 endpoints using PHP OAuth2 Server library along with sample endpoints access controlled by client/user tokens
      2. Annotate your API with Swagger-UI
      3. Create API for Member Create/Read/Update
      4. Write Unit tests for Member Create/Read/Update
      5. Create API for Auth login/logout & Write Unit Tests

Before we start ensure that your environment is all set

      • Install XAMPP
      • Create a starter app using starter-app-php

        Create a schema named starter_app_dev in mysql using phpMyAdmin.
        Copy code into starter-app-php folder
        Now ready http://localhost/starter-app-php/ app

1 viagra est il en vente libre. Create API for Member Create/Read/Update

Lets make a list of features that we want, just so it would guide us in our design.

  Feature
Login Domain
1a Ensure that password is getting encrypted while saving
1b We shouldn’t be able to create new Login with same username
1c We should have the ability to expire an account
1d We should have the ability to lock an account
Member Domain
2a Each member should have a unique UUID to identify them using URL
2b We cannot have two members with same email
2c A Member cannot exist without a Login
API / MemberController / create
3a Registration with an existing username should respond with 400
3b Registration with an existing email should respond with 400
3c Invalid email syntax should return 400
3d Successful registration should respond with 200 along with member info

Given the list of features, we will start off with the following ER Model

login-member-ermodel

Our next step is to create a module classes in CI.

class MemberModel extends CI_Model
{

    function __construct()
    {
        parent::__construct();
    }

    function addLogin($pdata)
    {
        $this->db->insert("login", $pdata);
        return $this->db->insert_id();
    }

    function addMember($pdata)
    {
        $this->db->insert("member", $pdata);
        return $this->db->insert_id();
    }

    function updateMemberById($id, $pdata)
    {
        $this->db->where("id", $id);
        return $this->db->update("member", $pdata);
    }

    function updateMemberByLoginId($login_id, $pdata)
    {
        $this->db->where("login_id", $login_id);
        return $this->db->update("member", $pdata);
    }

    function getLoginByUsername($username)
    {
        $this->db->select("m.*");
        $this->db->where("m.username", $username);
        $query = $this->db->get("login m");
        if ($query->num_rows() > 0) {
            return $query->row_array();
        }
        return false;
    }

    function getMemberById($login_id)
    {
        $this->db->select("u.*");
        $this->db->where("m.id", $login_id);
        $this->db->join("member u", "m.id=u.login_id");
        $query = $this->db->get("login m");
        if ($query->num_rows() > 0) {
            return $query->row_array();
        }
        return false;
    }

    function getMemberByLoginId($login_id)
    {
        $this->db->select("u.*");
        $this->db->where("m.id", $login_id);
        $this->db->join("member u", "m.id=u.login_id");
        $query = $this->db->get("login m");
        if ($query->num_rows() > 0) {
            $row = $query->row_array();            
            return $row;
        }
        return false;
    }

    function checkUsername($username)
    {
        $this->db->select("m.*");
        $this->db->where("m.username", $username);
        $query = $this->db->get("login m");
        if ($query->num_rows() > 0) {
            return true;
        }
        return false;
    }

}

Lets Create our first API to create a Member
Add an action to create Member.

include_once(APPPATH . "libraries/OAuth2/Autoloader.php");

class Member extends BaseApi
{
    function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->load->library('oauth');
        $this->load->model("MemberModel", "memberModel");
    }

    function create_post()
    {
        $this->server = $this->oauth->getOauthServer();
        $request = OAuth2\Request::createFromGlobals();
        $request->request['response_type'] = "token";
        if (empty($request->request['state'])) {
            $request->request['state'] = "create";
        }
        $response = new OAuth2\Response();

        if (!$this->server->validateAuthorizeRequest($request, $response)) {
            $this->set_response_error($response->getParameters());
        } else {
            $errors = [];
            if (!empty($this->post('username')) && $this->apiModel->checkUsername($this->post('username')) === true) {
                $errors[] = [
                    "messageCode" => "user.username.exists",
                    "message" => "user.username.exists",
                    "objectName" => "",
                    "propertyName" => "username"
                ];
            } else if (empty($this->post('username'))) {
                $errors[] = [
                    "messageCode" => "user.username.invalid",
                    "message" => "user.username.invalid",
                    "objectName" => "",
                    "propertyName" => "username"
                ];
            }
            if (empty($this->post('password'))) {
                $errors[] = [
                    "messageCode" => "user.password.invalid",
                    "message" => "user.password.invalid",
                    "objectName" => "",
                    "propertyName" => "password"
                ];
            }
            if (empty($this->post('firstName'))) {
                $errors[] = [
                    "messageCode" => "user.firstName.invalid",
                    "message" => "user.firstName.invalid",
                    "objectName" => "",
                    "propertyName" => "firstName"
                ];
            }

            if (empty($errors)) {
                $login_data = array();
                $login_data['username'] = $this->post('username');
                $login_data['password'] = $this->post('password');
                $login_data['password_expired'] = 0;
                $login_data['account_expired'] = 0;
                $login_data['account_locked'] = 0;
                $login_data['enabled'] = 1;
                $login_id = $this->apiModel->addLogin($login_data);
                if ($login_id !== false) {
                    $member_data = array();
                    $member_data['login_id'] = $login_id;
                    $member_data['first_name'] = ($this->post("firstName") !== null) ? $this->post("firstName") : "";
                    $member_data['last_name'] = ($this->post("lastName") !== null) ? $this->post("lastName") : "";
                    $member_data['email'] = ($this->post("email") !== null) ? $this->post("email") : "";
                    $member_data['phone'] = ($this->post("phone") !== null) ? $this->post("phone") : "";
                    $member_data['description'] = ($this->post("description") !== null) ? $this->post("description") : "";
                    $member_id = $this->apiModel->addMember($member_data);
                }
            }

            if (empty($errors)) {
                $member = $this->apiModel->getMemberByLoginId($login_id);
                $this->server = $this->oauth->getOauthServer(["password"]);
                $request = OAuth2\Request::createFromGlobals();
                $request->request['grant_type'] = "password";
                $token = $this->server->handleTokenRequest($request)->getParameters();

                $this->set_response_success([
                    "member" => $member,
                    "token" => $token
                ]);
            } else {
                $this->set_response_error([
                    "errors" => $errors
                ]);
            }
        }
    }

    function login_post()
    {
        $this->server = $this->oauth->getOauthServer(["password", "refresh_token"]);
        $request = OAuth2\Request::createFromGlobals();
        $request->request['grant_type'] = "password";
        $token = $this->server->handleTokenRequest($request)->getParameters();
        $member_data = [];
        if(!empty($token['user_id'])){
            $member_data = $this->apiModel->getMemberByLoginId($token['user_id']);
        }
        if (!empty($token['access_token'])) {
            $this->set_response_success([
                "member" => $member_data,
                "token" => $token
            ]);
        } else {
            $this->set_response_error($token);
        }
    }
    
}

 

We will continue this post with creating tests for the features that we have built.

What is Codeception?
Codeception is a modern full-stack testing framework for PHP. Inspired by BDD, it provides you an absolutely new way of writing acceptance, functional and even unit tests. Powered by PHPUnit.

Now its time to open terminal console and generate Test Cases. Here are the steps to integrate:

  1. Download Codeception
  2. Generate BootStrap files
  3. Write a Test Case for Register Api
  4. Build and Run
  5. Screenshots

1. Download and Install Codeception

Create a folder for TestCases generator. Name it as PhpTestGen.
Download composer.phar file from Composer Project.

Create a new file composer.json with below contents.

2. Generate BootStrap files

CodeCeption has a boostrap process which helps in generating basic structure for test cases.

After successfully running about command you should have below folder structure.

<img class="alignnone size-full wp-image-1805" src="http://blog.nbostech.com/wp-content/uploads/2016/01/Screen-Shot-2016-01-20-at-2.39.46-PM.png" alt="Screen Shot 2016-01-20 at 2.39.46 PM" width="766" height="410" srcset="http://blog.nbostech.com/wp-content/uploads/2016/01/Screen-Shot-2016-01-20-at-2.39.46-PM.png 766w, http://blog.nbostech.com/wp-content/uploads/2016/01/Screen-Shot-2016-01-20-at-2.39.46-PM-300×161.png 300w, http://blog.nbostech viagra prix qu.com/wp-content/uploads/2016/01/Screen-Shot-2016-01-20-at-2.39.46-PM-624×334.png 624w” sizes=”(max-width: 766px) 100vw, 766px” />

From the above screenshot we can see that Acceptance, api, functional and unit are the suites which has its respective yml file.

YML file is the configuration for each testcase we are going to write in future.

3. Write a Test Case for Register Api

Modify a yml file of API suite with below changes

And make changes in RegisterCest.php with this lines

 

4. Build and Run

There are several ways to execute bunch of tests. You can run tests from specific directory:

5. ScreenShots for success and failure

Screen Shot 2016-01-20 at 2.58.24 PM

Run the same test again, since user is already registered it will fail.Screen Shot 2016-01-20 at 2.59.44 PM

What is Swagger:

Swagger is a annotations library for generating Swagger compatible JSON documentation for your API. The resulting JSON documentation may then be utilized for internal and external user friendly documentation, API portal sandbox with Swagger UI.

You might have an existing application exposing some API in your favorite PHP Framework.
Irrespective of your framework, Swagger can be integrated using Annotation.
Refer Swagger Annotations

PreRequisite:
a) PHP command should work in your console terminal or windows command line tool.
b) Use php -c FILE_PATH_OF_php.ini in case php command gives any error

Now its time to open terminal console and generate Swagger UI. Here are the steps to integrate:

  1. Download Swagger.phar
  2. Add swagger Annotation to PHP file
  3. Generate Swagger JSON files
  4. Install Swagger UI Project
  5. Open Swagger UI

1. Download Swagger.phar

Create a folder for Swagger generator. Name it as SwaggerGenerator.
Download composer.phar file from Composer Project.
Next run below line in console :

After running above command, you should have swagger.phar in SwaggerGenerator/vendor/zircote/swagger-php/swagger.phar.

Copy that file and move it to SwaggerGenerator/swagger.phar

2. Add Swagger Annotation to PHP file

Sample PHP file with Swagger Annotation.
Add this Annotation as comments to your Controller or Class files as per your requirements.

3. Generate Swagger JSON files

Create a folder in your Apache DirectoryRoot called Swagger and a subfolder docs. Swagger/docs

4. Install Swagger UI project

Download the swagger UI code from here and place it in  Swagger/ui folder.

Edit ui/index.html and change the default  URL in javascript so that it picks up your domain.

 

5. Open Swagger UI

Go to browser and try to access “http://localhost/swagger/ui”. You will see below  screens on the browser.

Screen Shot 2016-01-12 at 3.30.41 PM

That’s right, you can launch your shopping cart website within few minutes.

Step 1:
Download the latest version of Opencart and unzip to your local folder.

Step 2:
Assuming you have bought a domain and have access to control panel details of hosting provider, for example cPanel. Upload your folder to hosting server using any FTP program. FileZilla Client is the most popular choice.

Step 3:
Create a Mysql Database using Cpanel. Note down the database details as you will be using them in next steps.

Step 4: We need to rename two config files.
a) config-dist.php to config.php
b) admin/config-dist.php to admin/config.php

Step 5:
Open your favorite browser and visit install folder.
http://yourDomainName/install

Step 6:
Proceed with installation steps. You will come across these screens.

step1

setp2

step3

scren4

 

Screen Shot 2015-12-23 at 1.16.41 PM

1.Install Apache,PHP and Mysql on your machine using the below command on the terminal

2.Open your host file in the below directory:

Edit this file to map your sites

 

3.Configure Apache
From the terminal create the new file using below command:

Type the below line in the new file:

 

4. Enable sites in apache2 and restart apache2

Let us enable your site using the below command on the terminal

Now let us restart and reload apache2 using the command:

 

Once Apache successfully restarts you’re pretty much done and ready to roll.