How to connect bitcoin payment gateway to onion website?

x_mode

Carder
Messages
42
Reputation
0
Reaction score
25
Points
8
Hello everyone.
I build a onion online store and I want to connect my store a gateway for receive crypto.
How can I add a balance system & payment system in crypto to onion website?
If anybody know something about it, it will be cool of you help me.
or if you can send me something read or view it will be good also.
 

Mutt

Professional
Messages
1,057
Reputation
7
Reaction score
595
Points
113
METHOD 1

Instructions: How to add payment in bitcoins on the site
Advertising network team about the choice of service and the nuances of accepting payments in cryptocurrency.
Bitcoin is gaining more and more attention, and blockchain technologies predict a bright future. Our company, for example, decided to provide customers with an opportunity to buy traffic for cryptocurrency and connected a payment method using bitcoin.

The current fashion for cryptocurrencies has a lot of reasonable advantages:
  1. Safe online payments: there is no fraud or chargebacks. The network is designed in such a way that the sent payment cannot be returned, the reliability of the transaction is confirmed by users all over the world, and each transaction is encrypted.
  2. Favorable commissions: the cost of making a payment does not exceed 1%. And the larger the transfer amount, the less loss.
  3. Anonymity: banks do not control clients' funds - no one has the right to block a transaction or add an extra commission.
  4. Unlimited payments: transactions are carried out in unlimited volumes, which is not allowed by other means of payment.

There are many services that allow you to accept bitcoins and other currencies. Only a small part of them:
We connected payment through the Bitaps API, because it turned out to be easier to do it through it. If Blockchain needs to write an application and wait for approval for three banking days, then here you can initially connect on your own. The API contains everything you need to do this.

Acceptance of payments
When creating an account for a client, it is necessary to generate and monitor a unique address (temporary wallet) for each payment. As soon as the payment is confirmed by the network, the API server transfers bitcoins from the temporary wallet to the specified wallet (your own or corporate, where it will be convenient for you to receive funds).

Each service has its own API, but the scheme looks approximately the same:
  • Generate a payment by using a special link and passing the parameters.
  • Create a Bitcoin merchant address to which money will be sent.
  • Create a link of your system (callback), which will be called upon confirmation of payment.
  • Specify the number of accepted confirmations of payment in the Bitcoin network (optional field, by default - 3).
  • Define the network commission level (optional field, by default - low). The higher it is, the faster the transfer will take place.

As a result, a generated address for receiving payment, a payment code and an invoice is obtained. You use the code in the database to record, sort, or search for payment information. The invoice can be sent to the buyer or used for a payment form.
After funds are credited to the specified account, confirmation occurs in the Bitcoin network. For each confirmation, a callback is sent and parameters are passed to identify the payment. Upon receipt of the last confirmation, the customer's order or service must be completed. The amount is transferred to Satoshi - the smallest part of Bitcoin.
For conversion, use the methods of obtaining currency rates. The course changes frequently, so get it at the time of enrollment and make a conversion.

Number of confirmations
The required number of confirmations depends on the risk model, clients and amounts. If you trust your customers, then accept payments without confirmation or with one confirmation. For small transfers, three confirmations are sufficient.

Six confirmations are mathematically impossible to counterfeit without 51% of the processing power of the network. The more confirmations are required, the greater the commission and the waiting time. On average, the payment takes 15-20 minutes, and the payment for the client will look like this:
  • The choice of a product or service.
  • Issuing an invoice to the client (displaying the wallet number and the amount required for payment on the page).
  • Transfer of funds by the client.
  • Waiting for three confirmations and completing an order or service (in our case, this is replenishing the account of an advertising cabinet).

