How to integrate Paypal to your website

Signup with https://developer.paypal.com/

Go to Sandbox -> accounts and create a test account for seller or buyer.

Then Go to Account -> My selling tools

There you can configure the settings for your website.

1. Paypal buttons : Copy the button code and paste in your page

2. Update the website preference and enter the website url so that paypal will return back to your website

After clicking Buy Now button, the params are sent to Paypal sandbox as mentioned in the form action.

<?php
$sql = "SELECT * FROM products";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $row = mysqli_fetch_assoc($resultset) ) {
?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="images/<?php echo $row['p_image']; ?>"/>
<div class="caption">
<h4 class="pull-right">Price: <?php echo $row['price']; ?></h4>
<h4>Name: <?php echo $row['p_name']; ?></h4>
</div>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<!-- Paypal business test account email id so that you can collect the payments. -->
<input type="hidden" name="business" value="<?php echo $paypal_email; ?>">
<!-- Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="<?php echo $row['p_name']; ?>">
<input type="hidden" name="item_number" value="<?php echo $row['id']; ?>">
<input type="hidden" name="amount" value="<?php echo $row['price']; ?>">
<input type="hidden" name="currency_code" value="USD">
<!-- URLs -->
<input type='hidden' name='cancel_return' value='http://localhost/paypal_integration_php/cancel.php'>
<input type='hidden' name='return' value='http://localhost/paypal_integration_php/success.php'>
<!-- payment button. -->
<input type="image" name="submit" border="0"
src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">
<img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
</form>
</div>
</div>
<?php } ?>

When the PayPal payment is successful, success message was shown otherwise failed message displayed. On success page, we will receive the transaction information with $_GET variable and insert transaction data into the database.

<?php
$item_number = $_GET['item_number'];
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];
//Get product price to store into database
$sql = "SELECT * FROM products WHERE id = ".$item_number;
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!empty($txn_id) && $payment_gross == $row['price']){
//Insert tansaction data into the database
mysqli_query($conn, "INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
$last_insert_id = mysqli_insert_id($conn);
?>
<h1>Your payment has been successful.</h1>
<h1>Your Payment ID - <?php echo $last_insert_id; ?>.</h1>
<?php
}else{
?>
<h1>Your payment has failed.</h1>
<?php
}
?>

How to store data in cloud Firestore?

Cloud Firestore is an alternative to firebase realtime database with faster query feature.

Once signed with firebase you can create project in firebase. Once the project has been created you can set Firestore as its database.

On clicking the Create database button, choose “start in test mode” and click enable.

Now a new empty cloud firestore database havebeen created. For adding the content to the database we have to create an instance.

Creating collection and documents:

To write data to the firestore database, create an instance as in below example,

val ProjectDB = FirebaseFirestore.getInstance()

Then you can add collection to your database,

Val col = projectDB.collection("collection_name")

To create a document within that collection

col.document("document_name")

Writing data in document :

db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})
.then(function() {
    console.log("Document successfully written!");
})
.catch(function(error) {
    console.error("Error writing document: ", error);
});

 

How to deploy node js code in heroku?

To use Heroku CLI it requires Git, before get starting with Heroku make sure Git was installed. Once installed, you can use the heroku command from your command shell.

In commandprompt, login with your heroku logins.

$ heroku login
Enter your Heroku credentials.
Email: **********
Password:*********

By using the below commands make sure you have installed all the requirements.

$ node --version
$ npm --version
$ git --version

Create an app on heroku and push the code to it.

$ heroku create

Usually we use the git push command to push our code from local repository to server. we can use the same to push our code to heroku.

$ git push heroku master

once deployed we can open the website using,

$ heroku open

How to create a cloud server (droplet) in digitalocean?

  • Create a new account in digital ocean and login with your email and password.
  • Click Create => Droplets from top right corner.

In the next page we have to choose the configuration options for the droplets.

  • In the first step choose an image from the 3 categories.

Distributions are images without any additional software.

Container distributers include CoreOS, Fedora etc;

One click apps are images that include preconfigured applications.

  • Then choose the size of RAM and storage space required.
  • Next, you’re required to choose the data center regions.
  • Add your SSH keys which provide more security than using a password.

