How to make better use of blockchain API

geek12345 2021-05-15 01:33:37 阅读数:510

make better use blockchain api

Blockchain allows data providers and consumers to trade information directly in a single open system , Instead of subscribing to dozens of centralized services around the world , And write their software to work with each API communicate . Read this blockchain API course , Learn how to use it according to your specific needs .

API( Application programming interface ) It's a way that a single computer program can interact with another program ( class , The process , function , Structure or constant ) Description of . It is usually contained in any Internet agreement ( for example RFC) Description of , Software frameworks or standard calls to operating system functions . It is usually implemented by a separate software library or operating system service . Developers usually use blockchain API To write all kinds of applications .

API Define the program ( modular , library ) Features provided , And allow abstraction from the way the function is implemented . Software components are delivered through API Interact with each other . under these circumstances , Components usually form a hierarchy : High level components use the API, And these components use even lower level components API. The protocol for data transmission over the Internet is based on this principle .

Standard protocol stack (OSI A network model ) contain 7 layer ( From physical bit transport layer to application protocol layer , Be similar to HTTP and IMAP agreement ). Each level uses the functionality of the previous underlying data transfer level , And provide the necessary functions for the next coverage level .

Be careful : The concept of agreement and API It's similar in concept . Both are functional abstractions , In addition to the protocol involving data transmission , and API Related to the interaction of the application .

Blockchain API Varieties

The development of blockchain software usually includes various difficult parts . One of the most important is to create blockchains API Interface . Some projects provide API Services to help users and developers :

An incredibly easy way for websites to receive bitcoin payments . This service is completely secure , Ideal for business or personal use :

  • Blockchain linked wallet service .
  • For sending and receiving payments from blockchain wallets API.
  • Data request for each block and transaction JSON.
  • Simple blockchain for requests API: Simple text format for querying blockchain data API.
  • Web Socket : Streaming sockets with low latency , Provide data for new blocks and transactions .

Let's start with the blockchain wallet API Comments begin . Blockchain Wallet API Provides a simple interface . To use this API, You need to start a small local service that manages your wallet . Your app goes through HTTP API The call interacts with this service locally .

Now? , You can get it from the new blockchain wallet API Transfer bitcoin . All deals are worth 0.0001 BTC The cost of miners . Here it is PHP In the way :