Important notes
  1. In addition to the commission of the payment acceptance service, there is a bitcoin commission for transferring from a temporary wallet to the one you specified. Unfortunately, it is not written about this anywhere, so we recommend not to make small payments. The minimum top-up is set in our network - 1000 rubles.
  2. The bitcoin rate, like other cryptocurrencies, changes significantly every second. We recommend recalculating the exchange rate and withdrawing bitcoin into real currency as often as possible. Of course, this works for those cases if it is important for you to work with real currency, converting bitcoin at the rate.
  3. Not every blockchain service allows you to use an API to accept payments without confirmation. The criteria for admission to this or that service are unknown, so apply to several places.
  4. Each service has a different commission for accepting payments. Study each in detail before deciding to connect.
  5. Do not set the number of required confirmations for payment above six. This will lead to longer customer wait times and negative reviews. Three is enough for safety.
  6. At a low commission level, funds transfer takes thirty minutes. If you want to save money for buyers, do not increase the commission level.

METHOD 2

Do it yourself cryptocurrency payments acceptance
From time to time I see questions about how to accept Bitcoin payments on my website without using third-party services. It is quite simple, but it must be borne in mind that there are pitfalls.
In this article I will try to describe in as much detail as possible, without focusing on any programming language, how to accept Bitcoin payments (and, if desired, Litecoin, Dash, Bitcoin Cash, Steep, ONION, etc.), starting with expanding a full node and ending with a payment check.

Prerequisites
It is assumed that you have a site hosted on a VPS, to which you have root access, and are also willing to spend $ 15 + to pay for the server for the wallet.

Installing a wallet
The first step is to allocate a separate server to host the wallet. Why a separate server? A separate server will reduce the risk of an attacker withdrawing all your funds if the main site is compromised. Well, do not forget that blockchain storage requires a lot of disk space (~ 150Gb of disk space, etc. - see the link for details).
What are the cheap server options? There are a lot of them, in my opinion the most adequate - servers from hetzner.de or chipcore.com. On chipcore.com, for example, you can take a dedicated one with a 500Gb disk (enough for BTC and a couple more blockchains) for about $ 17. If you know something cheaper - write in the comments, it's very interesting (I think, not only to me).
After you have made a meaningful decision that you want to accept cryptocurrencies on your website and have bought a server (or used an existing one), you need to install a bitcoin node.
Any suitable operating system must be installed on the server, the easiest option is Ubuntu 16.10 (yes, in fact, this is not the best choice, it is better to install 16.04 or wait for 18.04 and wait a couple of months for stabilization). As a rule, it makes no sense to bother with disk partitioning and you can safely use 2-4Gb on swap and let the rest on the root partition (/ or root).
After the server is available, the first thing to do is to disable password authentication and configure ssh key authentication. It's pretty easy to do, there is a good description from DigitalOcean.
After the server is configured, a couple of commands are enough to start a full-fledged wallet node

Install bitcoind
Code:
sudo apt-add-repository ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install bitcoind

That's all it takes to set up a node.

Bitcoind setup
The first step is to create a user bitcoin:
Code:
adduser bitcoin
# everywhere we select standard values and specify some complex password

and create service directories:
Code:
mkdir -p /etc/bitcoin
chown bitcoin: /etc/bitcoin
mkdir -p /run/bitcoind
chown bitcoin: /run/bitcoind
mkdir -p /var/lib/bitcoind
chown bitcoin: /var/lib/bitcoind

Now the smallest thing remains - to correctly configure the node to receive JSON RPC requests.
The minimal config will look like this:
Code:
rpcuser=USERNAME
rpcpassword=PASSWORD
rpcbind=127.0.0.1
rpcallowip=127.0.0.1/32

It must be put at the address /etc/bitcoin/bitcoin.conf. And don't forget to set the correct owner:
Code:
chown bitcoin: /etc/bitcoin/bitcoin.conf

Important: using USERNAME and PASSWORD is a deprecated method and a little insecure. It is more correct to use rpcauth, an example can be found here.
Further, it is enough to configure the systemd service to start the node (including after a reboot).
To do this, you can simply copy the unit file located at the address in the directory /etc/systemd/system/:
Code:
wget https://raw.githubusercontent.com/bitcoin/bitcoin/master/contrib/init/bitcoind.service[/URL] -O /etc/systemd/system/bitcoind.service