In the final step, choose the number of droplets and hostname. Then click create droplet.

How to use cookies in PHP 7

COOKIE

A cookie is used to identify a user. Cookies are text files stored on the client computer and they are kept of use tracking purpose.

PHP transparently supports HTTP cookies. Browser stores this information on local machine for future use. Server script sends a set of cookies to the browser. For example name, age, or id etc.

A cookie is created with the setcookie() function. Using PHP, you can both create and retrieve cookie values.

Syntax

setcookie (name, value, expire, path, domain, secure, httponly);  

(or)

Setrawcookie(name, value, expire, path, domain, secure, httponly);  

Setrawcookie() is to send a cookie without url encoding the cookie value (for PHP 5, PHP 7)

Only the name parameter is required. All other parameters are optional.

Example Scripts

Create Cookies:

<?php
$cookie_value = 'Test_cookie';

setcookie("TestCookie", $value); /* TestCookie is Cookie Name */
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

Retrieve Cookies:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

Edit Cookies:

<?php
if(!isset($_COOKIE[$cookie_name])) {
    echo $cookie_name . "' is not set!";
} else {
    echo $cookie_name . "' is set!<br>";

   /*Again Set Cookie value to updated (New) value */

   setcookie($cookie_name, 'changed value ', time() + (86400 * 30), "/");
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

Delete Cookies:

When deleting a cookie you should assure that the expiration date is in the past.

<?php
// set the expiration date to one hour ago
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

How to Install Blocksci and Trouble shooting it.

Installing Blocksci

https://citp.github.io/BlockSci/compiling.html

Requirements :

If you don’t have enough memory it won’t install easily and

  • Cmake version should be 3.9
  • GCC and G++ should be 7 version

Complete instruction to install Cmake 3.9, GCC, G++ :

https://gist.github.com/black13/5c951d3073f8f57e9efa8e1a874b25f1

If the official manual didn’t work you could follow the below steps:

  • sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
  • sudo apt-get update
  • sudo apt install libtool autoconf libboost-filesystem-dev libboost-iostreams-dev
    libboost-serialization-dev libboost-thread-dev libboost-test-dev libssl-dev libjsoncpp-dev
    libcurl4-openssl-dev libjsoncpp-dev libjsonrpccpp-dev libsnappy-dev zlib1g-dev libbz2-dev
    liblz4-dev libzstd-dev libjemalloc-dev libsparsehash-dev python3-dev python3-pip
  • sudo apt-get install g++-7
  • install cmake 3.9 or higher instead of 3.5 (the cmake 3.5 version installed by apt-get install) (or follow this link to remove old version of cmake and get the new version.)
  • sudo update-alternatives –install /usr/bin/gcc gcc /usr/bin/gcc-7 60 –slave /usr/bin/g++ g++ /usr/bin/g++-7
  • git clone https://github.com/citp/BlockSci.git
  • cd BlockSci
  • mkdir release
  • cd release
  • cmake -DCMAKE_BUILD_TYPE=Release ..

Install make :

  • sudo make install
  • cd ..
  • sudo -H pip3 install -e blockscipy (this takes around 2 hours)

 

How to write a clean code – 6 Tips

This is a tiny post which talks about writing a clean code for a fresher who is trying hard to get success in the IT Industry.

1) Use the meaningful variable names

example
$elapsed_time_in_days;
$days_since_deletion;

2) Adding comments is one of the good habits. write comments for every code modifications.

3) Code scouting – When picking up the new code from the Internet, Take some time to read it and try to add methods or split the required functionalities.

4) Functions and sub-functions. Make sure functions are doing its job that its meant to do.

5) Testing – Unit testing is very important, testing the functionality and isolation intensively.

6) Final tips are Practice, Practice, Practice.

Goog Luck!

What is Elasticsearch and how it works?

Elasticsearch

Elasticsearch is an open-source, distributed, multi-tenant-capable search engine. The term multi-tenant refers to the architecture in which a single software runs on a server and serve more than one user at the same time.

SQL database managements systems aren’t really designed for full-text searches also they will take around 10 sec to list out the results were as Elastic search will perform a full-text search and return the results within few milliseconds.

