How To Install, Setup And Implement NodeJS In PHP Application

What Is NodeJS?

Typically in web response paradigm, the client always initiates communication, but with the help of NodeJS now both the client and server can initiate communication, allowing them to exchange data freely.

In simple words, after a database update the client needs to request the server to get the latest data. But using NodeJS, a client can send the updated data to NodeJS and the NodeJS will distribute the data across all the clients. So, no need to initiate request by each client to the server to get the latest data.

Where We Can Use NodeJS?

Below are the few examples where you can get the best out of Node.js,

  • A counter which updates after a record insert into database.
  • Show real-time activity like Twitter or Facebook.
  • Implement Desktop notification to notify users about what others are doing.
  • You can build a chatting tool using the non-blocking, event-driven I/O paradigm of NodeJS

Install And Setup NodeJS

  1. Install NodeJS and NPM
  2. Install socket.io using NPM
  3. Install Forever

Run the below notification.js file forever using the “Forever”. (it should not stop)

notification.js

var fs = require('fs');
/* If you are using SSL, uncomment the below lines*/
/*
var options = {
    key: fs.readFileSync('/var/www/html/YOUR_CERTIFICATE_FOLDER/your_project_key.key'),
    cert: fs.readFileSync('/var/www/html/YOUR_CERTIFICATE_FOLDER/your_project_crt.crt'),
    ca: fs.readFileSync('/var/www/html/YOUR_CERTIFICATE_FOLDER/your_project_ca-bundle.ca-bundle')
};
var app = require('https').createServer(options, handler);
*/

var app = require('http').createServer(handler); // For non-ssl server
var io = require('socket.io').listen(app);
app.listen(3002);
function handler (req, res) {
	res.writeHead(200);
	res.end("Welcome to socket.io.");
}
/** This section is for receiving and sending message **/
var Room;
io.sockets.on('connection', function (socket) {
	socket.on('subscribeTo', function (data) {
		if(Room){
			socket.leave(Room);
		}
		Room = data.channel;
		console.log('Connecting client to: '+data.channel);
		socket.join(data.channel);
	});
	socket.on('iotoserver', function (data) {
		console.log('here we are in action event and data is: \n-----------------------------------------------------');
		//var dataJSON = JSON.parse(data);
		//socket.broadcast.emit(dataJSON.channel, { message: 'A new socket added and sending message.' });
		socket.broadcast.to(data.channel).emit('iotoclient', { message: data.message });
		//io.sockets.in('game').emit('message', 'cool game');
		console.log(data);
	});
});

NOTE: Your Node.js should run with the port “3002”. Try to use another sub-domain/domain to call your Node.js server. Another server is always a good option.

Implement NodeJS In Your Application

Use Elephant.io (a socket.io client) to send message to NodeJS.
Get the ElephantIO package from, https://github.com/Wisembly/elephant.io/tree/master/src
You need the Client.php and the AbstractPayload.php file only.

<?php
use ElephantIO\Client as ElephantIOClient;
include("ElephantIO/Client.php");

$elephant = new ElephantIOClient('http://www.your-node-server.com:3002', 'socket.io', 1, false, false, true);
$elephant->setHandshakeTimeout(1000);
$elephant->init();
$elephant->send(
ElephantIOClient::TYPE_EVENT, null, null, json_encode(array('name' => 'iotoserver', 'args' => array('channel' => 'my_first_channel', 'message' => 'my message to all the online users')))
	);
$elephant->close();
?>

Put this JavaScript in the page, where you want to receive the real-time notification

<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script>
try{
  var client = io.connect('http://www.your-node-server.com:3002');
  
  client.on('connect',function (data) {
  	client.emit('subscribeTo', { channel: 'my_first_channel' });
  });
  
  client.on('iotoclient', function (data) {
    alert(data.message);
  });
} catch(e){
	console.log('Socket ERROR\n');
	console.log(e);
}
</script>

See Also: Creating a custom handler session in CakePHP 2.x

Are you looking to Install, setup and implement NodeJS in your PHP application? We are here to help you. We have experienced NodeJS developers to provide all types of JavaScript solutions. Let’s discuss

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

How To Integrate PayPal In PHP

To accept online payments through your website you would need a payment gateway. There are numerous payment gateways that can be implemented to your website; however you will need to choose the best for your PHP application. “PayPal” is one of the most renowned payment platforms that offers the best in class services as well as secure payment transaction. One of the best features of PayPal is that it facilitates developers to check-out the integration on merchant sites.

From a developer’s point of view, PayPal API is a simple, user friendly and versatile which facilitates them to avoid the PCI burden of having credit card details to be passed through their servers. PayPal is also the most secure platform that takes care of all the money transactions for the users.