$amounta = "10000000";
$amountb = "400000";
$addressa = "1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq";
$addressb = "1ExD2je6UNxL5oSu6iPUhn9Ta7UrN8bjBy";
$recipients = urlencode('{
"'.$addressa.'": '.$amounta.',
"'.$addressb.'": '.$amountb.'
$json_url = "http://localhost:3000/merchant/$guid/sendmany?password=$firstpassword&second_password=$secondpassword&recipients=$recipients";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$message = $json_feed->message;
$txid = $json_feed->tx_hash;

WebSocket API Allows developers to access real-time data about new transactions and blocks .

from URL link wss:// Start . When deploying sockets , Users send op news {“op”:“ping”} To subscribe to the channel . then , Subscribe to notifications about all new bitcoin transactions {“op”:“unconfirmed_sub”}. Last , Subscription address {“op”:”addr_sub”, “addr”:”$bitcoin_address”}.

Notice of the new transaction is as follows :

"op": "utx",
"x": {
"lock_time": 0,
"ver": 1,
"size": 192,
"inputs": [
"sequence": 4294967295,
"prev_out": {
"spent": true,
"tx_index": 99005468,
"type": 0,
"addr": "1BwGf3z7n2fHk6NoVJNkV32qwyAYsMhkWf",
"value": 65574000,
"n": 0,
"script": "76a91477f4c9ee75e449a74c21a4decfb50519cbc245b388ac"
"script": "483045022100e4ff962c292705f051c2c2fc519fa775a4d8955bce1a3e29884b2785277999ed02200b537ebd22a9f25fbbbcc9113c69c1389400703ef2017d80959ef0f1d685756c012102618e08e0c8fd4c5fe539184a30fe35a2f5fccf7ad62054cad29360d871f8187d"
"time": 1440086763,
"tx_index": 99006637,
"vin_sz": 1,
"hash": "0857b9de1884eec314ecf67c040a2657b8e083e1f95e31d0b5ba3d328841fc7f",
"vout_sz": 1,
"relayed_by": "",
"out": [
"spent": false,
"tx_index": 99006637,
"type": 0,
"addr": "1A828tTnkVFJfSvLCqF42ohZ51ksS3jJgX",
"value": 65564000,
"n": 0,
"script": "76a914640cfdf7b79d94d1c980133e3587bd6053f091f388ac"

For blockchain data API, If to GET Request add &cors=true Parameters , You can use CORS Do some data API call .

CORS( Cross source resource sharing ) It's a modern browser technology , It provides a web page that can access resources in another domain . Until recently , Overcome the homology strategy to XSS The main way to ask for restrictions is to use JSONP.JSONP There is a fatal limitation in itself : It can only pass through GET Method to receive data . adopt POST Method send data is still inaccessible .

The technology itself is very simple . There are three domains that want to download resources from the server . To achieve this , Providing content Web The server is sufficient to indicate the list of trusted domains in the response header Access-Control-Allow-Origin:A,B,C. Then the limitation of the principle of homology On the requested page, there will be pages that do not apply to these domains . To start a cross source request , The client browser will send HTTP request ( The requested site domain ) Add the original request . for example , page Try from Page to get data .

In blockchain data API in , A single block is as follows :

"tx":[--Array of Transactions--]

Blockchain charts and Statistics API Allow and The chart displayed on the screen interacts with the statistical information .( Blockchain information API).

have access to Charts API Methods to receive information about Chart information :

"status": "ok",
"name": "Confirmed Transactions Per Day",
"unit": "Transactions",
"period": "day",
"description": "The number of daily confirmed Bitcoin transactions.",
"values": [
"x": 1442534400, // Unix timestamp (2015-09-18T00:00:00+00:00)
"y": 188330.0

Stats API Can be used to receive information about Information about Statistics :

"market_price_usd": 610.036975,
"hash_rate": 1.8410989266292908E9,
"total_fees_btc": 6073543165,
"n_btc_mined": 205000000000,
"n_tx": 233805,
"n_blocks_mined": 164,
"minutes_between_blocks": 8.2577,
"totalbc": 1587622500000000,
"n_blocks_total": 430098,
"estimated_transaction_volume_usd": 1.2342976868108143E8,
"blocks_size": 117490685,
"miners_revenue_usd": 1287626.6577490852,
"nextretarget": 431423,
"difficulty": 225832872179,
"estimated_btc_sent": 20233161880242,
"miners_revenue_btc": 2110,
"total_btc_sent": 184646388663542,
"trade_volume_btc": 21597.09997288,
"trade_volume_usd": 1.3175029536228297E7,
"timestamp": 1474035340000

The currency API

Acceptance of bitcoin payment is becoming more and more popular and needed . There are many ways to accept bitcoin payment on a website . One of the most convenient ways is blockchain API. ad locum , You don't need to bind to a specific language or language SDK; You don't even need to register there . All you need is a wallet to accept bitcoin , And there will be time for quite simple API Connect to your system . Besides , Customers won't see your wallet , It's the temporary wallet of the exchange .

Before we talk directly about code ( We'll use... In the example PHP, But it can be in Java,Python And so on ), It is necessary to clarify the payment acceptance mechanism itself .

The whole process follows the order :

  • 1. The user requests a temporary wallet from the blockchain by sending a series of data .
  • 2. Blockchain returns its temporary wallet to receive payments to users .
  • 3. The user shows the wallet to the client , And a small group of instructions on how to deal with it .
  • 4. Customers pay ( Put money in your wallet ).
  • 5. Users should wait for payment verification in bitcoin system .
  • 6. In the case of successful verification of the blockchain system , The script will be called on the user's site ( The user has to indicate which ), And transmit all transaction data .
  • 7. after , Secure confirmation of payment within the user's system .

To get a temporary wallet , You should send a series of data :

  • The script that will be copied in case of successful confirmation of the transaction URL. It is worth noting that , It is recommended to specify a parameter ( Even some parameters ), To identify payments in the current system . Just specify the client in the user's system ID And enter any data into the database , But only after receiving confirmation of the transaction can . however , The official document recommends the use of pre created payment numbers and any verification phrases . in general , We go through the routine GET Parameter acquisition in transfer request URL. For blockchain systems , This parameter is called a callback . The value should be encoded as URL link .
  • The user's wallet is used to receive payments . Blockchain will transfer the money it receives to this wallet . The parameter is called the address .
  • The last parameter is called the method , And used to create temporary wallets .

This data will be sent to the blockchain script (, Each parameter is commonly used GET Parameters . The execution result is processed by the user system ( The result will be JSON Format ). About blockchain information API All the content of is in the blockchain API Document .

Now? , The user is ready to accept payment for the wallet , But the fact that they can't register their receipts from the system . Users should remember , In a real system , Well thought out and well written code is recommended , And a database of ready payments ( The payment number will be , user ID Stored in the system and validating phrases or their components ). Besides , The timing of verification payments can be different and very important , The bitcoin exchange rate is likely to change . Users have two options : Keep the rate at the time of payment , Or request the rate after receiving the confirmation of the transaction .

The transaction confirmation receipt file should be called receive_payment.php, And it should be stored in the root of the website ; When asking for a temporary wallet , The user is creating $ callback_url Specified its name .

actually , The same payment script will not only be called once , And it will be called according to the number of confirmations on each node . This means that the user has to check for confirmation first .

Blockchain provides many parameters :

  • Transaction_hash, The only transaction hash .
  • Input_transaction_hash, The unique hash value of the original transaction .
  • Input_address, Blockchain wallets that will receive payments .
  • Destination_address, Will send payment to the user's wallet .
  • Confirmations, Number confirmed by node ( If the value of this parameter is greater than or equal to 6, It is suggested that payment confirmation be accepted ).

value Parameter in Satoshi Born in money , Not bitcoin (1Satoshi=0.00000001BTC). therefore , The resulting value should be reduced to bitcoin . be known as invoice_id and secret The parameters of are set by the user at the receiving stage of blockchain wallet . therefore , There may be more or less of them , And they can have any name .

It is recommended that the received value be stored in bitcoin in the payment history ; however , It should be converted into another currency ( For example, dollars ), Used by the user system . If the system is only for bitcoin , You don't need to convert anything .

There is a separate exchange rate API file , Used to convert bitcoin into other currencies . The user must specify two parameters :

  • Name of currency ( A list of currencies is available in the document , Users can also use the call Print_r($ Exchange_data_obj) Get it .
  • The amount of bitcoin users want to exchange .

Blockchain development platform and API

today , There are many companies developing platforms and projects that provide application development tools There's a lot of blockchain information API, To handle their e-wallet service ( This is one of the biggest e-wallet Services ), Designed to send and receive payments and perform other operations . The chain creates an interface for accessing the data contained in the complete node of the distributed records registry , And standard information request : for example , About your bitcoin balance . Besides , You can send a notification when you perform an operation at a specific address .

Stellar It's a semi decentralized ( The gateway organizes Services , Not miners ), Publicly accessible logs and unified development environment ( Blockchain API, Multi signature API) Bound to the Stripe Payment network . Other companies have blockchain wallets with multilateral signatures API, for example,Gem,BlockCypher etc. .

future , A more unified blockchain is needed API development environment , Including the various ever-changing components of the blockchain ecosystem ( Storage , Document maintenance , Wallet interaction , Mobile payment , Authentication and reputation ). Smart contracts will allow us to create a global meteorological data market meteorological data market, Where consumers will request real-time data and receive it in a common format ( Using blockchain information API).

Centralized data providers can bid farewell to their own formats and sales activities , It's sending data to globally accessible weather markets dApp. It can connect the development environment of blockchain with other large network segments : for example , Machine to machine (M2M) Infrastructure for communications and Internet of things networks , For rapid application development . In the distant future , An example of this type of advanced integrated application could be a smart watch that interacts with traffic sensors within the smart city infrastructure , In order to use the smart contract in bitcoin to automatically reserve and pay traffic .

API Operating system and diversity issues

Almost all operating systems (UNIX,Windows,OS X etc. ) There is one. API, Programmers can use this API Create applications for the operating system . Lord API An operating system is a set of system calls . It should be noted that , Developers usually have several different API To achieve the same result . Besides , Every API Usually use a lower level of abstraction API Program components to achieve . for example : In order to see “Hello,world!” This business , In the browser , You just need to create one with the smallest title HTML The document and the simplest body containing the given line .

When the browser opens this document , The browser program will change the name of the file ( Or open file descriptor ) Transfer to processing HTML Library of documents , And the library file will use operations API The system reads this file , And then through “clear window” Type of standard graphics / Basic operation API Library calls it . Write... In the selected font “Hello,world!”. During these operations , The graphic primitive library will use the corresponding request access window interface library . The library has been linked to the operating system API contact , Write data to the video card buffer .

meanwhile , Almost every level actually has several possible alternatives API. for example , We can not be in HTML Write the source document , But in LaTeX Write on . We can use any browser to display . Generally speaking , Different browsers use different HTML library , All of these can be compiled using different raw libraries and different operating systems .

therefore , Existing multi-level API The main difficulty of the system is :

  • Take software code from a API Porting the system to another API The complexity of the system ( for example , When changing the operating system ).
  • Loss of function when moving from a lower level to a higher level . Roughly speaking , Every API“ layer ” Created to facilitate the execution of some standard set of operations . But at the same time , It's really hard , Or it's impossible to perform by lower API Other operations provided by level .
  • From a API Move to another API It's difficult to transplant program code when it's needed . These problems often occur when transferring modules to other operating systems .
  • From low-level management to high-level management , Reduce the scope of interface functions . under these circumstances , Promote the implementation of strictly defined task categories . meanwhile , Control of access to other regulators has been lost . After all , Lower levels allow you to easily manage the basic components of the program .

The classification of software interfaces is closely related to the purpose and function of applications controlled by them . in fact , When running complex systems , There are usually other API The same problem can be solved in other ways .

Separate group assignments are used to manage software modules (wxWidgets,Qt,GTK etc. ), operating system (Amiga ROM kernel ,Cocoa,Linux kernel API,OS/2 API,POSIX,Windows API), voice (DirectMusic /) Interface to the graphics component of DirectSound,OpenAL), Window interface, etc . Their separation depends on the degree of application in the hierarchy and function . Users of computer games usually don't doubt the graphics API Provide them with such fast image rendering and amazing image brightness .

Global blockchain API It usually includes interfaces to various programming languages . With their help , You can manage solutions for very specific and local tasks . It all depends on the implementation of the specific algorithm .


Blockchain raises a lot of extremely important issues . Its use has a wide range of advantages : Reject the third party , Protect the trade , Secure trading , Resource sharing , Guaranteed deal , Automatic execution of contracts, etc .

Let's take a look at this technology from the perspective of :

  • A blockchain can contain multiple API, Including simple blockchains API, Blockchain information API, Blockchain Wallet API, Transaction scripting language ,P2P Node communication API And clients for checking transactions in the network API.
  • Application programming interface (API) Now included in the public infrastructure of password protection ( Blockchain ).
  • Blockchain is used as a new form of database : for example , As a permanent storage immutable password blockchain API secret key ( Or hash ) Distributed hash table for (DHT), Associated with massive storage of data links .
  • A new browser will allow users to run decentralized applications (Dapps), Not just web pages ( for example , In Ethereum Mist).

It can also solve many more difficult problems . One of them is centralization . Blockchain technology can be very useful in the future world , In this world , Both centralized and decentralized models will be applied . It will not only undermine existing stereotypes and plans , It also helps to develop large ecosystems that combine old and innovative approaches .

If you need more information about blockchain Technology , Please contact the application team .


If you want to learn blockchain and Blockchain Technologies Build a career , So please see some Ethereum we share 、 The currency 、EOS、Fabric And other interactive online programming practical courses related to blockchain :

  • java Ethereum development tutorial , Mainly aimed at java and android Programmers develop blockchain Ethereum web3j Detailed explanation .
  • python The etheric fang , Mainly aimed at python Used by the Engineer Detailed explanation of blockchain Ethereum development .
  • php The etheric fang , It mainly introduces the use of php Conduct smart contract development interaction , Create an account 、 transaction 、 Transfer accounts 、 Token development, filters and transactions .
  • Introduction to Ethereum , It mainly introduces smart contract and dapp application development , Suitable for entry .
  • Advanced course of Ethereum development , It mainly introduces the use of node.js、mongodb、 Blockchain 、ipfs Realize decentralization of e-commerce DApp actual combat , Suitable for advanced .
  • ERC721 Ethereum proves the actual battle , The course is a digital art creation and sharing DApp The actual development of the main line , In depth to explain the concept of Ethereum heterogeneity pass 、 Standards and development programs . It contains ERC-721 Autonomous implementation of standards , Explain OpenZeppelin Second development of contract code base , The actual project adopts Truffle,IPFS, It has realized the general stock exchange and decentralized general stock exchange .
  • C# The etheric fang , It mainly explains how to use C# Based on Development .Net The Ethereum application of , Including account management 、 Status and transactions 、 Smart contract development and interaction 、 Filters and trading etc .
  • java Bitcoin development tutorial , This course is for beginners , It covers the core concepts of bitcoin , For example, blockchain storage 、 Decentralized consensus mechanism 、 Keys and scripts 、 Trade with UTXO etc. , At the same time, it also explains in detail how to Java Bitcoin support function is integrated in the code , For example, create an address 、 Manage your wallet 、 Construct naked transactions, etc , yes Java A rare bitcoin development learning course for Engineers .
  • php Bitcoin development tutorial , This course is for beginners , It covers the core concepts of bitcoin , For example, blockchain storage 、 Decentralized consensus mechanism 、 Keys and scripts 、 Trade with UTXO etc. , At the same time, it also explains in detail how to Php Bitcoin support function is integrated in the code , For example, create an address 、 Manage your wallet 、 Construct naked transactions, etc , yes Php A rare bitcoin development learning course for Engineers .
  • c# Bitcoin development tutorial , This course is for beginners , It covers the core concepts of bitcoin , For example, blockchain storage 、 Decentralized consensus mechanism 、 Keys and scripts 、 Trade with UTXO etc. , At the same time, it also explains in detail how to C# Bitcoin support function is integrated in the code , For example, create an address 、 Manage your wallet 、 Construct naked transactions, etc , yes C# A rare bitcoin development learning course for Engineers .
  • EOS Introductory tutorial , This course helps you get a quick introduction to EOS Development of decentralized application of blockchain , Content covered EOS Tool chain 、 Accounts and wallets 、 Issue tokens 、 Smart contract development and deployment 、 Use code to interact with smart contracts and other core knowledge points , At last, we use all the knowledge points to complete a note DApp Development of .
  • Play in depth EOS Wallet development , This course uses mobile phones EOS The whole development process of wallet is the main line , Learn more EOS Blockchain application development , The course covers accounts 、 Computing resources 、 Intelligent contract 、 Actions and transactions, etc EOS The core concept of blockchain , It also explains how to use eosjs and eosjs-ecc Development package access EOS Blockchain , And how to React Integration of front-end applications EOS Blockchain support . The content of the course is simple , It's very suitable for front-end engineers to study deeply EOS Blockchain application development .
  • Hyperledger Fabric Blockchain development details , This course is for beginners , The content includes Hyperledger Fabric The identity certificate and MSP service 、 Authority strategy 、 Channel configuration and startup 、 Chain code communication interface and other core concepts , Also contains Fabric Network design 、nodejs Chain code and operation practice of application development , yes Nodejs Engineers learn Fabric The best choice for blockchain development .
  • Hyperledger Fabric java Blockchain development details , The course is for beginners , The content includes Hyperledger Fabric The identity certificate and MSP service 、 Authority strategy 、 Channel configuration and startup 、 Chain code communication interface and other core concepts , Also contains Fabric Network design 、java Chain code and operation practice of application development , yes java Engineers learn Fabric The best choice for blockchain development .
  • tendermint Blockchain development details , This course is suitable for the students who want to use tendermint Engineers who develop blockchain , The course includes tendermint The core concepts in the application development model , for example ABCI Interface 、 Ms merkel tree 、 Multi version state library, etc , It also includes rich practical codes such as token issuance , yes go The best choice for language engineers to get started with blockchain development .

Original translation of Huizhi , Reprint please indicate the source . Here is How to make better use of blockchain API