Then launch it and configure autorun:
Code:
systemctl daemon-reload
systemctl start bitcoind
systemctl enable bitcoind

Now you can check the efficiency of the node:
Code:
curl --data-binary '{"jsonrpc": "1.0", "method": "getinfo", "params": [] }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/

If everything is ok, the following message will be returned in response:
Code:
{"result":{"balance":0.000000000000000,"blocks":59952,"connections":48,"proxy":"","generate":false,
"genproclimit":-1,"difficulty":16.61907875185736},"error":null,"id":"curltest"}

Setting up the main site server
It remains only to configure the server on which your site is located.
The safest and easiest way to make the wallet API available on the backend is to pass an ssh tunnel through the systemd service (or any other init service). In the case of using systemd, the configuration of the service is as simple as possible:
Code:
[Unit]
Description=SSH Tunnel BTC
After=network.target

[Service]
Restart=always
RestartSec=20
User=tunnel
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -L 127.0.0.1:8332:127.0.0.1:8332 tunnel@YOUR_SERVER_IP

[Install]
WantedBy=multi-user.target

This configuration needs to be placed along the path /etc/systemd/system/sshtunnel-btc.service.
After that, we put the service into autostart and run:
Code:
systemctl enable sshtunnel-btc.service
systemctl start sshtunnel-btc.service

To check, you can knock on the localhost port and check that everything is ok:
Code:
curl --data-binary '{"jsonrpc": "1.0", "method": "getinfo", "params": [] }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/

API documentation
The most convenient way to get acquainted with the list of all methods is by the link.
It is very easy to call them even through curl, we have already used an example of a request earlier when getting information about a node using the getinfo method.
There are two options for passing parameters - an array or a dictionary.
Below you can see examples of a request to get a new address with the transfer of parameters by an array and a dictionary:
Code:
# array
curl --data-binary '{"jsonrpc": "1.0", "method": "getnewaddress", "params": ["test"] }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/
# object
curl --data-binary '{"jsonrpc": "1.0", "method": "getnewaddress", "params": {"account": "test"} }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/

Simple API client
For use, it is convenient to write a simple wrapper with the functions we need (or use an existing library for your language). Example for ruby:
Code:
class Btc
class BtcError < StandardError; end

SUPPORTED_METHODS = %w(get_new_address get_addresses_by_account get_info get_net_totals get_balance get_received_by_address send_to_address list_transactions get_transaction)

class << self
def method_missing(method_name, *args)
if SUPPORTED_METHODS.include?(method_name.to_s)
send_request(method_name.to_s, args.empty? ? nil : args)
else
super
end
end

def respond_to_missing?(method_name, _include_private = false)
SUPPORTED_METHODS.include?(method_name) || super
end

protected

def host
ENV["HOST"] || "http://username:[email protected]:8332"
end

private

def send_request(method, params = nil)
uri = URI.parse(host)
request = Net::HTTP::Post.new(uri)
request.basic_auth uri.user, uri.password
request.body = JSON.dump(
jsonrpc: "1.0",
method: method.tr("_", ""),
params: params
)

req_options = { use_ssl: uri.scheme == "https" }

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end

begin
result = JSON.parse(response.body)
rescue JSON::ParserError
raise BtcError.new(response.body)
end
raise BtcError.new(result["error"].to_json) if result["error"]

result["result"].is_a?(Hash) ? result["result"].deep_symbolize_keys : result["result"]
end
end
end

After that, you can conveniently use it in something like this:
Code:
# run with HOST env variable (HOST=http://username:password@localhost:8332)
Btc.get_info
# => {result: {...}}

An analogous example for node.js:
Code:
var http = require('http');