Integrating PayPal in Your Website

The first thing we need is a Sandbox Credential and API Credentials. This can be availed using the following steps:

  • Create a Business account in “https://developer.paypal.com/” in order to access the Sandbox account.
  • Log into your business account; move to the ‘Application Tab’ and create a Sandbox test account for developers to check-out the PayPal integration.
  • For PayPal payment pro services, you can use this Sandbox Credentials for logging into “https://www.sandbox.paypal.com/”
  • If you want to login to your sandbox account you have to first log into your developer account.

Steps to Implement ‘the work’ in Your Site

  • In PayPal payment pro ‘the work’ is done through API call.
  • In your code you will have to implement a function i.e. ‘PPHttpPost(methodname,str);’
  • ‘methodname’ specifies the name of the API you want to call i.e. ‘CreateRecurringPaymentsProfile’, ‘GetTransactionDetails’ etc.

There are numerous other methods for the integration which can be availed form the PayPal developer site:  https://developer.paypal.com/webapps/developer/docs/classic/api/

Under ‘Merchant’ API you would find a list of functions that can be performed by PayPal website pro.
Clicking on NVP link of each function you can view the methods and the required parameters for that method.

Second Parameter in the string; which is passed to the API, is for getting the response. It includes all the parameters that have to be passed e.g.

[sourcecode]$str = "&TOKEN = $token&AMT = $paymentAmount&CURRENCYCODE = $currencyID&PROFILESTARTDATE =
$startDate";[/sourcecode]

 

[sourcecode]$nvpStr  .= "&BILLINGPERIOD = $billingPeriod&BILLINGFREQUENCY = $billingFreq&CREDITCARDTYPE = $CREDITCARDTYPE&ACCT = $ACCT&EXPDATE = $EXPDATE&CVV2 = $CVV2&EMAIL = $EMAIL&STREET = $STREET&CITY = $CITY&STATE = $STATE&COUNTRYCODE = $COUNTRYCODE&ZIP = $ZIP&FIRSTNAME = $FIRSTNAME&LASTNAME = $LASTNAME&DESC = $DESC&FAILEDINITAMTACTION = $FAILEDINITAMTACTION&INITAMT = $INITAMT";[/sourcecode]

Note: This string might differ for different methods but the structure is similar.

  • This function returns an array having one key as ACK.
  • The value of this key specifies the FAILURE and SUCCESS of the function.

If ACK is a failure then the returned array contains following error message.

[sourcecode]function PPHttpPost($methodName, $nvpStr_) {

$APIUserName = urlencode(‘API USERNAME’);

$APIPassword = urlencode(‘API PASSWORD’);

$APISignature = urlencode(‘API SIGNATURE’);

$APIEndpoint = "https://api-3t.sandbox.paypal.com/nvp"; //sandbox url.

$version = urlencode(‘51.0’);

//setting the curl parameters.

$choice = curl_init();

curl_setopt($choice, CURLOPT_URL, $APIEndpoint);

curl_setopt($choice, CURLOPT_VERBOSE, 1);

//turning off the server and peer verification(TrustManager Concept).

curl_setopt($choice, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($choice, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($choice, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($choice, CURLOPT_POST, 1);

//NVPRequest for submitting to server

$nvprequest = "METHOD=$methodName&VERSION=$version&PWD=$APIPassword&USER=$APIUserName&SIGNATURE=$APISignature";

// setting the nvprequest as POST FIELD to curl

curl_setopt($choice, CURLOPT_POSTFIELDS, $nvprequest);

//getting response from server

$httpResponse = curl_exec($choice);

if(!$httpResponse) {

exit("$methodName failed: ".curl_error($choice).'(‘.curl_errno($choice).’)’);

}

// Here Extract the RefundTransaction response details

$httpResponseArr = explode("&", $httpResponse);

$httpParsedResponseArr = array();

foreach ($httpResponseArr as $i => $value) {

$tmpAr = explode("=", $value);

if(sizeof($tmpAr) > 1) {

$httpParsedResponseArr[$tmpAr[0]] = $tmpAr[1];
}
}

if((0 == sizeof($httpParsedResponseArr)) || !array_key_exists(‘ACK’, $httpParsedResponseArr)) {
exit("Invalid HTTP Response for POST request($nvprequest) to $APIEndpoint.");
}
return $httpParsedResponseArr;
}[/sourcecode]

Setting of IPN URL

IPN stands- Instant Payment Notification

Under the Profile tab of the sandbox site there is an ‘Instant Payment Notification preference’ link. Set the IPN URL from the link.

Conclusion:

This notification is sent from server to server when any transaction is done in PayPal. To capture this transaction we can set URL in Instant Payment Notification preferences page and manage those transaction information.