Elastic search is based on Lucene,which is a open source full-text search engine library written in Java.

Indexing and Retrieving data :

Indexing :

The act of storing data in Elasticsearch is called indexing. In Elastic search each data was stored in simple JSON document. Data can be stored using HTTP PUT request.

Elasticsearch cluster can contain multiple indices which are similar to the databases in SQL. Each indices may contain multiple types. These types hold multiple documents and each document has multiple fields.

PUT /index/type/Id

Example :

Lets imagine a school record of all students.

Here the Index (Indices) may be Class-11, Class-12

Type will be as Student. Here the each student data was stored with the ID of the particular student. The files stored under this type may contains fields like : Name, Register number, Father Name etc.

eg: PUT Class-11 / Student / 1

Retrieving :

Retrieving a document is easy in elastic search where we can simple execute “HTTP Get” request and specify the address of the document.

GET /index/type/Id

eg: Class-11 / Student / 1

Every feature of Elasticsearch is exposed as a REST API:

Index API: Used to document the index.

Get API: Used to retrieve the document.

Search API: Used to submit your query and get a result.

Put Mapping API: Used to override default choices and define the mapping.

Filtering Queries and Aggregations :

Elasticsearch has a single set of components called queries, which can be mixed and matched in endless combinations.

This single set of components can be used in two contexts:

  1. Filtering Context
  2. Query Context

When used in filtering context, the query is said to be a “non-scoring” or “filtering” query.

When used in a querying context, the query becomes a “scoring” query.

Non-Scoring Query is to filter the data which matches with the given query.

A scoring query calculates how relevant each document is to the query, and assigns it a relevance _score, which is later used to sort matching documents by relevance.

Aggregations :

The query returns a certain subset of documents, and the aggregation operates on those documents.

Installing Litecoin cryptocoin data and deploying its blockchain server in CentOS7

Installation
https://download.litecoin.org/litecoin-0.16.0/linux/litecoin-0.16.0-x86_64-linux-gnu.tar.gz

Download the above tar file and extract it using following commands
tar xvf litecoin-0.16.0-x86_64-linux-gnu.tar.gz

Starting a litecoin server
Here, first time you need to reindex the whole chain using -reindex command
First time command: ./litecoind –txindex -daemon -reindex

litecoind -server -txindex -daemon -rpc -rpcbind=0.0.0.0 -rpcuser=theone -rpcpassword=pass123 -rpcport=9332

The above command lets you to download the blocks continously and you can access the server private data using RPC API calls.

Stopping a litecoin server
litecoind stop
if the above command doesnt work
killall -9 litecoind

Litecoin reference (params)
https://litecoin.info/index.php/Litecoin.conf

It should automatically download the blocks in the root
/root/.litecoin/..

Will keep you updated with more commands.

 

How to Secure Your Social Media Accounts

According to a recent study it was found that we are spending approximately 2 hours in social media every day. The most popular social media platforms have billions of users, and the number keeps getting bigger every year.

Previously the social media platform was considered as a medium to get connected with other people. Now enterprises see them as a valid advertising tools. We can see most android applications are using major social media accounts to validate user identity.

Here are some tips for keeping your accounts secure:

Personal Accounts :

  1. Close your accounts that you’re not using. Hackers can leverage these forgotten account and access other accounts linked to it, like your email,mobile number etc.
  1. Before signing in to any application via your social media login, kindly check if this type of access is necessary.
  1. Please change your password often. And make sure it is somewhat complex or unique.
  1. Keep your mobile app updated. Latest versions with updated security features may protect you from the newest known threats.
  1. If any links or mails seems to be spam kindly report the account as spam. If enough people take the same action, networking service can remove the account.
  1. Use unique email (not your personal email) for all social media account. If possible, create a whole new email specifically for social media accounts so that if you are compromised, the hackers won’t have access to any valuable information.

    Corporate Accounts :

    Now-a-days social media forms the better marketing place for enterprises. They use company’s social media to promote their own brand, gain followers, or even spread a specific message.

  1. Monitor your social media regularly.
  1. Limit access to only the necessary people.
  1. Make sure you won’t share any confidential details in the social media pages.
  1. Always be aware aware of the latest security solutions.
  1. Change your password frequently.