function BtcApi(host, port, username, password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
};
BtcApi.methods = [
'getNewAddress',
'getAddressesByAccount',
'getInfo',
'getNetTotals',
'getBalance',
'getReceivedByAddress',
'sendToAddress',
'listTransactions',
'getTransaction',
];
BtcApi.prototype.sendRequest = function(method, params, callback) {
if (BtcApi.methods.indexOf(method) === -1) {
throw new Error('wrong method name ' + method)
};

if (callback == null) {
callback = params;
};

var body = JSON.stringify({
jsonrpc: '1.0',
method: method.toLowerCase(),
params: params,
});

var auth = 'Basic ' + Buffer.from(this.username + ':' + this.password).toString('base64');

var options = {
host: this.host,
port: this.port,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': auth
},
};

var request = http.request(options, function (response) {
var result = '';
response.setEncoding('utf8');

response.on('data', function (chunk) {
result += chunk;
});

// Listener for intializing callback after receiving complete response
response.on('end', function () {
try {
callback(JSON.parse(result));
} catch (e) {
console.error(e);
callback(result);
}
});
});

request.write(body)
request.end()
};

for (var i = 0; i < BtcApi.methods.length; i++) {
BtcApi.prototype[BtcApi.methods[i]] = function (method) {
return function (params, callback) {
this.sendRequest(method, params, callback)
}
}(BtcApi.methods[i])
}

module.exports = BtcApi

Which can be used something like this:
var BtcApi = require('./btc');

var client = new BtcApi('127.0.0.1', 8332, 'username', 'password');

client.listTransactions({ count: 1 }, function (response) {
console.log('response: ', JSON.stringify(response));
});

// {"result":[{...}]}

It's even easier for Python - the official way is to use:
Code:
from jsonrpc import ServiceProxy

access = ServiceProxy("http://user:[email protected]:8332")
access.getinfo()

