📜 ⬆️ ⬇️

We write our own Bitcoin payment gateway

UPDATE. Zaopensorsil payment gateway: github.com/Overtorment/Cashier-BTC

For various reasons, existing payment gateways (such as Bitpay) may not suit you. In this article, we will consider creating your own Bitcoin gateway from scratch.

It is assumed that the reader is familiar with the device network Bitcoin. If not, I recommend these articles: “How the Bitcoin protocol actually works” and “Bitcoin: an introduction for developers”

Conventionally, I would divide our proposed system into 4 parts:
')

To perform these operations, we need to find a set of software solutions that will simplify our lives.
The most popular and used solutions can perform all or almost all of the above operations, but nothing prevents us from combining solutions, or even writing our own bicycle for certain stages.

Work with addresses


In general, any cryptographic library supporting elliptical cryptography can cope with this.

Another suitable Bitcoin library to work with Bitcoin:


Getting information from the Bitcoin network


The most "heavy" item.
The classic solution is to raise your own standard Bitcoin full node, which is also the canonical bitcoind. This will allow us to communicate with him via JSON-RPC. With it, we will be able to both receive information from the network and push transactions.
What you should pay attention to:

The alternative is to implement the complete node on Ruby + PostgreSQL, Toshi . Non-canon but incompatible implementation. Please note, due to additional indexes, the database will take 220+ gigabytes of space. Again, network synchronization is required.
Perhaps there are other implementations of the complete node (unknown to me).
Another alternative is to use the public API of the provider. On his shoulders will fall information from the network and broadcast transactions.

Now there is:



Personally, I recommend connecting multiple solutions with a fayloverom.

Creating and signing transactions


Depending on which main library we have chosen, this library is able or not able to create and sign transactions.
You can write yourself.
See the “Working with Addresses” section.

Transaction Transaction


The result of creating and signing transactions are binary data (hex), ready to push into the network. Until the network sees the transaction, consider there is no transaction. When the network has seen the transaction, it is considered unconfirmed. It is enough to transfer the transaction to a single Bitcoin node, after which in a matter of seconds the majority of the Bitcoin network will see the transaction.
Some client clients are able to broadcast transactions from the “Work with Addresses” section (through some hardcoded endpoints), or any full node. You can even translate a transaction with your hands, by visiting the provider's Bitcoin API’s special page and entering the transaction into a special form. Kanonichno, a confirmed transaction is a transaction that is included in 6 or more consecutive blocks (or in 1-3. Non-canonical, but faster). Transactions with a zero (or insufficient) commission can remain unconfirmed for a long time (up to a month, in my practice). Such transactions are preferably periodically relayed.

General principles of payment gateway operation


Option 1


Suppose we have a unique invoice (invoice, order) submitted for payment to the client, and the client will pay in bitcoins.
To begin with, it is necessary to convert the currency of the original account (USD for example) to BTC. The task is trivial and we will not consider it.
Further. The de facto standard is the generation of a new unique Bitcoin address for each order (it’s the same account, it’s the invoice, it’s an order). It is expected that only our client will transfer funds to this account, only once, and only a strictly specified amount (more can be done, no one will be offended, but no less). So when funds are received at the specified Bitcoin address in the right quantity, the order is considered paid.

In short, the chain is as follows:



When Bitcoins arrive at the address, you have options to count the unconfirmed or confirmed balance.
There is a small chance that the transaction will be rolled back, and this can be either the fault of the payer (which is actually an intruder), or due to circumstances beyond his control.

If you have the opportunity to “take away” the goods or services provided by the client in the event of a transaction canceled, I recommend to count the unconfirmed balance. This will mean an almost instant payment process for the client (as opposed to an hour of waiting, for example). And if any transactions appear to be rolled back as a result, request the client to re-pay, threatening to take away the service / product.

Do not expect that such a fraud will immediately overtake you immediately, rollback of transactions is very rare, and “manually” to encourage such a rollback (for which, by the way, the attacker has no guarantee of success) for technically unqualified clients is impossible (as opposed to credit card credit cards).

Another example of when an unconfirmed balance can be credited is if it takes more than one hour to prepare a customer’s order (for example, the customer’s shopping cart is processed, it is prepared to be sent by courier). There is a lot of time to double-check the balance before sending the goods.

For other cases, you can enter a certain threshold, above which you must expect a confirmed balance (for example, 0.25 BTC). For maximum reliability, make it zero.

After the order is closed, you can leave Bitcoins at this address on demand, or for convenience, transfer to a single “aggregation” wallet of the merchant. Be careful, in the latter case, you can compromise such a commercial indicator as “turnover”, because payment transaction can track every paying customer.
For transfers, you will need to create, sign, and translate transactions using private keys for addresses.

A few words about the lifetime of the order.
If your product or service is rigidly tied to an equivalent in fiat currency (for example, USD), then the typical life of the order is 7-15 minutes due to the exchange rate volatility.

Option 2


It is suitable when you do not invoice for payment, and the user account contains a certain single balance, which it replenishes and from which it spends.
Here you will need to generate a Bitcoin address on the user, and show him, with a request to replenish it with any amount.
In this case, it is necessary to monitor the address for incoming transactions, replenish the internal balance of the user in the presence of these.
In this case, I recommend to count only confirmed transactions (from 3 blocks and above).



A few words about security


In the case of hacking, the intruder will be interested in only one thing - private keys from the addresses you generate, because they allow you to transfer funds from these addresses anywhere.
I recommend keeping them isolated from the main system in some kind of secure storage. In the end, you will need them only when you yourself want to use the gained bitcoins (spend, convert to cash, etc).

What's next?


If necessary, the proceeded bitcoins can be automatically entered into the stock exchange and sold on the stock exchange API. To do this, we need to create, sign and broadcast transactions using private keys for addresses.

That's all, I hope it will be useful to those who have a similar task.
Corrections of inaccuracies and errors are welcome in lichku.

Source: https://habr.com/ru/post/266779/


All Articles