Actually, there are no problems with PHP either (it is recommended to use http://jsonrpcphp.org/ ):
Code:
require_once 'jsonRPCClient.php';

$bitcoin = new jsonRPCClient('http://user:[email protected]:8332/');

echo "<pre>\n";
print_r($bitcoin->getinfo()); echo "\n";
echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";
echo "</pre>";

A good collection of documentation can be found here .
The examples above are slightly modified versions of those listed here.

Integration with the site
The only part left is to set up the processing of receiving payments and generating addresses for replenishment.

The process of integrating the acceptance of crypto payments looks something like this:
  • When a user requests a payment, we show him the address where to transfer funds
  • In the background (the easiest option is by cron), we check the list of wallet transactions and, when a new one arrives, we add funds / change the payment status.
To generate receiving addresses, you can use several different approaches - creating a new address for each deposit, or using a permanent address for the user's account.
The first option is safer (since it is more difficult to track repeated payments by the payer) and simple, but it can become a problem when using not very powerful hardware (each generated address increases the load on the node, but this becomes noticeable only from several million addresses).
The second option is more convenient if users have to register and pay frequently, but at the same time it is less secure (for example, you can track all receipts of funds to a user account).
To generate a top-up address, call the getnewaddress method, which will return a new top-up address in response. For convenience, you can pass an account as a parameter (account) to which the created address will be linked. Sometimes it can be handy to view transactions for a specific user.
Several methods are suitable for checking the balance. The easiest way is to create a record in the database for each generated address for replenishment, and then check for each of the records through the method of getreceivedbyaddressreceipt of funds (not the most productive option, but suitable for most situations).
Another good option would be to receive information via listtransactions about the latest operations and for them already look for a user who receives balances. Which type of implementation to use is up to you.
An important point when checking transactions is to correctly indicate the number of confirmations to protect against various attacks. For most cryptocurrencies, they can usually be found in the White Paper.
For bitcoin, the currently recommended value is 6 confirmations for small amounts. Here everything is well documented.
I will not write code examples here, because it strongly depends on the technology used.

Conclusion
I also wanted to write about the integration of other wallets, in more detail about the requirements for the server and about the withdrawal, how to accept payments if the site is not hosted on a VPS with root access, etc., but I realized that the article was already big, so if it will be interesting - I'd better publish it in one of the next articles.
 

x_mode

Carder
Messages
42
Reputation
0
Reaction score
25
Points
8
METHOD 1

Instructions: How to add payment in bitcoins on the site

Advertising network team about the choice of service and the nuances of accepting payments in cryptocurrency.
Bitcoin is gaining more and more attention, and blockchain technologies predict a bright future. Our company, for example, decided to provide customers with an opportunity to buy traffic for cryptocurrency and connected a payment method using bitcoin.

The current fashion for cryptocurrencies has a lot of reasonable advantages:
  1. Safe online payments: there is no fraud or chargebacks. The network is designed in such a way that the sent payment cannot be returned, the reliability of the transaction is confirmed by users all over the world, and each transaction is encrypted.
  2. Favorable commissions: the cost of making a payment does not exceed 1%. And the larger the transfer amount, the less loss.
  3. Anonymity: banks do not control clients' funds - no one has the right to block a transaction or add an extra commission.
  4. Unlimited payments: transactions are carried out in unlimited volumes, which is not allowed by other means of payment.

There are many services that allow you to accept bitcoins and other currencies. Only a small part of them:
We connected payment through the Bitaps API, because it turned out to be easier to do it through it. If Blockchain needs to write an application and wait for approval for three banking days, then here you can initially connect on your own. The API contains everything you need to do this.

Acceptance of payments
When creating an account for a client, it is necessary to generate and monitor a unique address (temporary wallet) for each payment. As soon as the payment is confirmed by the network, the API server transfers bitcoins from the temporary wallet to the specified wallet (your own or corporate, where it will be convenient for you to receive funds).

Each service has its own API, but the scheme looks approximately the same:
  • Generate a payment by using a special link and passing the parameters.
  • Create a Bitcoin merchant address to which money will be sent.
  • Create a link of your system (callback), which will be called upon confirmation of payment.
  • Specify the number of accepted confirmations of payment in the Bitcoin network (optional field, by default - 3).
  • Define the network commission level (optional field, by default - low). The higher it is, the faster the transfer will take place.

As a result, a generated address for receiving payment, a payment code and an invoice is obtained. You use the code in the database to record, sort, or search for payment information. The invoice can be sent to the buyer or used for a payment form.
After funds are credited to the specified account, confirmation occurs in the Bitcoin network. For each confirmation, a callback is sent and parameters are passed to identify the payment. Upon receipt of the last confirmation, the customer's order or service must be completed. The amount is transferred to Satoshi - the smallest part of Bitcoin.
For conversion, use the methods of obtaining currency rates. The course changes frequently, so get it at the time of enrollment and make a conversion.

Number of confirmations
The required number of confirmations depends on the risk model, clients and amounts. If you trust your customers, then accept payments without confirmation or with one confirmation. For small transfers, three confirmations are sufficient.

Six confirmations are mathematically impossible to counterfeit without 51% of the processing power of the network. The more confirmations are required, the greater the commission and the waiting time. On average, the payment takes 15-20 minutes, and the payment for the client will look like this:
  • The choice of a product or service.
  • Issuing an invoice to the client (displaying the wallet number and the amount required for payment on the page).
  • Transfer of funds by the client.
  • Waiting for three confirmations and completing an order or service (in our case, this is replenishing the account of an advertising cabinet).

Important notes
  1. In addition to the commission of the payment acceptance service, there is a bitcoin commission for transferring from a temporary wallet to the one you specified. Unfortunately, it is not written about this anywhere, so we recommend not to make small payments. The minimum top-up is set in our network - 1000 rubles.
  2. The bitcoin rate, like other cryptocurrencies, changes significantly every second. We recommend recalculating the exchange rate and withdrawing bitcoin into real currency as often as possible. Of course, this works for those cases if it is important for you to work with real currency, converting bitcoin at the rate.
  3. Not every blockchain service allows you to use an API to accept payments without confirmation. The criteria for admission to this or that service are unknown, so apply to several places.
  4. Each service has a different commission for accepting payments. Study each in detail before deciding to connect.
  5. Do not set the number of required confirmations for payment above six. This will lead to longer customer wait times and negative reviews. Three is enough for safety.
  6. At a low commission level, funds transfer takes thirty minutes. If you want to save money for buyers, do not increase the commission level.

METHOD 2

Do it yourself cryptocurrency payments acceptance

From time to time I see questions about how to accept Bitcoin payments on my website without using third-party services. It is quite simple, but it must be borne in mind that there are pitfalls.
In this article I will try to describe in as much detail as possible, without focusing on any programming language, how to accept Bitcoin payments (and, if desired, Litecoin, Dash, Bitcoin Cash, Steep, ONION, etc.), starting with expanding a full node and ending with a payment check.

Prerequisites
It is assumed that you have a site hosted on a VPS, to which you have root access, and are also willing to spend $ 15 + to pay for the server for the wallet.

Installing a wallet
The first step is to allocate a separate server to host the wallet. Why a separate server? A separate server will reduce the risk of an attacker withdrawing all your funds if the main site is compromised. Well, do not forget that blockchain storage requires a lot of disk space (~ 150Gb of disk space, etc. - see the link for details).
What are the cheap server options? There are a lot of them, in my opinion the most adequate - servers from hetzner.de or chipcore.com. On chipcore.com, for example, you can take a dedicated one with a 500Gb disk (enough for BTC and a couple more blockchains) for about $ 17. If you know something cheaper - write in the comments, it's very interesting (I think, not only to me).
After you have made a meaningful decision that you want to accept cryptocurrencies on your website and have bought a server (or used an existing one), you need to install a bitcoin node.
Any suitable operating system must be installed on the server, the easiest option is Ubuntu 16.10 (yes, in fact, this is not the best choice, it is better to install 16.04 or wait for 18.04 and wait a couple of months for stabilization). As a rule, it makes no sense to bother with disk partitioning and you can safely use 2-4Gb on swap and let the rest on the root partition (/ or root).
After the server is available, the first thing to do is to disable password authentication and configure ssh key authentication. It's pretty easy to do, there is a good description from DigitalOcean.
After the server is configured, a couple of commands are enough to start a full-fledged wallet node

Install bitcoind
Code:
sudo apt-add-repository ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install bitcoind

That's all it takes to set up a node.

Bitcoind setup
The first step is to create a user bitcoin:
Code:
adduser bitcoin
# everywhere we select standard values and specify some complex password

and create service directories:
Code:
mkdir -p /etc/bitcoin
chown bitcoin: /etc/bitcoin
mkdir -p /run/bitcoind
chown bitcoin: /run/bitcoind
mkdir -p /var/lib/bitcoind
chown bitcoin: /var/lib/bitcoind

Now the smallest thing remains - to correctly configure the node to receive JSON RPC requests.
The minimal config will look like this:
Code:
rpcuser=USERNAME
rpcpassword=PASSWORD
rpcbind=127.0.0.1
rpcallowip=127.0.0.1/32

It must be put at the address /etc/bitcoin/bitcoin.conf. And don't forget to set the correct owner:
Code:
chown bitcoin: /etc/bitcoin/bitcoin.conf

Important: using USERNAME and PASSWORD is a deprecated method and a little insecure. It is more correct to use rpcauth, an example can be found here.
Further, it is enough to configure the systemd service to start the node (including after a reboot).
To do this, you can simply copy the unit file located at the address in the directory /etc/systemd/system/:
Code:
wget https://raw.githubusercontent.com/bitcoin/bitcoin/master/contrib/init/bitcoind.service[/URL] -O /etc/systemd/system/bitcoind.service

Then launch it and configure autorun:
Code:
systemctl daemon-reload
systemctl start bitcoind
systemctl enable bitcoind

Now you can check the efficiency of the node:
Code:
curl --data-binary '{"jsonrpc": "1.0", "method": "getinfo", "params": [] }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/

If everything is ok, the following message will be returned in response:
Code:
{"result":{"balance":0.000000000000000,"blocks":59952,"connections":48,"proxy":"","generate":false,
"genproclimit":-1,"difficulty":16.61907875185736},"error":null,"id":"curltest"}

Setting up the main site server
It remains only to configure the server on which your site is located.
The safest and easiest way to make the wallet API available on the backend is to pass an ssh tunnel through the systemd service (or any other init service). In the case of using systemd, the configuration of the service is as simple as possible:
Code:
[Unit]
Description=SSH Tunnel BTC
After=network.target

[Service]
Restart=always
RestartSec=20
User=tunnel
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -L 127.0.0.1:8332:127.0.0.1:8332 tunnel@YOUR_SERVER_IP

[Install]
WantedBy=multi-user.target

This configuration needs to be placed along the path /etc/systemd/system/sshtunnel-btc.service.
After that, we put the service into autostart and run:
Code:
systemctl enable sshtunnel-btc.service
systemctl start sshtunnel-btc.service

To check, you can knock on the localhost port and check that everything is ok:
Code:
curl --data-binary '{"jsonrpc": "1.0", "method": "getinfo", "params": [] }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/

API documentation
The most convenient way to get acquainted with the list of all methods is by the link.
It is very easy to call them even through curl, we have already used an example of a request earlier when getting information about a node using the getinfo method.
There are two options for passing parameters - an array or a dictionary.
Below you can see examples of a request to get a new address with the transfer of parameters by an array and a dictionary:
Code:
# array
curl --data-binary '{"jsonrpc": "1.0", "method": "getnewaddress", "params": ["test"] }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/
# object
curl --data-binary '{"jsonrpc": "1.0", "method": "getnewaddress", "params": {"account": "test"} }' -H 'Content-Type: application/json' http://USERNAME:[email protected]:8332/

Simple API client
For use, it is convenient to write a simple wrapper with the functions we need (or use an existing library for your language). Example for ruby:
Code:
class Btc
class BtcError < StandardError; end

SUPPORTED_METHODS = %w(get_new_address get_addresses_by_account get_info get_net_totals get_balance get_received_by_address send_to_address list_transactions get_transaction)

class << self
def method_missing(method_name, *args)
if SUPPORTED_METHODS.include?(method_name.to_s)
send_request(method_name.to_s, args.empty? ? nil : args)
else
super
end
end

def respond_to_missing?(method_name, _include_private = false)
SUPPORTED_METHODS.include?(method_name) || super
end

protected

def host
ENV["HOST"] || "http://username:[email protected]:8332"
end

private

def send_request(method, params = nil)
uri = URI.parse(host)
request = Net::HTTP::Post.new(uri)
request.basic_auth uri.user, uri.password
request.body = JSON.dump(
jsonrpc: "1.0",
method: method.tr("_", ""),
params: params
)

req_options = { use_ssl: uri.scheme == "https" }

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end

begin
result = JSON.parse(response.body)
rescue JSON::ParserError
raise BtcError.new(response.body)
end
raise BtcError.new(result["error"].to_json) if result["error"]

result["result"].is_a?(Hash) ? result["result"].deep_symbolize_keys : result["result"]
end
end
end

After that, you can conveniently use it in something like this:
Code:
# run with HOST env variable (HOST=http://username:password@localhost:8332)
Btc.get_info
# => {result: {...}}

An analogous example for node.js:
Code:
var http = require('http');

function BtcApi(host, port, username, password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
};
BtcApi.methods = [
'getNewAddress',
'getAddressesByAccount',
'getInfo',
'getNetTotals',
'getBalance',
'getReceivedByAddress',
'sendToAddress',
'listTransactions',
'getTransaction',
];
BtcApi.prototype.sendRequest = function(method, params, callback) {
if (BtcApi.methods.indexOf(method) === -1) {
throw new Error('wrong method name ' + method)
};

if (callback == null) {
callback = params;
};

var body = JSON.stringify({
jsonrpc: '1.0',
method: method.toLowerCase(),
params: params,
});

var auth = 'Basic ' + Buffer.from(this.username + ':' + this.password).toString('base64');

var options = {
host: this.host,
port: this.port,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': auth
},
};

var request = http.request(options, function (response) {
var result = '';
response.setEncoding('utf8');

response.on('data', function (chunk) {
result += chunk;
});

// Listener for intializing callback after receiving complete response
response.on('end', function () {
try {
callback(JSON.parse(result));
} catch (e) {
console.error(e);
callback(result);
}
});
});

request.write(body)
request.end()
};

for (var i = 0; i < BtcApi.methods.length; i++) {
BtcApi.prototype[BtcApi.methods[i]] = function (method) {
return function (params, callback) {
this.sendRequest(method, params, callback)
}
}(BtcApi.methods[i])
}

module.exports = BtcApi

Which can be used something like this:
var BtcApi = require('./btc');

var client = new BtcApi('127.0.0.1', 8332, 'username', 'password');

client.listTransactions({ count: 1 }, function (response) {
console.log('response: ', JSON.stringify(response));
});

// {"result":[{...}]}

It's even easier for Python - the official way is to use:
Code:
from jsonrpc import ServiceProxy

access = ServiceProxy("http://user:[email protected]:8332")
access.getinfo()

Actually, there are no problems with PHP either (it is recommended to use http://jsonrpcphp.org/ ):
Code:
require_once 'jsonRPCClient.php';

$bitcoin = new jsonRPCClient('http://user:[email protected]:8332/');

echo "<pre>\n";
print_r($bitcoin->getinfo()); echo "\n";
echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";
echo "</pre>";

A good collection of documentation can be found here .
The examples above are slightly modified versions of those listed here.

Integration with the site
The only part left is to set up the processing of receiving payments and generating addresses for replenishment.

The process of integrating the acceptance of crypto payments looks something like this:
  • When a user requests a payment, we show him the address where to transfer funds
  • In the background (the easiest option is by cron), we check the list of wallet transactions and, when a new one arrives, we add funds / change the payment status.
To generate receiving addresses, you can use several different approaches - creating a new address for each deposit, or using a permanent address for the user's account.
The first option is safer (since it is more difficult to track repeated payments by the payer) and simple, but it can become a problem when using not very powerful hardware (each generated address increases the load on the node, but this becomes noticeable only from several million addresses).
The second option is more convenient if users have to register and pay frequently, but at the same time it is less secure (for example, you can track all receipts of funds to a user account).
To generate a top-up address, call the getnewaddress method, which will return a new top-up address in response. For convenience, you can pass an account as a parameter (account) to which the created address will be linked. Sometimes it can be handy to view transactions for a specific user.
Several methods are suitable for checking the balance. The easiest way is to create a record in the database for each generated address for replenishment, and then check for each of the records through the method of getreceivedbyaddressreceipt of funds (not the most productive option, but suitable for most situations).
Another good option would be to receive information via listtransactions about the latest operations and for them already look for a user who receives balances. Which type of implementation to use is up to you.
An important point when checking transactions is to correctly indicate the number of confirmations to protect against various attacks. For most cryptocurrencies, they can usually be found in the White Paper.
For bitcoin, the currently recommended value is 6 confirmations for small amounts. Here everything is well documented.
I will not write code examples here, because it strongly depends on the technology used.

Conclusion
I also wanted to write about the integration of other wallets, in more detail about the requirements for the server and about the withdrawal, how to accept payments if the site is not hosted on a VPS with root access, etc., but I realized that the article was already big, so if it will be interesting - I'd better publish it in one of the next articles.
Hello and thanks for the help.
You sent instructions on how to install a gateway but how to use this gateway on the site?
How to publish a product on the site to be seen the price tag in Bitcoins?
How can I make a balance system on the site? And where can I read in detail about it?
I do not have much experience in programming.
Therefore, if there is a place where you can learn everything from scratch, I will be very happy.

I want to build an online store. What is better, own gateway or service?
Thanks.
 
Top