Defi Token Development Company- Security Tokenizer

Do you want to launch your own Defi Token? https://bit.ly/3C0UM0i

No more waiting! Get Security Tokenizers' Defi Token Development Service and Solutions!

Visit here--> https://www.securitytokenizer.io/defi-token-development


#tokendevelopment #tokendevelopmentcompany #tokendevelopmentservices #crypto #cryptocurrency #usa #uk #indonesia #southkorea #japan #token #defi 

Defi Token Development Company- Security Tokenizer

Ethereum Merge - A Simplified Guide

The "Ethereum Merge" has been the talk of the town for the past few weeks, with Google hyping it more with a countdown timer featuring two Pandas approaching each other and quoting the merge date of September 15, 2022. Ethereum’s successful merge is a huge step for the community and a pathway towards mainstream adoption that can bring in billions of users to Web 3. Ethereum's blockchain, being the base for thousands of upcoming and well-known firms, has taken this valiant leap in conserving the environment as well as increasing the speed and scalability.

A significant upgrade to its blockchain network—the Merge, Ethereum, the second largest crypto token—has now switched from a proof-of-work (POW) mechanism to a proof-of-stake (POS) mechanism.According to Ethereum developers, this upgrade will make the $60 billion ecosystem that houses crypto exchanges, lending companies, Non Fungible Token (NFT) market places, and other applications more secure and long-lasting.

The Merge officially kicked in at 6:43 am UTC, with more than 45,000 people watching with bated breath on Youtube in the "Ethereum Mainnet Merge Viewing Party." The key metrics trickled in, suggesting that Ethereum’s core systems had remained intact. After about a 15-minute wait, the $200 billion market value giant declared the merge successful. This Ethereum Merge will mark the beginning of energy-efficient crypto operations, which will accelerate the drive for mass adoption of crypto-related products and services.
 

What is Ethereum Merge & its Fundamentals?

In 2008, Bitcoin introduced the world to the idea of decentralized blockchains that facilitate the process of transactions and track assets. The history of any transaction on the blockchain is unaltered because of its distributed and transparent nature across the network.

And with the introduction of Ethereum in 2015, expanding the core concept of Bitcoin with smart computer programmes that effectively use the blockchain as global supercomputers by recording the data on their network.

Decentralized Finance ( DeFi ) and Non Fungible Tokens ( NFTs ), the main catalyst of the recent crypto boom run on the Ethereum blockchain. Unlike a centralized system where a centralized agency or government facilitates the process, Depending on your peers to facilitate the transaction happens in decentralized system. The validators are a set of people or groups who authenticate the transactions. These validators put up collateral that they could stake, earning them rewards in the form of crypto tokens if they validated it correctly. In the event that they screw up or are not able to validate, then their stake is partially or wholly seized by the network. Working on this basic principle, the blockchains have paved two ways of achieving consensus, namely, Proof Of Work ( POW ) and Proof Of Stake ( POS ).


Proof Of Work (POW)   

In Proof Of Work, the investment comes in the form of a significant amount of computational energy being spent on solving complicated mathematical algorithms and equations quickly in order to validate new transactions and keep winning crypto blocks as rewards. Bitcoin, Ethereum, and other major blockchain giants that use Proof of Work consensus typically have massive warehouses stacked with computing machines like shelves of books, with each computer hot to the touch as it strains to run around the clock pumping out cryptocurrencies.

If the validator correctly authenticates, he is rewarded; if they get it wrong, they receive nothing and have wasted a lot of time and energy. The energy lost is comparatively very high and affects global electricity consumption. The Ethereum blockchain consumes as much energy as the entire country of Finland, consuming so much energy and being responsible for one of the blockchain sectors that greatly exploits the environment. This led to the new concept of "Proof Of Stake."
 

Proof Of Stake (POS)

In this Proof Of Stake method, you don’t need validators to run massive supercomputers. These validators are skinned in the game by "staking" some of their own coins. The investment is made by a user who has a significant amount of existing crypto in the network, such as the Ethereum blockchain blocking down 32 ETH for transaction validation and sending them to an address where they cannot be bought or sold.These stacked ETH tokens act like lottery tokens. The more ETH a validator stacks, the higher the probability of them being selected.

Stakeholders who breach the rule by spending their staked wager or are caught recording inaccurate data risk losing their entire wages. Here, the stakeholders are willing to bear the risk of staking a huge amount in return for a chance to make massive profits. The energy consumption in Proof Of Stake is not even a rounding error in terms of environmental impact. The Ethereum blockchain has fundamentally shifted to this mechanism, which consumes 99.90% less energy.With this new mechanism adopted in place, shifting the entire algorithm proving that a decentralized and permission less network can operate energy efficiently.

Proof Of Stake is like running an application on your MacBook, such as Slack, Google Chrome, or Netflix, even while being plugged in for electricity. It will not have an environmental impact.
 

The Merge - It's Incentives & Trades


The Ethereum network is better understood as a kind of living organism that works together, a bunch of computers interacting with each other in the same language, following an identical set of rules. A new set of incentives is introduced for the parties operating these computers to follow the rules as written to secure the blockchain from unwanted tampering. With energy consumption dropping to the base and the applications already running on the Ethereum blockchain gaining benefits, investors will be much more interested and concerned. Unlike the Proof of Work mechanism, which converts physical resources into network security, the Proof of Stake merger connects financial resources to security.

The Ethereum blockchain will no longer be concentrated in the hands of a few publicly traded mining syndicates; instead, the old power players will be replaced by new genuine stake holders, breaking down the monumental dream of those syndicates. The Merge has become an object of speculation in the crypto market since mid-July, with traders pricing in post-merge gains, easing the clash in the digital asset market earlier this year. In a recent note, Bank Of America used the example of an insurance company, "Nexus Mutual," to describe the merger benefit in detail. Nexus Mutual has been doling out insurance policies for those dealing with crypto hacks using Ethereum's blockchain. The network allows you to collect premiums, pool all of your money, invest it in Ether stakes, verify transactions, and earn huge profit rewards in exchange for replacing government bonds, which only provide mediocre returns.

Conclusion:

ETH fanatics are already looking forward to "the surge, the verge, the purge, and the splurge" in the blockchain network. Though the partial adoption of sharding in the ETH ecosystem has already boosted the speed, a complete adoption will supercharge the blockchain to process high volumes of transactions in mere seconds. Sharding will increase the speed of the system from its current capacity of 15-20 transactions per second to 100,000 transactions per second.

Ethereum has officially bid adieu to its miners, who undertook block validation in its previous POW avatar. These miners, who racked in about $19 billion last year through mining coins, are completely rattled. Hence, Ethereum Merge will undoubtedly provide numerous benefits to developers, end users, and the environment.

#ethereum #eth #merge #crypto 

Ethereum Merge - A Simplified Guide

Buy, Sell and Trade Beldex (BDX) on Koinbazar

Afanddy Bin Hushmi owned firm, Beldex International launched the Beldex blockchain in January 2019 which has been widely accepted by the earthians unanimously. Beldex tokens are mined proof of work coins, incorporating an integrated PrivateSend privacy protocol from DASH and a few more key privacy features to improve original privacy, as well as its own configurable privacy technology.

The Beldex blockchain provides a unique variable solution to problems of privacy, scalability and ecosystem. BDX uses higher size Ring CT network type, providing the user with complete anonymity and making their roots untraceable. Hence the transactions made are utterly innominate, pirate and secure.

Uses of Beldex

Beldex is highly compatible and the Beldex bridge making the blockchain entirely interoperable with the Binance smartchain, Ethereum ( ETH ) bridge, Polkdot ( DOT ) bridge and more. Beldex will be bridging its BDX coins on many smartchains without trading off its inherent privacy features.

The Beldex bridge not only making BDX coins run on other blockchains, also increases the scalability of the native crytpocoin, Anchoring down the transaction fees with instant processing.

The Beldex privacy protocol enables crosschain payment privacy and anonymity protocol that anonymizes the transactions. Adding zk-SNARKS algorithm, zethu protocol and El Gawal Encryption to its blockchain package, BDX provides speed and security at its peak. Extra provision of an exchange medium, that underpins the ecosystem to reduce the risk due to time based analysis providing Privacy Guaranteed flash transactions.

Interesting Facts about Beldex

1. The trading value of BDX is $1.12 million in 24 hours and has seen an All Time High ( ATH ) of $ 137,242,055.

2. Addition of flash transactions, a second layer atop the Beldex blockchain that allows for a confirmation of transactions before being included in blocks within seconds.

3. Beldex has an array of services which comprises of BChat, BelNet, Beldex Browser, Beldex wallets, Beldex privacy protocol, Beldex wallet extension and Beldex bridge.They are all decentralised apps tailored to make the process of transaction comparatively hassle- free. It also makes up the Beldex private ecosystem which is an advantage to all its users. The transaction history will be maintained in a decentralized blockchain.

Tokenomics :

TOKEN NAME : BELDEX

SHORT NAME : BDX

TOTAL SUPPLY : 9,903,120,858

CIRCULATING SUPPLY : 2,973,120,858

How to Buy Beldex (BDX) ?

Follow the below steps to buy Beldex,

1.Create a crypto trading account with Koinbazar global cryptocurrency exchange platform.

 2. Complete your KYC verification process.

3. Add your bank account

4. Start to buy BDX coins with Indian rupees (INR) & Tether (USDT)

BDX/INR -> https://koinbazar.com/trade/BDX_INR

BDX/USDT -> https://koinbazar.com/trade/BDX_USDT

To make your BDX coin trade anywhere, anytime with the great trading experience with koinbazar Android and iOS app.

#cryptocurrency #cryptos #crypto 

 Buy, Sell and Trade Beldex (BDX) on Koinbazar

What is Mintable Token ?

Mintable token is a non fixed total supply, allowing the token user to mint more tokens whenever they want. Mintable tokens may sound similar like mineable tokens, while both tend to produce new tokens they are completely varied in terms of utility and design. This is turn has far reaching implications for the kind of function they can perform and the security risks they entail.

Minting is basically a decentralized process of increasing the total supply of tokens and ending them when reached necessity. This process can be enabled during the creation of token and any number of tokens required can be minted irrespective of number. Both the proof of work and proof of stable protocols make use of mechanisms that ensure users have invested interest in updating the validity of the network. It can either be a fungible token or a cryptocoin.

PROOF OF WORK

In the case of proof-of-work tokens, this investment takes the form of considerable computational energy expended on finding the quickest solution to challenging equations in order to submit new transactions and get the block reward. The miners are typically compensated in cryptocurrencies, putting these new coins into circulation, and they are typically kept and validated on a blockchain..

PROOF OF STAKE

In proof of stake, the investment comes in the form of users having an existing stake in the network, which means the users who wish to validate transactions in exchange for cryptocurrency must first wager a significant amount. This amount is referred to as their stake. These stakeholders are randomly picked and their transactions are verified on blockchains. The greater their individual stock worth, the greater their chance of selection. Stakeholders are unable to withdraw the money they have staked. They run the danger of losing their entire bet if they break the rules or are discovered capturing false data. Stakeholders in this process are willing to accept the risks of staking large sums in exchange for the possibility of profit. 

The maximum number of tokens that can exist is fixed by a hard cap. Tokens will be produced up to the hard cap and given to the team if the hard cap was not reached when the crowdsale ended. The block reward is given a fixed number in each, so it is impossible to manipulate the token supply. Consequently, both the processes provide surety that the cryptocurrency has a limited supply, and the scarcity of the currency is also ensured.

Mintable tokens are usually fungible and are created in Ethereum blockchain (ERC-20). They are most prominent in the crypto ecosystem. These Ethereum blockchains basically follow smart contracts. Hence they are safeguarded by having smart contracts audits performed by a third party, a meticulous review process that defends the project against attacks.

TYPES OF MINTABLE TOKENS

Mintable tokens are classified into two types based on their production supply namely,

FIXED SUPPLY

To raise the value of the token / asset as well as the demand for it, tokens are minted in required numbers. Once the demand is reached no additional coins are minted and so they are also termed deflationary.

CONTINUOUS SUPPLY

The prime goal in continuous supply model is improving the under lying utility and benefits rather than raising the asset value as in fixed supply. They are inflationary as new tokens are minted for utility purpose only.

Non-Fungible Tokens

Non fungible tokens ( NFTs) is prime example of mintable token, where NFTs are added to Ethereum blockchain and the creator  utilizes them to sell their photos, videos and digital 3D objects. To mint NFTs a user must need cryptocurrency wallet with Ethereum in it. Then creating a cryptocurrency wallet on NFT marketplace will allow them to upload their work, paying it in terms of Ethereum for creation will push it further for verification. Once verified a NFT is minted.

#crypto #cryptos #cryptocurrency 

What is Mintable Token ?
Isai  Upton

Isai Upton

1660532460

Integrate Django with Coinbase Commerce to Accept Crypto Payments

In this tutorial, we'll integrate Django with Coinbase Commerce to accept different crypto payments. We'll look at two different approaches: Coinbase Charges and Coinbase Checkout.

Source: https://testdriven.io

#django #crypto #coinbase 

Integrate Django with Coinbase Commerce to Accept Crypto Payments
Thai  Son

Thai Son

1660525200

Chấp Nhận Thanh Toán Bằng Tiền Điện Tử Với Django Và Coinbase

Trong hướng dẫn này, chúng tôi sẽ tích hợp Django với Coinbase Commerce để chấp nhận các khoản thanh toán bằng tiền điện tử khác nhau. Chúng tôi sẽ xem xét hai cách tiếp cận khác nhau: Phí Coinbase và Kiểm tra Coinbase.

Coinbase Commerce là gì?

Coinbase Commerce là một dịch vụ thanh toán kỹ thuật số dành cho doanh nghiệp do Coinbase cung cấp, cho phép người bán chấp nhận thanh toán tiền điện tử bằng các loại tiền kỹ thuật số khác nhau. Tại thời điểm viết bài, họ hỗ trợ Bitcoin, Bitcoin Cash, DAI, Ethereum, Litecoin, Dogecoin và USD Coin. Coinbase Commerce dễ dàng tích hợp vào ứng dụng web của bạn và loại bỏ những rắc rối khi xử lý các khoản thanh toán bằng tiền điện tử.

Coinbase và Coinbase Commerce không giống nhau. Coinbase là một sàn giao dịch tiền điện tử và một nhà quản lý ví, trong khi Coinbase Commerce là nhà cung cấp dịch vụ thanh toán kỹ thuật số cho các thương gia.

API Coinbase Commerce cung cấp hai cách khác nhau để chấp nhận thanh toán bằng tiền điện tử: Phí Coinbase và Kiểm tra Coinbase.

Ưu điểm của Phí Coinbase:

  • có thể tùy chỉnh cao
  • khả năng đính kèm siêu dữ liệu theo chương trình

Ưu điểm của Coinbase Checkout:

  • sáng tạo
  • quản lý sản phẩm bảng điều khiển
  • thanh toán nhúng

Đối với hầu hết các ứng dụng, chúng tôi đề xuất API tính phí vì nó có thể được tùy chỉnh. Điều này vượt trội hơn sự đơn giản mà API Checkout cung cấp. Nếu bạn đang bán một sản phẩm cố định và việc tùy chỉnh không đóng vai trò lớn, hãy sử dụng API Checkout.

Thiết lập dự án

In this tutorial, we'll show how to get both approaches, Coinbase Charges and Coinbase Checkout, up and running. We'll start with the same project setup for each. Once set up, feel free to follow one or both approaches.

Django Project Setup

Start by creating a new directory and setting up a new Django project:

$ mkdir django-coinbase && cd django-coinbase
$ python3.9 -m venv env
$ source env/bin/activate

(env)$ pip install django==3.2.8
(env)$ django-admin startproject core .

After that, create a new app called payments:

(env)$ python manage.py startapp payments

Register the app in core/settings.py under INSTALLED_APPS:

# core/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payments.apps.PaymentsConfig', # new
]

Add a simple functional view called home_view to payments/views.py:

# payments/views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

Create a urls.py file inside the payments app:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
]

Update the project-level URLs file with the payments app:

# core/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payments.urls')), # new
    path('admin/', admin.site.urls),
]

Create a dedicated "templates" folder and a file for the homepage:

(env)$ mkdir templates
(env)$ touch templates/home.html

Then, add the following HTML to templates/home.html:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <a class="btn btn-primary" href="#">Purchase</a>
    </div>
  </body>
</html>

Make sure to update the settings.py file so Django knows to look for a "templates" folder:

# core/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], # new
        ...

Finally run migrate to sync the database and runserver to start Django's local web server:

(env)$ python manage.py migrate
(env)$ python manage.py runserver

That's it! Open http://localhost:8000/ in your favorite browser. You should see the homepage:

Trang chủ Django + Coinbase

Add Coinbase Commerce

Next, install coinbase-commerce:

(env)$ pip install coinbase-commerce==1.0.1

Để làm việc với Coinbase Commerce API , bạn cần tạo một tài khoản (nếu chưa có). Sau khi bạn đã tạo tài khoản, hãy đăng nhập và điều hướng đến cài đặt của bạn. Cuộn xuống phần "Khóa API", nhấp vào "Tạo khóa API" và sau đó "Hiển thị". Sao chép khóa API vào khay nhớ tạm của bạn.

Khóa API Coinbase

Sau đó, thêm khóa vào tệp settings.py :

# core/settings.py

COINBASE_COMMERCE_API_KEY = '<your coinbase api key here>'

Trước khi chuyển sang bước tiếp theo, hãy kiểm tra xem chúng ta có thể truy xuất dữ liệu từ API hay không. Nhập trình bao Python bằng lệnh sau:

(env)$ python manage.py shell

Nhập nội dung sau:

>>> from core import settings
>>> from coinbase_commerce.client import Client

Khởi tạo một khách hàng mới và liệt kê các khoản phí:

>>> client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
>>> for charge in client.charge.list_paging_iter():
...     print("{!r}".format(charge))

Nếu mọi thứ hoạt động, client.charge.list_paging_iter()phải là một danh sách trống. Miễn là bạn không gặp lỗi sau, bạn có thể cho rằng tất cả đều ổn:

coinbase_commerce.error.AuthenticationError: Request id 10780b77-1021-4b09-b53b-a590ea044380: No such API key.

Các trang hữu ích để làm việc với API Coinbase:

Với điều đó, hãy quyết định phương pháp tiếp cận bạn muốn thực hiện, Phí Coinbase hoặc Kiểm tra Coinbase.

Phí Coinbase

Phần này của hướng dẫn cho biết cách chấp nhận thanh toán bằng API phí Coinbase .

Coinbase Charges là cách tiếp cận dễ tùy chỉnh nhất để thu thập các khoản thanh toán bằng tiền điện tử. Với cách tiếp cận này, bạn có toàn quyền kiểm soát các khoản phí.

Quy trình làm việc:

  1. Sử dụng ứng dụng khách để kết nối với API Coinbase Commerce
  2. Tạo khoản phí (từ JSON)
  3. Tìm nạp khoản phí mới được tạo và chuyển nó vào mẫu
  4. Chuyển hướng người dùng đến trang web được lưu trữ trên Coinbase Commerce
  5. (Tùy chọn) Xác minh khoản phí bằng cách sử dụng webhooks

Tạo một khoản phí

Để yêu cầu thanh toán bằng tiền điện tử, bạn phải tạo một khoản phí . Vì thanh toán tiền điện tử là thanh toán đẩy , một khoản phí sẽ hết hạn sau một thời gian chờ đợi nếu không có khoản thanh toán nào được phát hiện. Các khoản phí được xác định bằng một mã 8 ký tự duy nhất.

Cập nhật home_viewđể tạo khoản phí :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    domain_url = 'http://localhost:8000/'
    product = {
        'name': 'Coffee',
        'description': 'A really good local coffee.',
        'local_price': {
            'amount': '5.00',
            'currency': 'USD'
        },
        'pricing_type': 'fixed_price',
        'redirect_url': domain_url + 'success/',
        'cancel_url': domain_url + 'cancel/',
    }
    charge = client.charge.create(**product)

    return render(request, 'home.html', {
        'charge': charge,
    })

Đầu tiên chúng tôi khởi tạo ứng dụng khách bằng cách chuyển COINBASE_COMMERCE_API_KEYcho nó. Sau đó, chúng tôi tạo một đối tượng JSON đại diện cho sản phẩm của chúng tôi (chúng tôi đã cung cấp tên, mô tả, v.v.). Chúng tôi cũng đã thông qua redirect_urlcancel_urltính phí mà chúng tôi sẽ sớm triển khai tại đây. Sau đó, chúng tôi giải nén đối tượng JSON và sử dụng ứng dụng khách để tạo một khoản phí. Cuối cùng, chúng tôi chuyển nó sang mẫu home làm ngữ cảnh.

Giờ đây, chúng tôi có thể truy cập thông tin phí trong template / home.html . Cập nhật mẫu như vậy:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <div class="card-body">
          <h5 class="card-title">{{ charge.name }}</h5>
          <p class="card-text">
            <span>{{ charge.description }}</span>
            <br>
            <span>${{ charge.pricing.local.amount }} {{ charge.pricing.local.currency }}</span>
          </p>
          <div>
            <a class="btn btn-primary w-100" href="{{ charge.hosted_url }}">Purchase</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Tham khảo tài liệu API tính phí để biết tất cả thông tin liên quan đến phí mà bạn có thể hiển thị trên mẫu.

Chạy máy chủ phát triển:

(env)$ python manage.py runserver

http: // localhost: 8000 / bây giờ sẽ giống như sau:

Trang chủ Django + Coinbase

Đừng kiểm tra nó ra được nêu ra. Chúng tôi sẽ làm điều đó trong thời gian ngắn.

Tạo Chế độ xem chuyển hướng

Hãy triển khai các lượt xem redirect_urlcancel_urlchúng ta đã chuyển sang phần phụ trách.

Tạo hai chế độ xem mới bên trong Payment / views.py :

# payments/views.py

def success_view(request):
    return render(request, 'success.html', {})


def cancel_view(request):
    return render(request, 'cancel.html', {})

Đăng ký các chế độ xem mới bên trong Payment / urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'), # new
    path('cancel/', views.cancel_view, name='payments-cancel'), # new
]

các mẫu / thành công.html :

<!-- templates/success.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been successful.</p>
    </div>
  </body>
</html>

các mẫu / hủy bỏ.html :

<!-- templates/cancel.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been cancelled.</p>
    </div>
  </body>
</html>

Bây giờ, sau khi thanh toán được xác nhận, người dùng sẽ được chuyển hướng đến redirect_url. Trong trường hợp họ hủy thanh toán (hoặc hết thời gian tính phí), họ sẽ được chuyển hướng đến cancel_url.

Thử nghiệm

Rất tiếc, Coinbase Commerce không hỗ trợ tài khoản hộp cát để thử nghiệm, có nghĩa là bạn sẽ cần sử dụng tiền điện tử thực để kiểm tra ứng dụng của mình.

Chạy máy chủ, điều hướng đến http: // localhost: 8000 / và nhấp vào nút "Mua". Bạn sẽ được chuyển hướng đến trang web được lưu trữ trên Coinbase Commerce:

Phí thương mại trên Coinbase

Khi bạn chọn một loại tiền điện tử mà bạn muốn thanh toán, địa chỉ ví (và mã QR) sẽ được hiển thị:

Địa chỉ tính phí thương mại trên Coinbase

Sau đó, bạn có 60 phút để chuyển tiền điện tử trước khi hết thời gian tính phí.

Sau khi bạn gửi tiền điện tử, sẽ mất vài phút (tùy thuộc vào loại tiền điện tử bạn sử dụng) để các thợ đào xác nhận giao dịch của bạn. Sau khi giao dịch nhận được số lượng xác nhận cần thiết (dựa trên tiền điện tử), bạn sẽ được chuyển hướng đến URL được liên kết với redirect_url.

Các khoản thanh toán sẽ xuất hiện trong Trang tổng quan thương mại trong "Thanh toán":

Thanh toán thương mại trên Coinbase

Bỏ qua phần "Xác nhận thanh toán với Webhooks" để tìm hiểu về xác nhận thanh toán.

Kiểm tra Coinbase

Phần này của hướng dẫn cho biết cách chấp nhận thanh toán bằng API Coinbase Checkout . Nếu bạn quyết định sử dụng Coinbase Charges, vui lòng bỏ qua phần này và chuyển xuống phần "Xác nhận thanh toán bằng Webhooks".

Coinbase Checkout is the easiest way to collect crypto payments with Coinbase Commerce. With this approach, charges will automatically be generated for you. This approach is appropriate when working with fixed products.

Workflow:

  1. Use a client to connect to the Coinbase Commerce API
  2. Fetch a checkout from Coinbase Commerce API and pass it to the template
  3. (Optional) Add the required HTML code to the template if dealing with embedded checkouts
  4. Redirect the user to Coinbase Commerce hosted site OR use an embedded checkout
  5. (Optional) Verify the charge using webhooks

Create a Checkout

There are two ways of creating a checkout:

  1. Programmatically via the coinbase-commerce library
  2. Manually within the Coinbase Commerce dashboard

For simplicity, we'll use the Commerce Dashboard.

Điều hướng đến "Checkout" và nhấp vào "Create Checkout":

Coinbase Commerce Checkout

Nhấp vào "Bán Sản phẩm". Nhập tên sản phẩm, mô tả và giá cả. Nhấn tiếp". Trong "Thông tin khách hàng", chọn "Không thu thập bất kỳ thông tin nào". Sau đó, nhấp vào "Xong.

Coinbase Commerce đã tạo tất cả mã HTML cần thiết mà bạn cần thêm vào mẫu trang chủ của mình. Bạn có thể thấy điều này trong tab "Nhúng". Để làm cho ứng dụng web có nhiều mô-đun hơn và có thể tái sử dụng, chúng tôi sẽ tìm nạp thông tin thanh toán trong home_viewthay vì mã hóa cứng trong mẫu. Để làm như vậy, trước tiên chúng tôi cần lấy ID thanh toán bằng cách sao chép URL trang được lưu trữ:

Coinbase Commerce Checkout

Liên kết vĩnh viễn sẽ trông giống như sau:

https://commerce.coinbase.com/checkout/df2d7c68-145e-4537-86fa-1cac705eb748

Chúng tôi chỉ quan tâm đến phân đoạn cuối cùng của URL, đại diện cho ID thanh toán:

df2d7c68-145e-4537-86fa-1cac705eb748

Lưu cái này bên trong tệp core / settings.py như sau:

# core/settings.py

COINBASE_CHECKOUT_ID = '<your checkout id>'

Cập nhật các khoản thanh toán / views.py :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    checkout = client.checkout.retrieve(settings.COINBASE_CHECKOUT_ID)
    checkout_link = f'https://commerce.coinbase.com/checkout/{checkout.id}'

    return render(request, 'home.html', {
        'checkout': checkout,
        'checkout_link': checkout_link,
    })

Mã này tìm nạp thanh toán và chuyển nó đến mẫu.

Cuối cùng, chúng ta cần sửa đổi mẫu trang chủ để sử dụng thanh toán. Bạn có thể sử dụng:

  1. Trang được lưu trữ - người dùng được chuyển hướng đến trang web Coinbase Checkout
  2. Trang được nhúng - mọi thứ diễn ra trên trang web của bạn

Đối với mục đích giáo dục, chúng tôi sẽ sử dụng cả hai cách tiếp cận.

Cập nhật các mẫu / home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Checkout</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <!-- Coinbase checkout details -->
        <div class="card-body">
          <h5 class="card-title">{{ checkout.name }}</h5>
          <p class="card-text">
            {{ checkout.description }}<br>
            {{ checkout.local_price.amount }} {{ checkout.local_price.currency }}
          </p>
          <div>
            <!-- Coinbase hosted approach (script not required) -->
            <a class="btn btn-primary w-100" href="{{ checkout_link }}">Purchase (hosted)</a>
            <!-- Coinbase embedded approach (script required) -->
            <div class="mt-2">
              <a class="btn btn-primary buy-with-crypto w-100" href="{{ checkout_link }}">Purchase (embedded)</a>
              <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Chạy máy chủ và điều hướng đến http: // localhost: 8000 / :

Ví dụ về thanh toán bằng Coinbase Commerce

Ứng dụng hoàn toàn hoạt động tại thời điểm này. Đừng thử nghiệm bất cứ điều gì chỉ được nêu ra. Chúng tôi sẽ làm điều đó trong phần tiếp theo.

Thử nghiệm

Rất tiếc, Coinbase Commerce không hỗ trợ tài khoản hộp cát để thử nghiệm, có nghĩa là bạn sẽ cần sử dụng tiền điện tử thực để kiểm tra ứng dụng của mình.

Khi máy chủ đang chạy, điều hướng đến http: // localhost: 8000 / . Bạn có thể kiểm tra bằng cách sử dụng trang web được lưu trữ trên Coinbase hoặc thanh toán được nhúng. Lựa chọn của bạn.

Khi bạn chọn một loại tiền điện tử mà bạn muốn thanh toán, địa chỉ ví (và mã QR) sẽ được hiển thị:

Địa chỉ tính phí thương mại trên Coinbase

Sau đó, bạn có 60 phút để chuyển tiền điện tử trước khi hết thời gian tính phí.

Sau khi bạn gửi tiền điện tử, sẽ mất vài phút (tùy thuộc vào loại tiền điện tử bạn sử dụng) để các thợ đào xác nhận giao dịch của bạn. Sau khi giao dịch nhận được số lượng xác nhận cần thiết (dựa trên tiền điện tử), bạn sẽ được hiển thị với thông báo "Thanh toán hoàn tất".

Các khoản thanh toán sẽ xuất hiện trong Trang tổng quan thương mại trong "Thanh toán":

Thanh toán thương mại trên Coinbase

Xác nhận thanh toán bằng Webhooks

Ứng dụng của chúng tôi hoạt động tốt vào thời điểm này, nhưng chúng tôi chưa thể xác nhận thanh toán theo chương trình. Chúng tôi chỉ chuyển hướng người dùng đến trang thành công sau khi họ kiểm tra, nhưng chúng tôi không thể chỉ dựa vào trang đó vì xác nhận thanh toán xảy ra không đồng bộ.

Bạn thường xử lý hai loại sự kiện khác nhau khi lập trình: Sự kiện đồng bộ, có hiệu lực và kết quả tức thì (ví dụ: tạo một khoản phí) và sự kiện không đồng bộ, không có kết quả ngay lập tức (ví dụ: xác nhận thanh toán). Bởi vì xác nhận thanh toán được thực hiện không đồng bộ, người dùng có thể được chuyển hướng đến trang thành công trước khi thanh toán của họ được xác nhận và trước khi chúng tôi nhận được tiền của họ.

Để nhận thông báo khi thanh toán được thực hiện, bạn cần tạo webhook . Chúng tôi sẽ cần tạo một điểm cuối đơn giản trong ứng dụng của mình, mà Coinbase Commerce sẽ gọi bất cứ khi nào có sự kiện xảy ra (tức là khi khoản phí được xác nhận). Bằng cách sử dụng webhooks, chúng tôi có thể chắc chắn rằng khoản thanh toán đã được thực hiện thành công.

Để sử dụng webhook, chúng ta cần:

  1. Thiết lập điểm cuối webhook trong ứng dụng
  2. Đăng ký điểm cuối trong Bảng điều khiển Coinbase Commerce

Định cấu hình Điểm cuối

Tạo coinbase_webhookchế độ xem trong Payment / views.py :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            # TODO: run some custom code here

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Khối mã này xác thực chữ ký và trọng tải của yêu cầu, sau đó tạo ra một sự kiện từ nó. Bây giờ bạn có thể kiểm tra loại sự kiện và thực hiện các hành động khác nhau dựa trên loại.

Cập nhật các lần nhập:

import logging

from coinbase_commerce.client import Client
from coinbase_commerce.error import SignatureVerificationError, WebhookInvalidPayload
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from core import settings

Bỏ qua lỗi COINBASE_COMMERCE_WEBHOOK_SHARED_SECRETchưa tồn tại. Chúng tôi sẽ thêm nó trong bước tiếp theo.

Đăng ký URL trong Payment / urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'),   # only for the Coinbase charges approach
    path('cancel/', views.cancel_view, name='payments-cancel'),      # only for the Coinbase charges approach
    path('webhook/', views.coinbase_webhook),  # new
]

Chế coinbase_webhookđộ xem hiện đóng vai trò là điểm cuối webhook của chúng tôi mà Coinbase Commerce sẽ gửi các sự kiện đến khi chúng xảy ra.

Nếu bạn đã làm theo cách tiếp cận Coinbase Checkout, đừng bao gồm success/hoặc cancel/URL.

Xác định Người dùng

Để xác định người dùng trong webhook của bạn, bạn cần chuyển một số siêu dữ liệu khi tạo khoản phí hoặc khi bắt đầu phiên thanh toán. Sau đó, bạn sẽ có thể tìm nạp siêu dữ liệu này bên trong webhook của mình.

Cách bạn chuyển siêu dữ liệu là khác nhau tùy thuộc vào cách bạn đã sử dụng:

  1. API tính phí - bạn sẽ phải đính kèm siêu dữ liệu vào sản phẩm
  2. API Checkout - bạn sẽ phải chuyển siêu dữ liệu dưới dạng thuộc tính HTML

Xác định người dùng bằng API tính phí

Để xác định người dùng với API tính phí, hãy bắt đầu bằng cách thêm thông tin sau vào lệnh productbên trong home_view:

# payments/views.py

product = {
    ...
    'metadata': {
        'customer_id': request.user.id if request.user.is_authenticated else None,
        'customer_username': request.user.username if request.user.is_authenticated else None,
    },
    ...
}

Khối mã này đính kèm ID người dùng và tên người dùng từ người dùng đã xác thực.

Bây giờ bạn có thể truy cập siêu dữ liệu bên trong dạng coinbase_webhookxem như sau:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['customer_id'] # new
            customer_username = event['data']['metadata']['customer_username'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id' or 'customer_username'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Xác định Người dùng bằng API Checkout

Để xác định người dùng bằng API Checkout, chúng tôi cần thêm siêu dữ liệu làm data-customthuộc tính dữ liệu vào các liên kết trong tệp mẫu / home.html :

Ví dụ:

<div>
  <!-- Coinbase hosted approach (script not required) -->
  <a
    class="btn btn-primary w-100"
    {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
    href="{{ checkout_link }}"
  >Purchase (hosted)</a>
  <!-- Coinbase embedded approach (script required) -->
  <div class="mt-2">
    <a
      class="btn btn-primary buy-with-crypto w-100"
      {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
      href="{{ checkout_link }}"
    >Purchase (embedded)</a>
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
  </div>
</div>

Sau đó, bạn có thể truy xuất siêu dữ liệu bên trong dạng coinbase_webhookxem như sau:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    import logging

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['custom'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Hãy nhớ rằng webhook nhận data-customdưới dạng văn bản thuần túy. Đảm bảo phân tích cú pháp nó thành một số nguyên trước khi sử dụng nó để tìm nạp người dùng từ cơ sở dữ liệu.

Đăng ký điểm cuối

Điều hướng đến https://commerce.coinbase.com/dashboard/settings , cuộn xuống "Đăng ký Webhook" và nhấp vào "Thêm điểm cuối":

Coinbase Commerce Webhook

Nhập URL điểm cuối của bạn và nhấn "Lưu".

URL cần bắt đầu bằng HTTPS, có nghĩa là bạn cần triển khai ứng dụng của mình trước khi có thể kiểm tra.

Tiếp theo, nhấp vào "Hiển thị bí mật được chia sẻ" và sao chép bí mật:

Bí mật webhook của Coinbase Commerce

Thêm bí mật được chia sẻ vào tệp settings.py như sau:

# core/settings.py

COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET = '<your coinbase webhook secret here>'

Kiểm tra điểm cuối

Khi ứng dụng của bạn được triển khai, bạn có thể gửi yêu cầu webhook thử nghiệm từ Trang tổng quan thương mại . Điều hướng đến "Đăng ký Webhook" và nhấp vào "Chi tiết" dưới điểm cuối webhook:

Chi tiết về Coinbase Commerce Webhook

Sau đó nhấp vào "Gửi kiểm tra":

Kiểm tra chi tiết Coinbase Commerce Webhook

Cuối cùng, chọn "phí: đã xác nhận" và nhấp vào "Gửi thử nghiệm" một lần nữa. Bạn sẽ thấy thông báo "Thanh toán đã thành công." nhật ký tin nhắn.

Sự kết luận

Trong hướng dẫn này, bạn đã học cách chấp nhận thanh toán tiền điện tử với Coinbase Commerce. Bây giờ bạn có thể tích hợp nó với Django và xác minh thanh toán qua webhook.

Bạn có thể tìm thấy mã trong các kho sau trên GitHub:

  1. django-coinbase-charge
  2. django-coinbase-checkout

Nguồn:  https://testdriven.io

#django #crypto #coinbase 

Chấp Nhận Thanh Toán Bằng Tiền Điện Tử Với Django Và Coinbase

Прием криптовалютных платежей с помощью Django и Coinbase

В этом руководстве мы интегрируем Django с Coinbase Commerce, чтобы принимать различные криптовалютные платежи. Мы рассмотрим два разных подхода: Coinbase Charges и Coinbase Checkout.

Что такое Coinbase Commerce?

Coinbase Commerce — это корпоративный сервис цифровых платежей, предлагаемый Coinbase, который позволяет продавцам принимать криптовалютные платежи в различных цифровых валютах. На момент написания они поддерживают Биткойн, Биткойн Кэш, DAI, Ethereum, Litecoin, Dogecoin и USD Coin. Coinbase Commerce легко интегрируется в ваше веб-приложение и избавляет от хлопот, связанных с криптовалютными платежами.

Coinbase и Coinbase Commerce — это не одно и то же. Coinbase — это криптобиржа и менеджер кошельков, а Coinbase Commerce — поставщик услуг цифровых платежей для продавцов.

Coinbase Commerce API предоставляет два разных способа приема криптовалютных платежей: Coinbase Charges и Coinbase Checkout.

Преимущества платежей Coinbase:

  • настраиваемый
  • возможность программно присоединять метаданные

Преимущества кассы Coinbase:

  • работает из коробки
  • панель управления продуктом
  • встроенная касса

Для большинства приложений мы рекомендуем Charges API, так как его можно настроить. Это перевешивает простоту, которую предлагает Checkout API. Если вы продаете фиксированный продукт и настройка не играет большой роли, не стесняйтесь использовать Checkout API.

Настройка проекта

В этом руководстве мы покажем, как запустить оба подхода, Coinbase Charges и Coinbase Checkout. Мы начнем с одинаковой настройки проекта для каждого из них. После настройки не стесняйтесь следовать одному или обоим подходам.

Настройка проекта Джанго

Начните с создания нового каталога и настройки нового проекта Django:

$ mkdir django-coinbase && cd django-coinbase
$ python3.9 -m venv env
$ source env/bin/activate

(env)$ pip install django==3.2.8
(env)$ django-admin startproject core .

После этого создайте новое приложение с именем payments:

(env)$ python manage.py startapp payments

Зарегистрируйте приложение в core/settings.py в разделе INSTALLED_APPS:

# core/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payments.apps.PaymentsConfig', # new
]

Добавьте простое функциональное представление, вызываемое home_viewв Payments/views.py :

# payments/views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

Создайте файл urls.py внутри paymentsприложения:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
]

Обновите файл URL-адресов на уровне проекта с помощью paymentsприложения:

# core/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payments.urls')), # new
    path('admin/', admin.site.urls),
]

Создайте специальную папку «templates» и файл для домашней страницы:

(env)$ mkdir templates
(env)$ touch templates/home.html

Затем добавьте следующий HTML-код в templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <a class="btn btn-primary" href="#">Purchase</a>
    </div>
  </body>
</html>

Обязательно обновите файл settings.py, чтобы Django знал, что нужно искать папку «templates»:

# core/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], # new
        ...

Наконец, запустите migrate, чтобы синхронизировать базу данных и runserverзапустить локальный веб-сервер Django:

(env)$ python manage.py migrate
(env)$ python manage.py runserver

Вот и все! Откройте http://localhost:8000/ в своем любимом браузере. Вы должны увидеть главную страницу:

Домашняя страница Django + Coinbase

Добавить коммерцию Coinbase

Далее устанавливаем coinbase-commerce:

(env)$ pip install coinbase-commerce==1.0.1

Для работы с Coinbase Commerce API вам необходимо создать учетную запись (если вы еще этого не сделали). После создания учетной записи войдите в систему и перейдите к настройкам. Прокрутите вниз до раздела «Ключи API», нажмите «Создать ключ API», а затем «Показать». Скопируйте ключ API в буфер обмена.

API-ключи Coinbase

Затем добавьте ключ в файл settings.py :

# core/settings.py

COINBASE_COMMERCE_API_KEY = '<your coinbase api key here>'

Прежде чем перейти к следующему шагу, давайте проверим, можем ли мы получить данные из API. Войдите в оболочку Python, используя следующую команду:

(env)$ python manage.py shell

Импортируйте следующее:

>>> from core import settings
>>> from coinbase_commerce.client import Client

Инициализируйте нового клиента и перечислите расходы:

>>> client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
>>> for charge in client.charge.list_paging_iter():
...     print("{!r}".format(charge))

Если все работает, client.charge.list_paging_iter()должен быть пустой список. Пока вы не видите следующую ошибку, вы можете считать, что все в порядке:

coinbase_commerce.error.AuthenticationError: Request id 10780b77-1021-4b09-b53b-a590ea044380: No such API key.

Полезные страницы для работы с Coinbase API:

При этом решите, какой подход вы хотите использовать, Coinbase Charges или Coinbase Checkout.

Комиссия Coinbase

В этой части руководства показано, как принимать платежи с помощью Coinbase Charges API .

Coinbase Charges — это наиболее настраиваемый подход к сбору платежей в криптовалюте. При таком подходе вы имеете полный контроль над начислениями.

Рабочий процесс:

  1. Используйте клиент для подключения к Coinbase Commerce API
  2. Создать платеж (из JSON)
  3. Получить вновь созданный платеж и передать его в шаблон
  4. Перенаправить пользователя на сайт, размещенный на Coinbase Commerce.
  5. (Необязательно) Подтвердите списание средств с помощью веб-перехватчиков.

Создать заряд

Чтобы запросить платеж в криптовалюте, вы создаете платеж . Поскольку криптовалютные платежи являются платежами push , срок действия платежа истекает после периода ожидания, если платеж не был обнаружен. Начисления идентифицируются уникальным 8-значным кодом.

Обновление home_viewдля создания заряда :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    domain_url = 'http://localhost:8000/'
    product = {
        'name': 'Coffee',
        'description': 'A really good local coffee.',
        'local_price': {
            'amount': '5.00',
            'currency': 'USD'
        },
        'pricing_type': 'fixed_price',
        'redirect_url': domain_url + 'success/',
        'cancel_url': domain_url + 'cancel/',
    }
    charge = client.charge.create(**product)

    return render(request, 'home.html', {
        'charge': charge,
    })

Сначала мы инициализировали клиента, перейдя COINBASE_COMMERCE_API_KEYк нему. Затем мы создали объект JSON, который представляет наш продукт (мы предоставили имя, описание и т. д.). Мы также перешли redirect_urlи cancel_urlк плате, которую мы реализуем здесь в ближайшее время. Затем мы распаковали объект JSON и использовали клиент для создания платежа. Наконец, мы передали его в домашний шаблон в качестве контекста.

Теперь мы можем получить доступ к информации о платежах в templates/home.html . Обновите шаблон следующим образом:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <div class="card-body">
          <h5 class="card-title">{{ charge.name }}</h5>
          <p class="card-text">
            <span>{{ charge.description }}</span>
            <br>
            <span>${{ charge.pricing.local.amount }} {{ charge.pricing.local.currency }}</span>
          </p>
          <div>
            <a class="btn btn-primary w-100" href="{{ charge.hosted_url }}">Purchase</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Обратитесь к документации Charge API для получения всей информации, связанной с оплатой, которую вы можете отобразить в шаблоне.

Запустите сервер разработки:

(env)$ python manage.py runserver

http://localhost:8000/ теперь должен выглядеть так:

Домашняя страница Django + Coinbase

Пока не тестируйте. Мы сделаем это в ближайшее время.

Создайте представления перенаправления

Давайте реализуем представления для redirect_urlи cancel_urlкоторые мы передали в плату.

Создайте два новых представления внутри Payments/views.py :

# payments/views.py

def success_view(request):
    return render(request, 'success.html', {})


def cancel_view(request):
    return render(request, 'cancel.html', {})

Зарегистрируйте новые представления внутри Payments/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'), # new
    path('cancel/', views.cancel_view, name='payments-cancel'), # new
]

И templates/success.html :

<!-- templates/success.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been successful.</p>
    </div>
  </body>
</html>

И templates/cancel.html :

<!-- templates/cancel.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been cancelled.</p>
    </div>
  </body>
</html>

Теперь, после подтверждения платежа, пользователь будет перенаправлен на redirect_url. В случае отмены платежа (или истечения времени списания) они будут перенаправлены на cancel_url.

Тестирование

К сожалению, Coinbase Commerce не поддерживает учетные записи песочницы для тестирования, а это означает, что вам нужно будет использовать настоящую криптографию для тестирования вашего приложения.

Запустите сервер, перейдите по адресу http://localhost:8000/ и нажмите кнопку «Купить». Вы будете перенаправлены на сайт, размещенный на Coinbase Commerce:

Комиссионные сборы Coinbase

Когда вы выбираете криптовалюту, которой хотите заплатить, будет показан адрес кошелька (и QR-код):

Адреса для комиссий Coinbase Commerce

Затем у вас есть 60 минут, чтобы перевести криптовалюту, прежде чем истечет время списания.

После того, как вы отправите криптовалюту, майнерам потребуется несколько минут (в зависимости от того, какую криптовалюту вы используете), чтобы подтвердить вашу транзакцию. После того, как транзакция получит необходимое количество подтверждений (в зависимости от криптовалюты), вы будете перенаправлены на URL-адрес, связанный с redirect_url.

Платежи появятся на панели управления коммерции в разделе «Платежи»:

Торговые платежи Coinbase

Перейдите к разделу «Подтверждение платежей с помощью веб-перехватчиков», чтобы узнать о подтверждении платежей.

Коинбейс Оформить заказ

В этой части руководства показано, как принимать платежи с помощью Coinbase Checkout API . Если вы решили использовать Coinbase Charges, не стесняйтесь пропустить этот раздел и перейти к разделу «Подтверждение платежей с помощью веб-перехватчиков».

Coinbase Checkout — это самый простой способ сбора криптовалютных платежей с помощью Coinbase Commerce. При таком подходе начисления будут автоматически генерироваться для вас. Такой подход уместен при работе с фиксированными продуктами.

Рабочий процесс:

  1. Используйте клиент для подключения к Coinbase Commerce API
  2. Получите кассу из API Coinbase Commerce и передайте ее в шаблон
  3. (Необязательно) Добавьте в шаблон необходимый HTML-код, если имеете дело со встроенными проверками.
  4. Перенаправьте пользователя на сайт, размещенный на Coinbase Commerce, ИЛИ используйте встроенную кассу.
  5. (Необязательно) Подтвердите списание средств с помощью веб-перехватчиков.

Создать кассу

Существует два способа создания кассы:

  1. Программно через библиотеку coinbase-commerce
  2. Вручную на панели инструментов Coinbase Commerce

Для простоты мы будем использовать Commerce Dashboard .

Перейдите в «Кассы» и нажмите «Создать кассу»:

Коинбейс Коммерс Касс

Нажмите «Продать товар». Введите название продукта, описание и цену. Нажмите "Далее". В разделе «Информация о клиенте» выберите «Не собирать информацию». Затем нажмите «Готово».

Coinbase Commerce сгенерировала весь необходимый HTML-код, который вам нужно добавить в свой домашний шаблон. Это можно увидеть на вкладке «Встроить». Чтобы сделать веб-приложение более модульным и пригодным для повторного использования, мы будем получать информацию о кассе home_viewвместо того, чтобы жестко кодировать ее в шаблоне. Для этого нам сначала нужно получить идентификатор проверки, скопировав URL-адрес размещенной страницы:

Коинбейс Коммерс Касс

Постоянная ссылка должна выглядеть примерно так:

https://commerce.coinbase.com/checkout/df2d7c68-145e-4537-86fa-1cac705eb748

Нас интересует только последний сегмент URL-адреса, который представляет собой идентификатор оформления заказа:

df2d7c68-145e-4537-86fa-1cac705eb748

Сохраните это в файле core/settings.py следующим образом:

# core/settings.py

COINBASE_CHECKOUT_ID = '<your checkout id>'

Обновите платежи/views.py :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    checkout = client.checkout.retrieve(settings.COINBASE_CHECKOUT_ID)
    checkout_link = f'https://commerce.coinbase.com/checkout/{checkout.id}'

    return render(request, 'home.html', {
        'checkout': checkout,
        'checkout_link': checkout_link,
    })

Этот код извлекает кассу и передает ее в шаблон.

Наконец, нам нужно изменить домашний шаблон, чтобы использовать кассу. Вы можете либо использовать:

  1. Размещенная страница — пользователь перенаправляется на веб-сайт Coinbase Checkout.
  2. Встроенная страница - все происходит на вашем сайте

В образовательных целях мы будем использовать оба подхода.

Обновите шаблоны/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Checkout</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <!-- Coinbase checkout details -->
        <div class="card-body">
          <h5 class="card-title">{{ checkout.name }}</h5>
          <p class="card-text">
            {{ checkout.description }}<br>
            {{ checkout.local_price.amount }} {{ checkout.local_price.currency }}
          </p>
          <div>
            <!-- Coinbase hosted approach (script not required) -->
            <a class="btn btn-primary w-100" href="{{ checkout_link }}">Purchase (hosted)</a>
            <!-- Coinbase embedded approach (script required) -->
            <div class="mt-2">
              <a class="btn btn-primary buy-with-crypto w-100" href="{{ checkout_link }}">Purchase (embedded)</a>
              <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Запустите сервер и перейдите по адресу http://localhost:8000/ :

Пример оформления заказа на Coinbase Commerce

На данный момент приложение полностью функционально. Пока ничего не тестируйте. Мы сделаем это в следующем разделе.

Тестирование

К сожалению, Coinbase Commerce не поддерживает учетные записи песочницы для тестирования, а это означает, что вам нужно будет использовать настоящую криптографию для тестирования вашего приложения.

Когда сервер запущен, перейдите по адресу http://localhost:8000/ . Вы можете проверить, используя размещенный на Coinbase сайт или встроенную кассу. Твой выбор.

Когда вы выбираете криптовалюту, которой хотите заплатить, будет показан адрес кошелька (и QR-код):

Адреса для комиссий Coinbase Commerce

Затем у вас есть 60 минут, чтобы перевести криптовалюту, прежде чем истечет время списания.

После того, как вы отправите криптовалюту, майнерам потребуется несколько минут (в зависимости от того, какую криптовалюту вы используете), чтобы подтвердить вашу транзакцию. После того, как транзакция получит необходимое количество подтверждений (в зависимости от криптовалюты), вы увидите сообщение «Платеж завершен».

Платежи появятся на панели управления коммерции в разделе «Платежи»:

Торговые платежи Coinbase

Подтверждение платежей с помощью вебхуков

На данный момент наше приложение работает хорошо, но мы пока не можем программно подтверждать платежи. Мы просто перенаправляем пользователя на страницу успеха после оформления заказа, но мы не можем полагаться только на эту страницу, поскольку подтверждение платежа происходит асинхронно.

При программировании вы часто имеете дело с двумя разными типами событий: синхронными событиями, которые имеют немедленный эффект и результаты (например, создание платежа), и асинхронными событиями, которые не имеют немедленного результата (например, подтверждение платежей). Поскольку подтверждение платежа выполняется асинхронно, пользователь может быть перенаправлен на страницу успеха до того , как его платеж будет подтвержден и до того, как мы получим его средства.

Чтобы получать уведомления о прохождении платежа, вам нужно создать вебхук . Нам нужно создать простую конечную точку в нашем приложении, которую Coinbase Commerce будет вызывать всякий раз, когда происходит событие (т. е. когда платеж подтверждается). Используя вебхуки, мы можем быть уверены, что платеж прошел успешно.

Чтобы использовать вебхуки, нам нужно:

  1. Настройте конечную точку веб-перехватчика в приложении
  2. Зарегистрируйте конечную точку в Coinbase Commerce Dashboard.

Настройте конечную точку

Создайте coinbase_webhookпредставление в Payments/views.py :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            # TODO: run some custom code here

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Этот блок кода проверяет подпись и полезную нагрузку запроса, а затем генерирует на их основе событие. Теперь вы можете проверить тип события и выполнить различные действия в зависимости от типа.

Обновите импорт:

import logging

from coinbase_commerce.client import Client
from coinbase_commerce.error import SignatureVerificationError, WebhookInvalidPayload
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from core import settings

Игнорируйте ошибку, которой COINBASE_COMMERCE_WEBHOOK_SHARED_SECRETеще не существует. Мы добавим его на следующем шаге.

Зарегистрируйте URL-адрес в payment/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'),   # only for the Coinbase charges approach
    path('cancel/', views.cancel_view, name='payments-cancel'),      # only for the Coinbase charges approach
    path('webhook/', views.coinbase_webhook),  # new
]

Представление coinbase_webhookтеперь служит нашей конечной точкой веб-перехватчика, на которую Coinbase Commerce будет отправлять события, когда они происходят.

Если вы следовали подходу Coinbase Checkout, не включайте success/или cancel/URL-адреса.

Идентифицировать пользователя

Чтобы идентифицировать пользователя в вашем вебхуке, вам необходимо передать некоторые метаданные при создании платежа или при запуске сеанса оформления заказа. Затем вы сможете получить эти метаданные внутри своего веб-хука.

Способ передачи метаданных зависит от того, какой подход вы использовали:

  1. API начислений - вам нужно будет прикрепить метаданные к продукту
  2. Checkout API — вам нужно будет передать метаданные в виде HTML-атрибута.

Идентифицируйте пользователя с помощью Charges API

Чтобы идентифицировать пользователя с помощью Charges API, начните с добавления следующего в productdict внутри home_view:

# payments/views.py

product = {
    ...
    'metadata': {
        'customer_id': request.user.id if request.user.is_authenticated else None,
        'customer_username': request.user.username if request.user.is_authenticated else None,
    },
    ...
}

Этот блок кода прикрепляет идентификатор пользователя и имя пользователя от аутентифицированного пользователя.

Теперь вы можете получить доступ к метаданным внутри coinbase_webhookпредставления следующим образом:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['customer_id'] # new
            customer_username = event['data']['metadata']['customer_username'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id' or 'customer_username'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Идентифицируйте пользователя с помощью Checkout API

Чтобы идентифицировать пользователя с помощью Checkout API, нам нужно добавить метаданные в качестве data-customатрибута данных к привязкам в templates/home.html :

Например:

<div>
  <!-- Coinbase hosted approach (script not required) -->
  <a
    class="btn btn-primary w-100"
    {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
    href="{{ checkout_link }}"
  >Purchase (hosted)</a>
  <!-- Coinbase embedded approach (script required) -->
  <div class="mt-2">
    <a
      class="btn btn-primary buy-with-crypto w-100"
      {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
      href="{{ checkout_link }}"
    >Purchase (embedded)</a>
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
  </div>
</div>

Затем вы можете получить метаданные внутри coinbase_webhookпредставления следующим образом:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    import logging

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['custom'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Имейте в виду, что вебхук получает data-customкак обычный текст. Обязательно проанализируйте его до целого числа, прежде чем использовать его для извлечения пользователя из базы данных.

Зарегистрируйте конечную точку

Перейдите к https://commerce.coinbase.com/dashboard/settings , прокрутите вниз до «Подписки на веб-перехватчики» и нажмите «Добавить конечную точку»:

Веб-хук Coinbase Commerce

Введите URL-адрес конечной точки и нажмите «Сохранить».

URL-адрес должен начинаться с HTTPS, а это означает, что вам необходимо развернуть приложение, прежде чем вы сможете его протестировать.

Далее нажмите «Показать общий секрет» и скопируйте секрет:

Секрет вебхука Coinbase Commerce

Добавьте общий секрет в файл settings.py следующим образом:

# core/settings.py

COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET = '<your coinbase webhook secret here>'

Протестируйте конечную точку

Развернув приложение, вы можете отправить тестовый запрос веб-перехватчика из Commerce Dashboard . Перейдите к «Подписки на веб-перехватчик» и нажмите «Подробности» под конечной точкой веб-перехватчика:

Детали веб-хука Coinbase Commerce

Затем нажмите «Отправить тест»:

Детальный тест Coinbase Commerce Webhook

Наконец, выберите «зарядка: подтверждено» и снова нажмите «Отправить тест». Вы должны увидеть сообщение «Платеж прошел успешно». сообщение журнала.

Вывод

Из этого руководства вы узнали, как принимать криптовалютные платежи с помощью Coinbase Commerce. Теперь вы сможете интегрировать его с Django и проверять платежи через веб-перехватчик.

Вы можете найти код в следующих репозиториях на GitHub:

  1. django-coinbase-заряды
  2. django-coinbase-checkout

Источник:  https://testdriven.io

#django #crypto #coinbase 

Прием криптовалютных платежей с помощью Django и Coinbase
工藤  晃

工藤 晃

1660510560

將 Django 與 Coinbase Commerce 集成以接受加密支付

在本教程中,我們將 Django 與 Coinbase Commerce 集成以接受不同的加密支付。我們將研究兩種不同的方法:Coinbase Charges 和 Coinbase Checkout。

什麼是 Coinbase 商務?

Coinbase Commerce 是 Coinbase 提供的一種企業數字支付服務,允許商家接受不同數字貨幣的加密支付。在撰寫本文時,它們支持比特幣、比特幣現金、DAI、以太坊、萊特幣、狗狗幣和美元硬幣。Coinbase Commerce 易於集成到您的 Web 應用程序中,並消除了處理加密支付的麻煩。

Coinbase 和 Coinbase Commerce 不是一回事。Coinbase 是加密貨幣交易所和錢包管理器,而 Coinbase Commerce 是商家的數字支付服務提供商。

Coinbase Commerce API 提供了兩種不同的接受加密支付的方式:Coinbase Charges 和 Coinbase Checkout。

Coinbase 收費的優勢:

  • 高度可定制
  • 以編程方式附加元數據的能力

Coinbase Checkout 的優勢:

  • 開箱即用
  • 儀表板產品管理
  • 嵌入式結帳

對於大多數應用程序,我們建議使用 Charges API,因為它可以自定義。這勝過 Checkout API 提供的簡單性。如果您銷售的是固定產品,而定制化並不重要,請隨意使用 Checkout API。

項目設置

In this tutorial, we'll show how to get both approaches, Coinbase Charges and Coinbase Checkout, up and running. We'll start with the same project setup for each. Once set up, feel free to follow one or both approaches.

Django Project Setup

Start by creating a new directory and setting up a new Django project:

$ mkdir django-coinbase && cd django-coinbase
$ python3.9 -m venv env
$ source env/bin/activate

(env)$ pip install django==3.2.8
(env)$ django-admin startproject core .

After that, create a new app called payments:

(env)$ python manage.py startapp payments

Register the app in core/settings.py under INSTALLED_APPS:

# core/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payments.apps.PaymentsConfig', # new
]

Add a simple functional view called home_view to payments/views.py:

# payments/views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

Create a urls.py file inside the payments app:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
]

Update the project-level URLs file with the payments app:

# core/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payments.urls')), # new
    path('admin/', admin.site.urls),
]

Create a dedicated "templates" folder and a file for the homepage:

(env)$ mkdir templates
(env)$ touch templates/home.html

Then, add the following HTML to templates/home.html:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <a class="btn btn-primary" href="#">Purchase</a>
    </div>
  </body>
</html>

Make sure to update the settings.py file so Django knows to look for a "templates" folder:

# core/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], # new
        ...

Finally run migrate to sync the database and runserver to start Django's local web server:

(env)$ python manage.py migrate
(env)$ python manage.py runserver

That's it! Open http://localhost:8000/ in your favorite browser. You should see the homepage:

Django + Coinbase 主頁

Add Coinbase Commerce

Next, install coinbase-commerce:

(env)$ pip install coinbase-commerce==1.0.1

In order to work with the Coinbase Commerce API, you'll need to create an account (if you haven't already). After you've created an account, log in and navigate to your settings. Scroll down to the "API keys" section, click "Create an API key" and then "Reveal". Copy the API key to your clipboard.

Coinbase API 密鑰

Then add the key to the settings.py file:

# core/settings.py

COINBASE_COMMERCE_API_KEY = '<your coinbase api key here>'

Before moving to the next step, let's test if we can retrieve data from the API. Enter the Python shell using the following command:

(env)$ python manage.py shell

Import the following:

>>> from core import settings
>>> from coinbase_commerce.client import Client

Initialize a new client and list the charges:

>>> client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
>>> for charge in client.charge.list_paging_iter():
...     print("{!r}".format(charge))

If everything works, client.charge.list_paging_iter() should be an empty list. As long as you don't see the following error you can assume all is well:

coinbase_commerce.error.AuthenticationError: Request id 10780b77-1021-4b09-b53b-a590ea044380: No such API key.

Useful pages for working with the Coinbase API:

With that, decide which approach you'd like to take, Coinbase Charges or Coinbase Checkout.

Coinbase Charges

This part of the tutorial shows how to accept payments using the Coinbase Charges API.

Coinbase Charges is the most customizable approach for collecting crypto payments. With this approach, you have full control over the charges.

Workflow:

  1. Use a client to connect to the Coinbase Commerce API
  2. Create a charge (from JSON)
  3. Fetch the newly created charge and pass it to the template
  4. Redirect the user to the Coinbase Commerce hosted site
  5. (Optional) Verify the charge using webhooks

Create a Charge

To request a cryptocurrency payment, you create a charge. Since cryptocurrency payments are push payments, a charge will expire after a waiting period if no payment has been detected. Charges are identified by a unique 8 character code.

Update home_view to create a charge:

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    domain_url = 'http://localhost:8000/'
    product = {
        'name': 'Coffee',
        'description': 'A really good local coffee.',
        'local_price': {
            'amount': '5.00',
            'currency': 'USD'
        },
        'pricing_type': 'fixed_price',
        'redirect_url': domain_url + 'success/',
        'cancel_url': domain_url + 'cancel/',
    }
    charge = client.charge.create(**product)

    return render(request, 'home.html', {
        'charge': charge,
    })

We first initialized the client by passing COINBASE_COMMERCE_API_KEY to it. Then, we created a JSON object which represents our product (we provided the name, description, etc.). We also passed redirect_url and cancel_url to the charge, which we'll implement here shortly. We then unpacked the JSON object and used the client to create a charge. Finally, we passed it to the home template as context.

We can now access charge information in templates/home.html. Update the template like so:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <div class="card-body">
          <h5 class="card-title">{{ charge.name }}</h5>
          <p class="card-text">
            <span>{{ charge.description }}</span>
            <br>
            <span>${{ charge.pricing.local.amount }} {{ charge.pricing.local.currency }}</span>
          </p>
          <div>
            <a class="btn btn-primary w-100" href="{{ charge.hosted_url }}">Purchase</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Refer to the Charge API documentation for all the charge-related info that you can display on the template.

Run the development server:

(env)$ python manage.py runserver

http://localhost:8000/ should now look like this:

Django + Coinbase 主頁

Don't test it out yet. We'll do that shortly.

Create the Redirect Views

Let's implement the views for redirect_url and cancel_url that we passed to the charge.

Create two new views inside payments/views.py:

# payments/views.py

def success_view(request):
    return render(request, 'success.html', {})


def cancel_view(request):
    return render(request, 'cancel.html', {})

Register the new views inside payments/urls.py:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'), # new
    path('cancel/', views.cancel_view, name='payments-cancel'), # new
]

And templates/success.html:

<!-- templates/success.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been successful.</p>
    </div>
  </body>
</html>

And templates/cancel.html:

<!-- templates/cancel.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been cancelled.</p>
    </div>
  </body>
</html>

Now, after the payment is confirmed, the user will be redirected to redirect_url. In the event that they cancel the payment (or the charge times out), they will be redirected to cancel_url.

Testing

Unfortunately, Coinbase Commerce doesn't support sandbox accounts for testing, which means that you'll need to use real crypto to test your application.

Run the server, navigate to http://localhost:8000/, and click on the "Purchase" button. You'll be redirected to the Coinbase Commerce hosted site:

Coinbase 商務收費

When you select a cryptocurrency with which you'd like to pay, a wallet address (and a QR code) will be shown:

Coinbase Commerce 收費地址

You then have 60 minutes to transfer the crypto before the charge times out.

After you send the crypto, it will take a few minutes (depending on which cryptocurrency you use) for miners to confirm your transaction. After the transaction gets the required number of confirmations (based on the cryptocurrency), you'll be redirected to the URL associated with redirect_url.

The payments will appear in the Commerce Dashboard under "Payments":

Coinbase 商業支付

Skip down to the "Confirm Payments with Webhooks" section to learn about payment confirmation.

Coinbase Checkout

This part of the tutorial shows how to accept payments using the Coinbase Checkout API. If you decided to go with Coinbase Charges, feel free to skip this section and move down to the "Confirm Payments with Webhooks" section.

Coinbase Checkout is the easiest way to collect crypto payments with Coinbase Commerce. With this approach, charges will automatically be generated for you. This approach is appropriate when working with fixed products.

Workflow:

  1. Use a client to connect to the Coinbase Commerce API
  2. Fetch a checkout from Coinbase Commerce API and pass it to the template
  3. (Optional) Add the required HTML code to the template if dealing with embedded checkouts
  4. Redirect the user to Coinbase Commerce hosted site OR use an embedded checkout
  5. (Optional) Verify the charge using webhooks

Create a Checkout

There are two ways of creating a checkout:

  1. Programmatically via the coinbase-commerce library
  2. Manually within the Coinbase Commerce dashboard

For simplicity, we'll use the Commerce Dashboard.

Navigate to "Checkouts" and click "Create Checkout":

Coinbase 商務結賬

Click "Sell a Product". Enter the product name, description, and price. Click "Next". Under "Customer information", select "Don't collect any information". Then, click "Done.

Coinbase Commerce generated all the necessary HTML code that you need to add to your home template. You can see this under the "Embed" tab. To make the web application more modular and reusable, we'll fetch the checkout info in the home_view instead of hard coding it in the template. To do so, we first need to obtain the checkout ID by copying the hosted page URL:

Coinbase 商務結賬

The permanent link should look something like this:

https://commerce.coinbase.com/checkout/df2d7c68-145e-4537-86fa-1cac705eb748

We're only interested in the last segment of the URL, which represents the checkout ID:

df2d7c68-145e-4537-86fa-1cac705eb748

Save this inside the core/settings.py file like so:

# core/settings.py

COINBASE_CHECKOUT_ID = '<your checkout id>'

Update payments/views.py:

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    checkout = client.checkout.retrieve(settings.COINBASE_CHECKOUT_ID)
    checkout_link = f'https://commerce.coinbase.com/checkout/{checkout.id}'

    return render(request, 'home.html', {
        'checkout': checkout,
        'checkout_link': checkout_link,
    })

This code fetches the checkout and passes it to the template.

Finally, we need to modify the home template to use the checkout. You can either use a:

  1. Hosted page - the user gets redirected to a Coinbase Checkout website
  2. Embedded page - everything happens on your website

For educational purposes, we'll use both approaches.

Update templates/home.html:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Checkout</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <!-- Coinbase checkout details -->
        <div class="card-body">
          <h5 class="card-title">{{ checkout.name }}</h5>
          <p class="card-text">
            {{ checkout.description }}<br>
            {{ checkout.local_price.amount }} {{ checkout.local_price.currency }}
          </p>
          <div>
            <!-- Coinbase hosted approach (script not required) -->
            <a class="btn btn-primary w-100" href="{{ checkout_link }}">Purchase (hosted)</a>
            <!-- Coinbase embedded approach (script required) -->
            <div class="mt-2">
              <a class="btn btn-primary buy-with-crypto w-100" href="{{ checkout_link }}">Purchase (embedded)</a>
              <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Run the server and navigate to http://localhost:8000/:

Coinbase Commerce 結帳示例

The application is completely functional at this point. Don't test anything just yet though. We'll do that in the next section.

Testing

Unfortunately, Coinbase Commerce doesn't support sandbox accounts for testing, which means that you'll need to use real crypto to test your application.

With the server running, navigate to http://localhost:8000/. You can test using the Coinbase hosted site or the embedded checkout. Your choice.

When you select a cryptocurrency with which you'd like to pay, a wallet address (and a QR code) will be shown:

Coinbase Commerce 收費地址

You then have 60 minutes to transfer the crypto before the charge times out.

After you send the crypto, it will take a few minutes (depending on which cryptocurrency you use) for miners to confirm your transaction. After the transaction gets the required number of confirmations (based on the cryptocurrency), you'll be presented with a "Payment complete" message.

The payments will appear in the Commerce Dashboard under "Payments":

Coinbase 商業支付

Confirm Payments with Webhooks

Our app works well at this point, but we can't programmatically confirm payments yet. We just redirect the user to the success page after they check out, but we can't rely on that page alone since payment confirmation happens asynchronously.

You often deal with two different types of events when programming: Synchronous events, which have an immediate effect and results (e.g., creating a charge), and asynchronous events, which don't have an immediate result (e.g., confirming payments). Because payment confirmation is done asynchronously, the user might get redirected to the success page before their payment is confirmed and before we receive their funds.

To get notified when the payment goes through, you need to create a webhook. We'll need to create a simple endpoint in our application, which Coinbase Commerce will call whenever an event occurs (i.e., when a charge is confirmed). By using webhooks, we can be sure the payment went through successfully.

In order to use webhooks, we need to:

  1. Set up the webhook endpoint in the application
  2. Register the endpoint in the Coinbase Commerce Dashboard

Configure the Endpoint

Create a coinbase_webhook view in payments/views.py:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            # TODO: run some custom code here

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

This block of code validates the signature and the payload of the request and then generates an event out of it. You can now check the event type and perform different actions based on the type.

Update the imports:

import logging

from coinbase_commerce.client import Client
from coinbase_commerce.error import SignatureVerificationError, WebhookInvalidPayload
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from core import settings

Ignore the error that COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET doesn't exist yet. We'll add it in the next step.

Register the URL in payments/urls.py:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'),   # only for the Coinbase charges approach
    path('cancel/', views.cancel_view, name='payments-cancel'),      # only for the Coinbase charges approach
    path('webhook/', views.coinbase_webhook),  # new
]

The coinbase_webhook view now serves as our webhook endpoint to which Coinbase Commerce will send events to when they occur.

If you followed the Coinbase Checkout approach, don't include the success/ or cancel/ URLs.

Identify the User

To identify the user in your webhook, you need to pass some metadata when creating the charge or when starting the checkout session. You'll then be able to fetch this metadata inside your webhook.

The manner in which you pass metadata is different depending on which approach you used:

  1. Charges API - you'll have to attach metadata to the product
  2. Checkout API - you'll have to pass metadata as an HTML attribute

Identify the User with the Charges API

To identify the user with the Charges API start by adding the following to the product dict inside home_view:

# payments/views.py

product = {
    ...
    'metadata': {
        'customer_id': request.user.id if request.user.is_authenticated else None,
        'customer_username': request.user.username if request.user.is_authenticated else None,
    },
    ...
}

This block of code attaches the user ID and username from the authenticated user.

You can now access the metadata inside the coinbase_webhook view like so:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['customer_id'] # new
            customer_username = event['data']['metadata']['customer_username'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id' or 'customer_username'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Identify the User with the Checkout API

要使用 Checkout API 識別用戶,我們需要將元數據作為data-custom數據屬性添加到templates/home.html中的錨點:

例如:

<div>
  <!-- Coinbase hosted approach (script not required) -->
  <a
    class="btn btn-primary w-100"
    {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
    href="{{ checkout_link }}"
  >Purchase (hosted)</a>
  <!-- Coinbase embedded approach (script required) -->
  <div class="mt-2">
    <a
      class="btn btn-primary buy-with-crypto w-100"
      {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
      href="{{ checkout_link }}"
    >Purchase (embedded)</a>
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
  </div>
</div>

然後,您可以像這樣檢索coinbase_webhook視圖內的元數據:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    import logging

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['custom'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

請記住,Webhookdata-custom以純文本形式接收。在使用它從數據庫中獲取用戶之前,請務必將其解析為整數。

註冊端點

導航到https://commerce.coinbase.com/dashboard/settings,向下滾動到“Webhook 訂閱”並單擊“添加端點”:

Coinbase Commerce 網絡鉤子

輸入您的端點 URL,然後按“保存”。

URL 需要以 HTTPS 開頭,這意味著您需要先部署應用程序,然後才能對其進行測試。

接下來,單擊“顯示共享密鑰”並複制該密鑰:

Coinbase Commerce Webhook 秘密

將共享密鑰添加到settings.py文件中,如下所示:

# core/settings.py

COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET = '<your coinbase webhook secret here>'

測試端點

部署應用程序後,您可以從Commerce Dashboard發送測試 webhook 請求。導航到“Webhook 訂閱”並單擊 Webhook 端點下的“詳細信息”:

Coinbase Commerce Webhook 詳細信息

然後點擊“發送測試”:

Coinbase Commerce Webhook 詳細信息測試

最後,選​​擇“charge:confirmed”並再次點擊“Send Test”。您應該會看到“付款已成功”。日誌消息。

結論

在本教程中,您學習瞭如何使用 Coinbase Commerce 接受加密支付。您現在應該能夠將其與 Django 集成並通過 webhook 驗證付款。

您可以在 GitHub 上的以下 repos 中找到代碼:

  1. django-coinbase-收費
  2. django-coinbase-checkout

來源:  https ://testdriven.io

#django #crypto #coinbase 

將 Django 與 Coinbase Commerce 集成以接受加密支付

Accepter Les Paiements Cryptographiques Avec Django Et Coinbase

Dans ce didacticiel, nous allons intégrer Django à Coinbase Commerce pour accepter différents paiements cryptographiques. Nous examinerons deux approches différentes : Coinbase Charges et Coinbase Checkout.

Qu'est-ce que Coinbase Commerce ?

Coinbase Commerce est un service de paiement numérique d'entreprise proposé par Coinbase, qui permet aux commerçants d'accepter les paiements cryptographiques dans différentes devises numériques. Au moment de la rédaction de cet article, ils prennent en charge Bitcoin, Bitcoin Cash, DAI, Ethereum, Litecoin, Dogecoin et USD Coin. Coinbase Commerce est facile à intégrer dans votre application Web et élimine les tracas liés aux paiements cryptographiques.

Coinbase et Coinbase Commerce ne sont pas la même chose. Coinbase est un échange crypto et un gestionnaire de portefeuille, tandis que Coinbase Commerce est un fournisseur de services de paiement numérique pour les commerçants.

L'API Coinbase Commerce propose deux manières différentes d'accepter les paiements cryptographiques : Coinbase Charges et Coinbase Checkout.

Avantages des frais Coinbase :

  • hautement personnalisable
  • possibilité de joindre par programme des métadonnées

Avantages de Coinbase Checkout :

  • fonctionne hors de la boîte
  • tableau de bord de gestion des produits
  • paiement intégré

Pour la plupart des applications, nous recommandons l'API Charges car elle peut être personnalisée. Cela l'emporte sur la simplicité offerte par l'API Checkout. Si vous vendez un produit fixe et que la personnalisation ne joue pas un grand rôle, n'hésitez pas à utiliser l'API Checkout.

Configuration du projet

Dans ce didacticiel, nous montrerons comment mettre en place les deux approches, Coinbase Charges et Coinbase Checkout. Nous allons commencer avec la même configuration de projet pour chacun. Une fois mis en place, n'hésitez pas à suivre une ou les deux approches.

Configuration du projet Django

Commencez par créer un nouveau répertoire et configurez un nouveau projet Django :

$ mkdir django-coinbase && cd django-coinbase
$ python3.9 -m venv env
$ source env/bin/activate

(env)$ pip install django==3.2.8
(env)$ django-admin startproject core .

Après cela, créez une nouvelle application appelée payments:

(env)$ python manage.py startapp payments

Enregistrez l'application dans core/settings.py sousINSTALLED_APPS :

# core/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payments.apps.PaymentsConfig', # new
]

Ajoutez une vue fonctionnelle simple appelée home_viewà payment/views.py :

# payments/views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

Créez un fichier urls.pypayments dans l' application :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
]

Mettez à jour le fichier d'URL au niveau du projet avec l' paymentsapplication :

# core/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payments.urls')), # new
    path('admin/', admin.site.urls),
]

Créez un dossier "templates" dédié et un fichier pour la page d'accueil :

(env)$ mkdir templates
(env)$ touch templates/home.html

Ensuite, ajoutez le code HTML suivant à templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <a class="btn btn-primary" href="#">Purchase</a>
    </div>
  </body>
</html>

Assurez-vous de mettre à jour le fichier settings.py afin que Django sache rechercher un dossier "templates":

# core/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], # new
        ...

Enfin, exécutez migratepour synchroniser la base runserverde données et démarrer le serveur Web local de Django :

(env)$ python manage.py migrate
(env)$ python manage.py runserver

C'est ça! Ouvrez http://localhost:8000/ dans votre navigateur préféré. Vous devriez voir la page d'accueil :

Page d'accueil de Django + Coinbase

Ajouter Coinbase Commerce

Ensuite, installez coinbase-commerce:

(env)$ pip install coinbase-commerce==1.0.1

Pour travailler avec l' API Coinbase Commerce , vous devrez créer un compte (si vous ne l'avez pas déjà fait). Après avoir créé un compte, connectez-vous et accédez à vos paramètres. Faites défiler jusqu'à la section "Clés API", cliquez sur "Créer une clé API" puis sur "Révéler". Copiez la clé API dans votre presse-papiers.

Clés API Coinbase

Ajoutez ensuite la clé au fichier settings.py :

# core/settings.py

COINBASE_COMMERCE_API_KEY = '<your coinbase api key here>'

Avant de passer à l'étape suivante, testons si nous pouvons récupérer les données de l'API. Entrez dans le shell Python à l'aide de la commande suivante :

(env)$ python manage.py shell

Importez les éléments suivants :

>>> from core import settings
>>> from coinbase_commerce.client import Client

Initialisez un nouveau client et listez les frais :

>>> client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
>>> for charge in client.charge.list_paging_iter():
...     print("{!r}".format(charge))

Si tout fonctionne, client.charge.list_paging_iter()devrait être une liste vide. Tant que vous ne voyez pas l'erreur suivante, vous pouvez supposer que tout va bien :

coinbase_commerce.error.AuthenticationError: Request id 10780b77-1021-4b09-b53b-a590ea044380: No such API key.

Pages utiles pour travailler avec l'API Coinbase :

Avec cela, décidez de l'approche que vous souhaitez adopter, Coinbase Charges ou Coinbase Checkout.

Frais Coinbase

Cette partie du didacticiel montre comment accepter les paiements à l'aide de l' API Coinbase Charges .

Coinbase Charges est l'approche la plus personnalisable pour collecter les paiements cryptographiques. Avec cette approche, vous avez un contrôle total sur les frais.

Flux de travail :

  1. Utiliser un client pour se connecter à l'API Coinbase Commerce
  2. Créer une charge (à partir de JSON)
  3. Récupérez la charge nouvellement créée et transmettez-la au modèle
  4. Rediriger l'utilisateur vers le site hébergé par Coinbase Commerce
  5. (Facultatif) Vérifiez les frais à l'aide de webhooks

Créer un frais

Pour demander un paiement en crypto-monnaie, vous créez un débit . Étant donné que les paiements en crypto-monnaie sont des paiements push , une charge expirera après une période d'attente si aucun paiement n'a été détecté. Les charges sont identifiées par un code unique à 8 caractères.

Mettre home_viewà jour pour créer une charge :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    domain_url = 'http://localhost:8000/'
    product = {
        'name': 'Coffee',
        'description': 'A really good local coffee.',
        'local_price': {
            'amount': '5.00',
            'currency': 'USD'
        },
        'pricing_type': 'fixed_price',
        'redirect_url': domain_url + 'success/',
        'cancel_url': domain_url + 'cancel/',
    }
    charge = client.charge.create(**product)

    return render(request, 'home.html', {
        'charge': charge,
    })

Nous avons d'abord initialisé le client en lui passant COINBASE_COMMERCE_API_KEY. Ensuite, nous avons créé un objet JSON qui représente notre produit (nous avons fourni le nom, la description, etc.). Nous avons également adopté redirect_urlet cancel_urlà la charge, que nous mettrons en œuvre ici sous peu. Nous avons ensuite décompressé l'objet JSON et utilisé le client pour créer une charge. Enfin, nous l'avons transmis au modèle d'accueil en tant que contexte.

Nous pouvons désormais accéder aux informations de facturation dans templates/home.html . Mettez à jour le modèle comme suit :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <div class="card-body">
          <h5 class="card-title">{{ charge.name }}</h5>
          <p class="card-text">
            <span>{{ charge.description }}</span>
            <br>
            <span>${{ charge.pricing.local.amount }} {{ charge.pricing.local.currency }}</span>
          </p>
          <div>
            <a class="btn btn-primary w-100" href="{{ charge.hosted_url }}">Purchase</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Reportez-vous à la documentation de l' API Charge pour toutes les informations relatives aux frais que vous pouvez afficher sur le modèle.

Exécutez le serveur de développement :

(env)$ python manage.py runserver

http://localhost:8000/ devrait maintenant ressembler à ceci :

Page d'accueil de Django + Coinbase

Ne le testez pas encore. Nous le ferons sous peu.

Créer les vues de redirection

Mettons en œuvre les vues pour redirect_urlet cancel_urlque nous avons passées à la charge.

Créez deux nouvelles vues dans payment/views.py :

# payments/views.py

def success_view(request):
    return render(request, 'success.html', {})


def cancel_view(request):
    return render(request, 'cancel.html', {})

Enregistrez les nouvelles vues dans payment/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'), # new
    path('cancel/', views.cancel_view, name='payments-cancel'), # new
]

Et templates/success.html :

<!-- templates/success.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been successful.</p>
    </div>
  </body>
</html>

Et templates/cancel.html :

<!-- templates/cancel.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been cancelled.</p>
    </div>
  </body>
</html>

Maintenant, une fois le paiement confirmé, l'utilisateur sera redirigé vers redirect_url. Dans le cas où ils annulent le paiement (ou si le débit expire), ils seront redirigés vers cancel_url.

Essai

Malheureusement, Coinbase Commerce ne prend pas en charge les comptes sandbox pour les tests, ce qui signifie que vous devrez utiliser un vrai crypto pour tester votre application.

Exécutez le serveur, accédez à http://localhost:8000/ et cliquez sur le bouton "Acheter". Vous serez redirigé vers le site hébergé par Coinbase Commerce :

Frais commerciaux Coinbase

Lorsque vous sélectionnez une crypto-monnaie avec laquelle vous souhaitez payer, une adresse de portefeuille (et un code QR) s'affichera :

Adresses de frais de commerce Coinbase

Vous disposez alors de 60 minutes pour transférer la crypto avant l'expiration de la charge.

Après avoir envoyé la crypto, il faudra quelques minutes (selon la crypto-monnaie que vous utilisez) aux mineurs pour confirmer votre transaction. Une fois que la transaction a reçu le nombre requis de confirmations (basé sur la crypto-monnaie), vous serez redirigé vers l'URL associée à redirect_url.

Les paiements apparaîtront dans le tableau de bord Commerce sous "Paiements":

Paiements commerciaux Coinbase

Passez à la section "Confirmer les paiements avec les webhooks" pour en savoir plus sur la confirmation de paiement.

Caisse Coinbase

Cette partie du didacticiel montre comment accepter les paiements à l'aide de l' API Coinbase Checkout . Si vous avez décidé d'opter pour Coinbase Charges, n'hésitez pas à ignorer cette section et à passer à la section "Confirmer les paiements avec les Webhooks".

Coinbase Checkout est le moyen le plus simple de collecter des paiements cryptographiques avec Coinbase Commerce. Avec cette approche, des frais seront automatiquement générés pour vous. Cette approche est appropriée lorsque vous travaillez avec des produits fixes.

Flux de travail :

  1. Utiliser un client pour se connecter à l'API Coinbase Commerce
  2. Récupérez un paiement à partir de l'API Coinbase Commerce et transmettez-le au modèle
  3. (Facultatif) Ajoutez le code HTML requis au modèle s'il s'agit de paiements intégrés
  4. Redirigez l'utilisateur vers le site hébergé par Coinbase Commerce OU utilisez un paiement intégré
  5. (Facultatif) Vérifiez les frais à l'aide de webhooks

Créer une caisse

Il existe deux manières de créer une caisse :

  1. Par programmation via la bibliothèque coinbase-commerce
  2. Manuellement dans le tableau de bord Coinbase Commerce

Pour plus de simplicité, nous utiliserons le Commerce Dashboard .

Accédez à "Commandes" et cliquez sur "Créer une caisse":

Paiement du commerce Coinbase

Cliquez sur "Vendre un produit". Saisissez le nom, la description et le prix du produit. Cliquez sur Suivant". Sous "Informations client", sélectionnez "Ne collectez aucune information". Ensuite, cliquez sur "Terminé.

Coinbase Commerce a généré tout le code HTML nécessaire que vous devez ajouter à votre modèle d'accueil. Vous pouvez le voir sous l'onglet "Intégrer". Pour rendre l'application Web plus modulaire et réutilisable, nous allons récupérer les informations de paiement dans le home_viewau lieu de les coder en dur dans le modèle. Pour ce faire, nous devons d'abord obtenir l'ID de paiement en copiant l'URL de la page hébergée :

Paiement du commerce Coinbase

Le lien permanent devrait ressembler à ceci :

https://commerce.coinbase.com/checkout/df2d7c68-145e-4537-86fa-1cac705eb748

Nous ne nous intéressons qu'au dernier segment de l'URL, qui représente l'ID de paiement :

df2d7c68-145e-4537-86fa-1cac705eb748

Enregistrez ceci dans le fichier core/settings.py comme suit :

# core/settings.py

COINBASE_CHECKOUT_ID = '<your checkout id>'

Mettre à jour les paiements/vues.py :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    checkout = client.checkout.retrieve(settings.COINBASE_CHECKOUT_ID)
    checkout_link = f'https://commerce.coinbase.com/checkout/{checkout.id}'

    return render(request, 'home.html', {
        'checkout': checkout,
        'checkout_link': checkout_link,
    })

Ce code récupère le paiement et le transmet au modèle.

Enfin, nous devons modifier le modèle d'accueil pour utiliser la caisse. Vous pouvez soit utiliser un :

  1. Page hébergée - l'utilisateur est redirigé vers un site Web Coinbase Checkout
  2. Page intégrée - tout se passe sur votre site Web

À des fins éducatives, nous utiliserons les deux approches.

Mettre à jour templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Checkout</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <!-- Coinbase checkout details -->
        <div class="card-body">
          <h5 class="card-title">{{ checkout.name }}</h5>
          <p class="card-text">
            {{ checkout.description }}<br>
            {{ checkout.local_price.amount }} {{ checkout.local_price.currency }}
          </p>
          <div>
            <!-- Coinbase hosted approach (script not required) -->
            <a class="btn btn-primary w-100" href="{{ checkout_link }}">Purchase (hosted)</a>
            <!-- Coinbase embedded approach (script required) -->
            <div class="mt-2">
              <a class="btn btn-primary buy-with-crypto w-100" href="{{ checkout_link }}">Purchase (embedded)</a>
              <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Exécutez le serveur et accédez à http://localhost:8000/ :

Exemple de paiement Coinbase Commerce

L'application est complètement fonctionnelle à ce stade. Ne testez rien pour l'instant cependant. Nous le ferons dans la section suivante.

Essai

Malheureusement, Coinbase Commerce ne prend pas en charge les comptes sandbox pour les tests, ce qui signifie que vous devrez utiliser un vrai crypto pour tester votre application.

Avec le serveur en cours d'exécution, accédez à http://localhost:8000/ . Vous pouvez tester en utilisant le site hébergé Coinbase ou le paiement intégré. Votre choix.

Lorsque vous sélectionnez une crypto-monnaie avec laquelle vous souhaitez payer, une adresse de portefeuille (et un code QR) s'affichera :

Adresses de frais de commerce Coinbase

Vous disposez alors de 60 minutes pour transférer la crypto avant l'expiration de la charge.

Après avoir envoyé la crypto, il faudra quelques minutes (selon la crypto-monnaie que vous utilisez) aux mineurs pour confirmer votre transaction. Une fois que la transaction a reçu le nombre requis de confirmations (basé sur la crypto-monnaie), un message "Paiement terminé" s'affiche.

Les paiements apparaîtront dans le tableau de bord Commerce sous "Paiements":

Paiements commerciaux Coinbase

Confirmer les paiements avec les Webhooks

Notre application fonctionne bien pour le moment, mais nous ne pouvons pas encore confirmer les paiements par programmation. Nous redirigeons simplement l'utilisateur vers la page de réussite après son paiement, mais nous ne pouvons pas compter uniquement sur cette page car la confirmation de paiement se produit de manière asynchrone.

Vous traitez souvent deux types d'événements différents lors de la programmation : les événements synchrones, qui ont un effet et des résultats immédiats (par exemple, la création d'une charge), et les événements asynchrones, qui n'ont pas de résultat immédiat (par exemple, la confirmation des paiements). Étant donné que la confirmation de paiement est effectuée de manière asynchrone, l'utilisateur peut être redirigé vers la page de réussite avant que son paiement ne soit confirmé et avant que nous recevions ses fonds.

Pour être averti lorsque le paiement est effectué, vous devez créer un webhook . Nous devrons créer un point de terminaison simple dans notre application, que Coinbase Commerce appellera chaque fois qu'un événement se produit (c'est-à-dire lorsqu'une charge est confirmée). En utilisant des webhooks, nous pouvons être sûrs que le paiement a bien été effectué.

Pour utiliser les webhooks, nous devons :

  1. Configurer le point de terminaison du webhook dans l'application
  2. Enregistrez le point de terminaison dans le tableau de bord Coinbase Commerce

Configurer le point de terminaison

Créez une coinbase_webhookvue dans payment/views.py :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            # TODO: run some custom code here

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Ce bloc de code valide la signature et la charge utile de la requête, puis génère un événement à partir de celle-ci. Vous pouvez maintenant vérifier le type d'événement et effectuer différentes actions en fonction du type.

Mettez à jour les importations :

import logging

from coinbase_commerce.client import Client
from coinbase_commerce.error import SignatureVerificationError, WebhookInvalidPayload
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from core import settings

Ignorez l'erreur qui COINBASE_COMMERCE_WEBHOOK_SHARED_SECRETn'existe pas encore. Nous l'ajouterons à l'étape suivante.

Enregistrez l'URL dans payment/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'),   # only for the Coinbase charges approach
    path('cancel/', views.cancel_view, name='payments-cancel'),      # only for the Coinbase charges approach
    path('webhook/', views.coinbase_webhook),  # new
]

La coinbase_webhookvue sert maintenant de point de terminaison de webhook auquel Coinbase Commerce enverra les événements lorsqu'ils se produiront.

Si vous avez suivi l'approche Coinbase Checkout, n'incluez pas les URL success/ou .cancel/

Identifier l'utilisateur

Pour identifier l'utilisateur dans votre webhook, vous devez transmettre certaines métadonnées lors de la création de la charge ou lors du démarrage de la session de paiement. Vous pourrez ensuite récupérer ces métadonnées dans votre webhook.

La manière dont vous transmettez les métadonnées est différente selon l'approche que vous avez utilisée :

  1. API Charges - vous devrez joindre des métadonnées au produit
  2. API de paiement - vous devrez transmettre les métadonnées en tant qu'attribut HTML

Identifier l'utilisateur avec l'API Charges

Pour identifier l'utilisateur avec l'API Charges, commencez par ajouter ce qui suit au productdict à l'intérieurhome_view :

# payments/views.py

product = {
    ...
    'metadata': {
        'customer_id': request.user.id if request.user.is_authenticated else None,
        'customer_username': request.user.username if request.user.is_authenticated else None,
    },
    ...
}

Ce bloc de code associe l'ID utilisateur et le nom d'utilisateur de l'utilisateur authentifié.

Vous pouvez maintenant accéder aux métadonnées à l'intérieur de la coinbase_webhookvue comme suit :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['customer_id'] # new
            customer_username = event['data']['metadata']['customer_username'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id' or 'customer_username'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Identifier l'utilisateur avec l'API Checkout

Pour identifier l'utilisateur avec l'API Checkout, nous devons ajouter les métadonnées en tant data-customqu'attribut de données aux ancres dans templates/home.html :

Par exemple:

<div>
  <!-- Coinbase hosted approach (script not required) -->
  <a
    class="btn btn-primary w-100"
    {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
    href="{{ checkout_link }}"
  >Purchase (hosted)</a>
  <!-- Coinbase embedded approach (script required) -->
  <div class="mt-2">
    <a
      class="btn btn-primary buy-with-crypto w-100"
      {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
      href="{{ checkout_link }}"
    >Purchase (embedded)</a>
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
  </div>
</div>

Vous pouvez ensuite récupérer les métadonnées à l'intérieur de la coinbase_webhookvue comme suit :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    import logging

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['custom'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Gardez à l'esprit que le webhook reçoit data-customdu texte brut. Assurez-vous de l'analyser en entier avant de l'utiliser pour extraire l'utilisateur de la base de données.

Enregistrer le point de terminaison

Accédez à https://commerce.coinbase.com/dashboard/settings , faites défiler jusqu'à "Abonnements Webhook" et cliquez sur "Ajouter un point de terminaison":

Coinbase Commerce Webhook

Entrez l'URL de votre point de terminaison et appuyez sur "Enregistrer".

L'URL doit commencer par HTTPS, ce qui signifie que vous devez déployer votre application avant de pouvoir la tester.

Ensuite, cliquez sur "Afficher le secret partagé" et copiez le secret :

Coinbase Commerce Webhook secret

Ajoutez le secret partagé au fichier settings.py comme suit :

# core/settings.py

COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET = '<your coinbase webhook secret here>'

Tester le point de terminaison

Une fois votre application déployée, vous pouvez envoyer une demande de webhook de test à partir du tableau de bord Commerce . Accédez à "Abonnements Webhook" et cliquez sur "Détails" sous le point de terminaison du webhook :

Détails du webhook Coinbase Commerce

Cliquez ensuite sur "Envoyer le test":

Test des détails du webhook Coinbase Commerce

Enfin, sélectionnez "charge:confirmed" et cliquez à nouveau sur "Send Test". Vous devriez voir le message "Le paiement a été effectué avec succès". message de journalisation.

Conclusion

Dans ce didacticiel, vous avez appris à accepter les paiements cryptographiques avec Coinbase Commerce. Vous devriez maintenant pouvoir l'intégrer à Django et vérifier les paiements via un webhook.

Vous pouvez trouver le code dans les dépôts suivants sur GitHub :

  1. django-coinbase-frais
  2. django-coinbase-checkout

Source :  https://testdrive.io

#django #crypto #coinbase 

Accepter Les Paiements Cryptographiques Avec Django Et Coinbase
Derrick  Ferry

Derrick Ferry

1660495620

Integre Django Con Coinbase Commerce Para Aceptar Pagos Criptográficos

En este tutorial, integraremos Django con Coinbase Commerce para aceptar diferentes criptopagos. Veremos dos enfoques diferentes: Cargos de Coinbase y Pago de Coinbase.

¿Qué es Coinbase Comercio?

Coinbase Commerce es un servicio de pago digital empresarial ofrecido por Coinbase, que permite a los comerciantes aceptar criptopagos en diferentes monedas digitales. Al momento de escribir, admiten Bitcoin, Bitcoin Cash, DAI, Ethereum, Litecoin, Dogecoin y USD Coin. Coinbase Commerce es fácil de integrar en su aplicación web y elimina la molestia de lidiar con pagos criptográficos.

Coinbase y Coinbase Commerce no son lo mismo. Coinbase es un intercambio de criptomonedas y un administrador de carteras, mientras que Coinbase Commerce es un proveedor de servicios de pago digital para comerciantes.

La API de Coinbase Commerce proporciona dos formas diferentes de aceptar pagos criptográficos: Cargos de Coinbase y Pago de Coinbase.

Ventajas de los cargos de Coinbase:

  • altamente personalizable
  • capacidad de adjuntar metadatos programáticamente

Ventajas de Coinbase Checkout:

  • funciona fuera de la caja
  • gestión de productos del tablero
  • pago incrustado

Para la mayoría de las aplicaciones, recomendamos la API de cargos, ya que se puede personalizar. Esto supera la simplicidad que ofrece la API de Checkout. Si está vendiendo un producto fijo y la personalización no juega un papel importante, no dude en utilizar la API de Checkout.

Configuración del proyecto

En este tutorial, le mostraremos cómo poner en funcionamiento ambos enfoques, Coinbase Charges y Coinbase Checkout. Comenzaremos con la misma configuración de proyecto para cada uno. Una vez configurado, siéntase libre de seguir uno o ambos enfoques.

Configuración del proyecto Django

Comience creando un nuevo directorio y configurando un nuevo proyecto Django:

$ mkdir django-coinbase && cd django-coinbase
$ python3.9 -m venv env
$ source env/bin/activate

(env)$ pip install django==3.2.8
(env)$ django-admin startproject core .

Después de eso, crea una nueva aplicación llamada payments:

(env)$ python manage.py startapp payments

Registre la aplicación en core/settings.py en INSTALLED_APPS:

# core/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payments.apps.PaymentsConfig', # new
]

Agregue una vista funcional simple llamada home_viewa pagos/vistas.py :

# payments/views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

Cree un archivo urls.pypayments dentro de la aplicación:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
]

Actualice el archivo de URL de nivel de proyecto con la paymentsaplicación:

# core/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payments.urls')), # new
    path('admin/', admin.site.urls),
]

Cree una carpeta de "plantillas" dedicada y un archivo para la página de inicio:

(env)$ mkdir templates
(env)$ touch templates/home.html

Luego, agregue el siguiente HTML a templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <a class="btn btn-primary" href="#">Purchase</a>
    </div>
  </body>
</html>

Asegúrese de actualizar el archivo settings.py para que Django sepa buscar una carpeta de "plantillas":

# core/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], # new
        ...

Finalmente, ejecute migratepara sincronizar la base de datos y runserverpara iniciar el servidor web local de Django:

(env)$ python manage.py migrate
(env)$ python manage.py runserver

¡Eso es todo! Abra http://localhost:8000/ en su navegador favorito. Deberías ver la página de inicio:

Página de inicio de Django + Coinbase

Agregar comercio de Coinbase

A continuación, instale coinbase-commerce:

(env)$ pip install coinbase-commerce==1.0.1

Para trabajar con la API de Coinbase Commerce , deberá crear una cuenta (si aún no lo ha hecho). Una vez que haya creado una cuenta, inicie sesión y navegue hasta su configuración. Desplácese hacia abajo hasta la sección "Claves de API", haga clic en "Crear una clave de API" y luego en "Revelar". Copie la clave API en su portapapeles.

Claves API de Coinbase

Luego agregue la clave al archivo settings.py :

# core/settings.py

COINBASE_COMMERCE_API_KEY = '<your coinbase api key here>'

Antes de pasar al siguiente paso, probemos si podemos recuperar datos de la API. Ingrese al shell de Python usando el siguiente comando:

(env)$ python manage.py shell

Importa lo siguiente:

>>> from core import settings
>>> from coinbase_commerce.client import Client

Inicialice un nuevo cliente y enumere los cargos:

>>> client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
>>> for charge in client.charge.list_paging_iter():
...     print("{!r}".format(charge))

Si todo funciona, client.charge.list_paging_iter()debería ser una lista vacía. Mientras no vea el siguiente error, puede asumir que todo está bien:

coinbase_commerce.error.AuthenticationError: Request id 10780b77-1021-4b09-b53b-a590ea044380: No such API key.

Useful pages for working with the Coinbase API:

With that, decide which approach you'd like to take, Coinbase Charges or Coinbase Checkout.

Coinbase Charges

This part of the tutorial shows how to accept payments using the Coinbase Charges API.

Coinbase Charges is the most customizable approach for collecting crypto payments. With this approach, you have full control over the charges.

Workflow:

  1. Use a client to connect to the Coinbase Commerce API
  2. Create a charge (from JSON)
  3. Fetch the newly created charge and pass it to the template
  4. Redirect the user to the Coinbase Commerce hosted site
  5. (Optional) Verify the charge using webhooks

Create a Charge

To request a cryptocurrency payment, you create a charge. Since cryptocurrency payments are push payments, a charge will expire after a waiting period if no payment has been detected. Charges are identified by a unique 8 character code.

Update home_view to create a charge:

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    domain_url = 'http://localhost:8000/'
    product = {
        'name': 'Coffee',
        'description': 'A really good local coffee.',
        'local_price': {
            'amount': '5.00',
            'currency': 'USD'
        },
        'pricing_type': 'fixed_price',
        'redirect_url': domain_url + 'success/',
        'cancel_url': domain_url + 'cancel/',
    }
    charge = client.charge.create(**product)

    return render(request, 'home.html', {
        'charge': charge,
    })

We first initialized the client by passing COINBASE_COMMERCE_API_KEY to it. Then, we created a JSON object which represents our product (we provided the name, description, etc.). We also passed redirect_url and cancel_url to the charge, which we'll implement here shortly. We then unpacked the JSON object and used the client to create a charge. Finally, we passed it to the home template as context.

We can now access charge information in templates/home.html. Update the template like so:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <div class="card-body">
          <h5 class="card-title">{{ charge.name }}</h5>
          <p class="card-text">
            <span>{{ charge.description }}</span>
            <br>
            <span>${{ charge.pricing.local.amount }} {{ charge.pricing.local.currency }}</span>
          </p>
          <div>
            <a class="btn btn-primary w-100" href="{{ charge.hosted_url }}">Purchase</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Refer to the Charge API documentation for all the charge-related info that you can display on the template.

Run the development server:

(env)$ python manage.py runserver

http://localhost:8000/ should now look like this:

Página de inicio de Django + Coinbase

Don't test it out yet. We'll do that shortly.

Create the Redirect Views

Let's implement the views for redirect_url and cancel_url that we passed to the charge.

Create two new views inside payments/views.py:

# payments/views.py

def success_view(request):
    return render(request, 'success.html', {})


def cancel_view(request):
    return render(request, 'cancel.html', {})

Register the new views inside payments/urls.py:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'), # new
    path('cancel/', views.cancel_view, name='payments-cancel'), # new
]

And templates/success.html:

<!-- templates/success.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been successful.</p>
    </div>
  </body>
</html>

And templates/cancel.html:

<!-- templates/cancel.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been cancelled.</p>
    </div>
  </body>
</html>

Now, after the payment is confirmed, the user will be redirected to redirect_url. In the event that they cancel the payment (or the charge times out), they will be redirected to cancel_url.

Testing

Unfortunately, Coinbase Commerce doesn't support sandbox accounts for testing, which means that you'll need to use real crypto to test your application.

Run the server, navigate to http://localhost:8000/, and click on the "Purchase" button. You'll be redirected to the Coinbase Commerce hosted site:

Cargos comerciales de Coinbase

When you select a cryptocurrency with which you'd like to pay, a wallet address (and a QR code) will be shown:

Direcciones de cargos de comercio de Coinbase

You then have 60 minutes to transfer the crypto before the charge times out.

Después de enviar la criptografía, los mineros tardarán unos minutos (dependiendo de la criptomoneda que utilice) en confirmar su transacción. Después de que la transacción obtenga la cantidad requerida de confirmaciones (según la criptomoneda), será redirigido a la URL asociada con redirect_url.

Los pagos aparecerán en el Panel de comercio en "Pagos":

Pagos comerciales de Coinbase

Pase a la sección "Confirmar pagos con webhooks" para obtener información sobre la confirmación de pagos.

Pago de Coinbase

Esta parte del tutorial muestra cómo aceptar pagos utilizando la API de pago de Coinbase . Si decidió optar por los cargos de Coinbase, no dude en omitir esta sección y pasar a la sección "Confirmar pagos con webhooks".

Coinbase Checkout es la forma más fácil de cobrar criptopagos con Coinbase Commerce. Con este enfoque, los cargos se generarán automáticamente para usted. Este enfoque es apropiado cuando se trabaja con productos fijos.

Flujo de trabajo:

  1. Use un cliente para conectarse a la API de Coinbase Commerce
  2. Obtenga un pago de la API de Coinbase Commerce y páselo a la plantilla
  3. (Opcional) Agregue el código HTML requerido a la plantilla si se trata de pagos incrustados
  4. Redirija al usuario al sitio alojado de Coinbase Commerce O use un pago integrado
  5. (Opcional) Verifica el cargo usando webhooks

Crear un pago

Hay dos formas de crear un checkout:

  1. Programáticamente a través de la biblioteca coinbase-commerce
  2. Manualmente dentro del panel de control de Coinbase Commerce

Para simplificar, usaremos Commerce Dashboard .

Navigate to "Checkouts" and click "Create Checkout":

Pago de comercio de Coinbase

Click "Sell a Product". Enter the product name, description, and price. Click "Next". Under "Customer information", select "Don't collect any information". Then, click "Done.

Coinbase Commerce generated all the necessary HTML code that you need to add to your home template. You can see this under the "Embed" tab. To make the web application more modular and reusable, we'll fetch the checkout info in the home_view instead of hard coding it in the template. To do so, we first need to obtain the checkout ID by copying the hosted page URL:

Pago de comercio de Coinbase

The permanent link should look something like this:

https://commerce.coinbase.com/checkout/df2d7c68-145e-4537-86fa-1cac705eb748

We're only interested in the last segment of the URL, which represents the checkout ID:

df2d7c68-145e-4537-86fa-1cac705eb748

Guarde esto dentro del archivo core/settings.py así:

# core/settings.py

COINBASE_CHECKOUT_ID = '<your checkout id>'

Actualizar pagos/views.py :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    checkout = client.checkout.retrieve(settings.COINBASE_CHECKOUT_ID)
    checkout_link = f'https://commerce.coinbase.com/checkout/{checkout.id}'

    return render(request, 'home.html', {
        'checkout': checkout,
        'checkout_link': checkout_link,
    })

Este código obtiene el pago y lo pasa a la plantilla.

Finalmente, necesitamos modificar la plantilla de inicio para usar el pago. Puedes usar un:

  1. Página alojada: el usuario es redirigido a un sitio web de Coinbase Checkout
  2. Página incrustada: todo sucede en su sitio web

Con fines educativos, utilizaremos ambos enfoques.

Actualizar templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Checkout</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <!-- Coinbase checkout details -->
        <div class="card-body">
          <h5 class="card-title">{{ checkout.name }}</h5>
          <p class="card-text">
            {{ checkout.description }}<br>
            {{ checkout.local_price.amount }} {{ checkout.local_price.currency }}
          </p>
          <div>
            <!-- Coinbase hosted approach (script not required) -->
            <a class="btn btn-primary w-100" href="{{ checkout_link }}">Purchase (hosted)</a>
            <!-- Coinbase embedded approach (script required) -->
            <div class="mt-2">
              <a class="btn btn-primary buy-with-crypto w-100" href="{{ checkout_link }}">Purchase (embedded)</a>
              <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Ejecute el servidor y navegue hasta http://localhost:8000/ :

Ejemplo de pago de Coinbase Commerce

La aplicación es completamente funcional en este punto. Sin embargo, no pruebes nada todavía. Lo haremos en la siguiente sección.

Pruebas

Desafortunadamente, Coinbase Commerce no admite cuentas sandbox para realizar pruebas, lo que significa que deberá usar criptografía real para probar su aplicación.

Con el servidor en ejecución, vaya a http://localhost:8000/ . Puede probar usando el sitio alojado de Coinbase o el pago integrado. Tu elección.

Cuando seleccione una criptomoneda con la que le gustaría pagar, se mostrará una dirección de billetera (y un código QR):

Direcciones de cargos de comercio de Coinbase

Luego tiene 60 minutos para transferir la criptomoneda antes de que se agote el tiempo de carga.

Después de enviar la criptografía, los mineros tardarán unos minutos (dependiendo de la criptomoneda que utilice) en confirmar su transacción. Después de que la transacción obtenga la cantidad requerida de confirmaciones (según la criptomoneda), se le presentará un mensaje de "Pago completo".

Los pagos aparecerán en el Panel de comercio en "Pagos":

Pagos comerciales de Coinbase

Confirmar pagos con webhooks

Nuestra aplicación funciona bien en este punto, pero aún no podemos confirmar los pagos mediante programación. Simplemente redirigimos al usuario a la página de éxito después de finalizar la compra, pero no podemos confiar solo en esa página ya que la confirmación del pago se realiza de forma asíncrona.

A menudo trata con dos tipos diferentes de eventos al programar: eventos sincrónicos, que tienen un efecto y resultados inmediatos (p. ej., crear un cargo) y eventos asincrónicos, que no tienen un resultado inmediato (p. ej., confirmar pagos). Debido a que la confirmación del pago se realiza de forma asíncrona, es posible que se redirija al usuario a la página de éxito antes de que se confirme su pago y antes de que recibamos sus fondos.

Para recibir una notificación cuando se realice el pago, debe crear un webhook . Tendremos que crear un punto final simple en nuestra aplicación, al que Coinbase Commerce llamará cada vez que ocurra un evento (es decir, cuando se confirme un cargo). Mediante el uso de webhooks, podemos estar seguros de que el pago se realizó correctamente.

Para usar webhooks, necesitamos:

  1. Configurar el punto final del webhook en la aplicación
  2. Registre el punto final en Coinbase Commerce Dashboard

Configurar el punto final

Cree una coinbase_webhookvista en pagos/views.py :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            # TODO: run some custom code here

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Este bloque de código valida la firma y la carga útil de la solicitud y luego genera un evento a partir de ella. Ahora puede verificar el tipo de evento y realizar diferentes acciones según el tipo.

Actualizar las importaciones:

import logging

from coinbase_commerce.client import Client
from coinbase_commerce.error import SignatureVerificationError, WebhookInvalidPayload
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from core import settings

Ignora el error que COINBASE_COMMERCE_WEBHOOK_SHARED_SECRETaún no existe. Lo agregaremos en el siguiente paso.

Registre la URL en pagos/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'),   # only for the Coinbase charges approach
    path('cancel/', views.cancel_view, name='payments-cancel'),      # only for the Coinbase charges approach
    path('webhook/', views.coinbase_webhook),  # new
]

La coinbase_webhookvista ahora sirve como nuestro punto final de webhook al que Coinbase Commerce enviará eventos cuando ocurran.

Si siguió el enfoque de Coinbase Checkout, no incluya las URL success/o .cancel/

Identificar al usuario

Para identificar al usuario en su webhook, debe pasar algunos metadatos al crear el cargo o al iniciar la sesión de pago. Luego podrá obtener estos metadatos dentro de su webhook.

La forma en que pasa los metadatos es diferente según el enfoque que haya utilizado:

  1. API de cargos : deberá adjuntar metadatos al producto
  2. API de pago : deberá pasar los metadatos como un atributo HTML

Identificar al Usuario con la API de Cargos

Para identificar al usuario con la API de cargos, comience agregando lo siguiente al productdictado interior home_view:

# payments/views.py

product = {
    ...
    'metadata': {
        'customer_id': request.user.id if request.user.is_authenticated else None,
        'customer_username': request.user.username if request.user.is_authenticated else None,
    },
    ...
}

Este bloque de código adjunta el ID de usuario y el nombre de usuario del usuario autenticado.

Ahora puede acceder a los metadatos dentro de la coinbase_webhookvista de la siguiente manera:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['customer_id'] # new
            customer_username = event['data']['metadata']['customer_username'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id' or 'customer_username'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Identificar al usuario con la API de Checkout

Para identificar al usuario con la API de Checkout, debemos agregar los metadatos como un data-customatributo de datos a los anclajes en templates/home.html :

Por ejemplo:

<div>
  <!-- Coinbase hosted approach (script not required) -->
  <a
    class="btn btn-primary w-100"
    {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
    href="{{ checkout_link }}"
  >Purchase (hosted)</a>
  <!-- Coinbase embedded approach (script required) -->
  <div class="mt-2">
    <a
      class="btn btn-primary buy-with-crypto w-100"
      {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
      href="{{ checkout_link }}"
    >Purchase (embedded)</a>
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
  </div>
</div>

A continuación, puede recuperar los metadatos dentro de la coinbase_webhookvista de la siguiente manera:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    import logging

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['custom'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Tenga en cuenta que el webhook se recibe data-customcomo texto sin formato. Asegúrese de analizarlo en un número entero antes de usarlo para recuperar al usuario de la base de datos.

Registrar el punto final

Vaya a https://commerce.coinbase.com/dashboard/settings , desplácese hacia abajo hasta "Suscripciones de Webhook" y haga clic en "Agregar un punto final":

Webhook de comercio de Coinbase

Ingrese la URL de su terminal y presione "Guardar".

La URL debe comenzar con HTTPS, lo que significa que debe implementar su aplicación antes de poder probarla.

A continuación, haga clic en "Mostrar secreto compartido" y copie el secreto:

Secreto del webhook de comercio de Coinbase

Agregue el secreto compartido al archivo settings.py así:

# core/settings.py

COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET = '<your coinbase webhook secret here>'

Probar el punto final

Con su aplicación implementada, puede enviar una solicitud de webhook de prueba desde el panel de comercio . Vaya a "Suscripciones de webhook" y haga clic en "Detalles" debajo del punto final de webhook:

Detalles del webhook de comercio de Coinbase

Luego haga clic en "Enviar prueba":

Prueba de detalles del webhook de Coinbase Commerce

Finalmente, seleccione el "cargo:confirmado" y haga clic en "Enviar prueba" nuevamente. Debería ver el mensaje "El pago se ha realizado correctamente". mensaje de registro.

Conclusión

En este tutorial, aprendió a aceptar pagos criptográficos con Coinbase Commerce. Ahora debería poder integrarlo con Django y verificar los pagos a través de un webhook.

Puede encontrar el código en los siguientes repositorios en GitHub:

  1. django-coinbase-cargos
  2. Django-coinbase-checkout

Fuente:  https://testdriven.io

#django #crypto #coinbase 

Integre Django Con Coinbase Commerce Para Aceptar Pagos Criptográficos
Callum  Allen

Callum Allen

1660488120

Aceitando Pagamentos De Criptografia Com Django E Coinbase

Neste tutorial, vamos integrar o Django com o Coinbase Commerce para aceitar diferentes pagamentos de criptomoedas. Veremos duas abordagens diferentes: Coinbase Charges e Coinbase Checkout.

O que é o Coinbase Commerce?

O Coinbase Commerce é um serviço de pagamento digital corporativo oferecido pela Coinbase, que permite que os comerciantes aceitem pagamentos criptográficos em diferentes moedas digitais. No momento em que escrevo, eles suportam Bitcoin, Bitcoin Cash, DAI, Ethereum, Litecoin, Dogecoin e USD Coin. O Coinbase Commerce é fácil de integrar ao seu aplicativo da web e elimina o incômodo de lidar com pagamentos criptográficos.

Coinbase e Coinbase Commerce não são a mesma coisa. A Coinbase é uma exchange de criptomoedas e um gerenciador de carteiras, enquanto a Coinbase Commerce é um provedor de serviços de pagamento digital para comerciantes.

A Coinbase Commerce API oferece duas maneiras diferentes de aceitar pagamentos de criptomoedas: Coinbase Charges e Coinbase Checkout.

Vantagens das Coinbase Charges:

  • altamente personalizável
  • capacidade de anexar metadados programaticamente

Vantagens do Coinbase Checkout:

  • Trabalha fora da caixa
  • gerenciamento de produtos do painel
  • checkout incorporado

Para a maioria dos aplicativos, recomendamos a API Charges, pois ela pode ser personalizada. Isso supera a simplicidade que a API do Checkout oferece. Se você está vendendo um produto fixo e a personalização não desempenha um papel importante, sinta-se à vontade para usar a API do Checkout.

Configuração do projeto

Neste tutorial, mostraremos como obter ambas as abordagens, Coinbase Charges e Coinbase Checkout, em funcionamento. Começaremos com a mesma configuração de projeto para cada um. Uma vez configurado, sinta-se à vontade para seguir uma ou ambas as abordagens.

Configuração do projeto Django

Comece criando um novo diretório e configurando um novo projeto Django:

$ mkdir django-coinbase && cd django-coinbase
$ python3.9 -m venv env
$ source env/bin/activate

(env)$ pip install django==3.2.8
(env)$ django-admin startproject core .

Depois disso, crie um novo aplicativo chamado payments:

(env)$ python manage.py startapp payments

Registre o aplicativo em core/settings.py em INSTALLED_APPS:

# core/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payments.apps.PaymentsConfig', # new
]

Adicione uma visualização funcional simples chamada home_viewpara payments/views.py :

# payments/views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

Crie um arquivo urls.py dentro do paymentsaplicativo:

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
]

Atualize o arquivo de URLs no nível do projeto com o paymentsaplicativo:

# core/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payments.urls')), # new
    path('admin/', admin.site.urls),
]

Crie uma pasta "modelos" dedicada e um arquivo para a página inicial:

(env)$ mkdir templates
(env)$ touch templates/home.html

Em seguida, adicione o seguinte HTML a templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <a class="btn btn-primary" href="#">Purchase</a>
    </div>
  </body>
</html>

Certifique-se de atualizar o arquivo settings.py para que o Django saiba procurar uma pasta "templates":

# core/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], # new
        ...

Finalmente execute migratepara sincronizar o banco de dados e runserveriniciar o servidor web local do Django:

(env)$ python manage.py migrate
(env)$ python manage.py runserver

É isso! Abra http://localhost:8000/ em seu navegador favorito. Você deve ver a página inicial:

Página inicial do Django + Coinbase

Adicionar Coinbase Commerce

A seguir, instale coinbase-commerce:

(env)$ pip install coinbase-commerce==1.0.1

Para trabalhar com a API Coinbase Commerce , você precisará criar uma conta (se ainda não tiver feito isso). Depois de criar uma conta, faça login e navegue até suas configurações. Role para baixo até a seção "Chaves de API", clique em "Criar uma chave de API" e depois em "Revelar". Copie a chave de API para sua área de transferência.

Chaves da API Coinbase

Em seguida, adicione a chave ao arquivo settings.py :

# core/settings.py

COINBASE_COMMERCE_API_KEY = '<your coinbase api key here>'

Antes de passar para a próxima etapa, vamos testar se podemos recuperar dados da API. Insira o shell do Python usando o seguinte comando:

(env)$ python manage.py shell

Importe o seguinte:

>>> from core import settings
>>> from coinbase_commerce.client import Client

Inicialize um novo cliente e liste as cobranças:

>>> client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
>>> for charge in client.charge.list_paging_iter():
...     print("{!r}".format(charge))

Se tudo funcionar, client.charge.list_paging_iter()deve ser uma lista vazia. Contanto que você não veja o seguinte erro, você pode assumir que está tudo bem:

coinbase_commerce.error.AuthenticationError: Request id 10780b77-1021-4b09-b53b-a590ea044380: No such API key.

Páginas úteis para trabalhar com a API Coinbase:

Com isso, decida qual abordagem você gostaria de adotar, Coinbase Charges ou Coinbase Checkout.

Cobranças da Coinbase

Esta parte do tutorial mostra como aceitar pagamentos usando a API Coinbase Charges .

Coinbase Charges é a abordagem mais personalizável para coletar pagamentos de criptomoedas. Com essa abordagem, você tem controle total sobre as cobranças.

Fluxo de trabalho:

  1. Use um cliente para se conectar à API Coinbase Commerce
  2. Criar uma cobrança (de JSON)
  3. Busque a cobrança recém-criada e passe-a para o modelo
  4. Redirecionar o usuário para o site hospedado pelo Coinbase Commerce
  5. (Opcional) Verifique a cobrança usando webhooks

Criar uma cobrança

Para solicitar um pagamento em criptomoeda, você cria uma cobrança . Como os pagamentos de criptomoeda são pagamentos por push , uma cobrança expirará após um período de espera se nenhum pagamento for detectado. As cobranças são identificadas por um código exclusivo de 8 caracteres.

Atualize home_viewpara criar uma cobrança :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    domain_url = 'http://localhost:8000/'
    product = {
        'name': 'Coffee',
        'description': 'A really good local coffee.',
        'local_price': {
            'amount': '5.00',
            'currency': 'USD'
        },
        'pricing_type': 'fixed_price',
        'redirect_url': domain_url + 'success/',
        'cancel_url': domain_url + 'cancel/',
    }
    charge = client.charge.create(**product)

    return render(request, 'home.html', {
        'charge': charge,
    })

Primeiro inicializamos o cliente passando COINBASE_COMMERCE_API_KEYpara ele. Em seguida, criamos um objeto JSON que representa nosso produto (fornecemos o nome, descrição etc.). Também passamos redirect_urle cancel_urlà cobrança, que implementaremos aqui em breve. Em seguida, descompactamos o objeto JSON e usamos o cliente para criar uma cobrança. Por fim, passamos para o modelo inicial como contexto.

Agora podemos acessar as informações de cobrança em templates/home.html . Atualize o modelo assim:

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <div class="card-body">
          <h5 class="card-title">{{ charge.name }}</h5>
          <p class="card-text">
            <span>{{ charge.description }}</span>
            <br>
            <span>${{ charge.pricing.local.amount }} {{ charge.pricing.local.currency }}</span>
          </p>
          <div>
            <a class="btn btn-primary w-100" href="{{ charge.hosted_url }}">Purchase</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Consulte a documentação da API de cobrança para obter todas as informações relacionadas à cobrança que você pode exibir no modelo.

Execute o servidor de desenvolvimento:

(env)$ python manage.py runserver

http://localhost:8000/ agora deve ficar assim:

Página inicial do Django + Coinbase

Não teste ainda. Faremos isso em breve.

Criar as visualizações de redirecionamento

Vamos implementar as views para redirect_urle cancel_urlque passamos para a cobrança.

Crie duas novas visualizações dentro de payments/views.py :

# payments/views.py

def success_view(request):
    return render(request, 'success.html', {})


def cancel_view(request):
    return render(request, 'cancel.html', {})

Registre as novas visualizações dentro de payments/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'), # new
    path('cancel/', views.cancel_view, name='payments-cancel'), # new
]

E templates/sucesso.html :

<!-- templates/success.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been successful.</p>
    </div>
  </body>
</html>

E templates/cancel.html :

<!-- templates/cancel.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Charge</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <p>Your payment has been cancelled.</p>
    </div>
  </body>
</html>

Agora, após a confirmação do pagamento, o usuário será redirecionado para redirect_url. No caso de cancelarem o pagamento (ou a cobrança expirar), eles serão redirecionados para cancel_url.

Teste

Infelizmente, o Coinbase Commerce não suporta contas de sandbox para teste, o que significa que você precisará usar criptografia real para testar seu aplicativo.

Execute o servidor, navegue até http://localhost:8000/ e clique no botão "Comprar". Você será redirecionado para o site hospedado pelo Coinbase Commerce:

Coinbase Commerce Charges

Quando você seleciona uma criptomoeda com a qual deseja pagar, um endereço de carteira (e um código QR) será mostrado:

Endereços de cobranças comerciais da Coinbase

Você tem 60 minutos para transferir a criptografia antes que a carga expire.

Depois de enviar a criptomoeda, levará alguns minutos (dependendo de qual criptomoeda você usa) para que os mineradores confirmem sua transação. Depois que a transação obtiver o número necessário de confirmações (com base na criptomoeda), você será redirecionado para o URL associado ao redirect_url.

Os pagamentos aparecerão no Painel de Comércio em "Pagamentos":

Coinbase Commerce Payments

Pule para a seção "Confirmar pagamentos com Webhooks" para saber mais sobre a confirmação de pagamento.

Coinbase Check-out

Esta parte do tutorial mostra como aceitar pagamentos usando a API Coinbase Checkout . Se você decidiu usar Coinbase Charges, sinta-se à vontade para pular esta seção e ir para a seção "Confirmar pagamentos com Webhooks".

O Coinbase Checkout é a maneira mais fácil de coletar pagamentos de criptomoedas com o Coinbase Commerce. Com essa abordagem, as cobranças serão geradas automaticamente para você. Essa abordagem é apropriada ao trabalhar com produtos fixos.

Fluxo de trabalho:

  1. Use um cliente para se conectar à API Coinbase Commerce
  2. Busque um checkout da Coinbase Commerce API e passe-o para o modelo
  3. (Opcional) Adicione o código HTML necessário ao modelo se estiver lidando com checkouts incorporados
  4. Redirecione o usuário para o site hospedado pelo Coinbase Commerce OU use um checkout incorporado
  5. (Opcional) Verifique a cobrança usando webhooks

Criar um check-out

Existem duas maneiras de criar um checkout:

  1. Programaticamente através da biblioteca coinbase-commerce
  2. Manualmente no painel do Coinbase Commerce

Para simplificar, usaremos o Commerce Dashboard .

Navegue até "Checkouts" e clique em "Create Checkout":

Coinbase Commerce Checkout

Clique em "Vender um Produto". Insira o nome do produto, descrição e preço. Clique em "Avançar". Em "Informações do cliente", selecione "Não coletar nenhuma informação". Em seguida, clique em "Concluído.

O Coinbase Commerce gerou todo o código HTML necessário que você precisa adicionar ao seu modelo inicial. Você pode ver isso na guia "Incorporar". Para tornar o aplicativo da Web mais modular e reutilizável, buscaremos as informações de checkout em home_viewvez de codificá-las no modelo. Para fazer isso, primeiro precisamos obter o ID de checkout copiando o URL da página hospedada:

Coinbase Commerce Checkout

O link permanente deve ser algo assim:

https://commerce.coinbase.com/checkout/df2d7c68-145e-4537-86fa-1cac705eb748

Estamos interessados ​​apenas no último segmento do URL, que representa o ID do checkout:

df2d7c68-145e-4537-86fa-1cac705eb748

Salve isso dentro do arquivo core/settings.py assim:

# core/settings.py

COINBASE_CHECKOUT_ID = '<your checkout id>'

Atualizar payments/views.py :

# payments/views.py

from coinbase_commerce.client import Client
from django.shortcuts import render

from core import settings


def home_view(request):
    client = Client(api_key=settings.COINBASE_COMMERCE_API_KEY)
    checkout = client.checkout.retrieve(settings.COINBASE_CHECKOUT_ID)
    checkout_link = f'https://commerce.coinbase.com/checkout/{checkout.id}'

    return render(request, 'home.html', {
        'checkout': checkout,
        'checkout_link': checkout_link,
    })

Este código busca o checkout e o passa para o template.

Por fim, precisamos modificar o modelo inicial para usar o checkout. Você pode usar um:

  1. Página hospedada - o usuário é redirecionado para um site do Coinbase Checkout
  2. Página incorporada - tudo acontece no seu site

Para fins educacionais, usaremos as duas abordagens.

Atualize templates/home.html :

<!-- templates/home.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django + Coinbase Checkout</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container mt-5">
      <div class="card w-25">
        <!-- Coinbase checkout details -->
        <div class="card-body">
          <h5 class="card-title">{{ checkout.name }}</h5>
          <p class="card-text">
            {{ checkout.description }}<br>
            {{ checkout.local_price.amount }} {{ checkout.local_price.currency }}
          </p>
          <div>
            <!-- Coinbase hosted approach (script not required) -->
            <a class="btn btn-primary w-100" href="{{ checkout_link }}">Purchase (hosted)</a>
            <!-- Coinbase embedded approach (script required) -->
            <div class="mt-2">
              <a class="btn btn-primary buy-with-crypto w-100" href="{{ checkout_link }}">Purchase (embedded)</a>
              <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Execute o servidor e navegue até http://localhost:8000/ :

Exemplo de checkout comercial da Coinbase

O aplicativo é completamente funcional neste momento. Não teste nada ainda. Faremos isso na próxima seção.

Teste

Infelizmente, o Coinbase Commerce não suporta contas de sandbox para teste, o que significa que você precisará usar criptografia real para testar seu aplicativo.

Com o servidor em execução, navegue até http://localhost:8000/ . Você pode testar usando o site hospedado pela Coinbase ou o checkout incorporado. Sua escolha.

Quando você seleciona uma criptomoeda com a qual deseja pagar, um endereço de carteira (e um código QR) será mostrado:

Endereços de cobranças comerciais da Coinbase

Você tem 60 minutos para transferir a criptografia antes que a carga expire.

Depois de enviar a criptomoeda, levará alguns minutos (dependendo de qual criptomoeda você usa) para que os mineradores confirmem sua transação. Depois que a transação obtiver o número necessário de confirmações (com base na criptomoeda), você receberá uma mensagem "Pagamento concluído".

Os pagamentos aparecerão no Painel de Comércio em "Pagamentos":

Coinbase Commerce Payments

Confirme pagamentos com Webhooks

Nosso aplicativo funciona bem neste momento, mas ainda não podemos confirmar pagamentos programaticamente. Apenas redirecionamos o usuário para a página de sucesso após o check-out, mas não podemos confiar apenas nessa página, pois a confirmação do pagamento ocorre de forma assíncrona.

Você costuma lidar com dois tipos diferentes de eventos ao programar: eventos síncronos, que têm efeito e resultados imediatos (por exemplo, criação de uma cobrança), e eventos assíncronos, que não têm resultado imediato (por exemplo, confirmação de pagamentos). Como a confirmação do pagamento é feita de forma assíncrona, o usuário pode ser redirecionado para a página de sucesso antes que o pagamento seja confirmado e antes de recebermos seus fundos.

Para ser notificado quando o pagamento for concluído, você precisa criar um webhook . Precisaremos criar um endpoint simples em nosso aplicativo, que o Coinbase Commerce chamará sempre que ocorrer um evento (ou seja, quando uma cobrança for confirmada). Ao usar webhooks, podemos ter certeza de que o pagamento foi realizado com sucesso.

Para usar webhooks, precisamos:

  1. Configurar o ponto de extremidade do webhook no aplicativo
  2. Registre o endpoint no Coinbase Commerce Dashboard

Configurar o ponto final

Crie uma coinbase_webhookvisualização em payments/views.py :

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            # TODO: run some custom code here

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Esse bloco de código valida a assinatura e a carga útil da solicitação e gera um evento a partir dela. Agora você pode verificar o tipo de evento e executar ações diferentes com base no tipo.

Atualize as importações:

import logging

from coinbase_commerce.client import Client
from coinbase_commerce.error import SignatureVerificationError, WebhookInvalidPayload
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from core import settings

Ignore o erro que COINBASE_COMMERCE_WEBHOOK_SHARED_SECRETainda não existe. Vamos adicioná-lo na próxima etapa.

Registre a URL em payments/urls.py :

# payments/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_view, name='payments-home'),
    path('success/', views.success_view, name='payments-success'),   # only for the Coinbase charges approach
    path('cancel/', views.cancel_view, name='payments-cancel'),      # only for the Coinbase charges approach
    path('webhook/', views.coinbase_webhook),  # new
]

A coinbase_webhookvisualização agora serve como nosso ponto de extremidade de webhook para o qual o Coinbase Commerce enviará eventos quando ocorrerem.

Se você seguiu a abordagem do Coinbase Checkout, não inclua os URLs success/ou .cancel/

Identifique o usuário

Para identificar o usuário em seu webhook, você precisa passar alguns metadados ao criar a cobrança ou ao iniciar a sessão de checkout. Você poderá buscar esses metadados dentro do seu webhook.

A maneira como você passa metadados é diferente dependendo de qual abordagem você usou:

  1. API de cobranças - você terá que anexar metadados ao produto
  2. API Checkout - você terá que passar metadados como um atributo HTML

Identifique o usuário com a API de cobranças

Para identificar o usuário com a API Charges, comece adicionando o seguinte ao productdict dentro de home_view:

# payments/views.py

product = {
    ...
    'metadata': {
        'customer_id': request.user.id if request.user.is_authenticated else None,
        'customer_username': request.user.username if request.user.is_authenticated else None,
    },
    ...
}

Este bloco de código anexa o ID do usuário e o nome de usuário do usuário autenticado.

Agora você pode acessar os metadados dentro da coinbase_webhookvisualização da seguinte forma:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    logger = logging.getLogger(__name__)

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['customer_id'] # new
            customer_username = event['data']['metadata']['customer_username'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id' or 'customer_username'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Identifique o usuário com a API Checkout

Para identificar o usuário com a API do Checkout, precisamos adicionar os metadados como um data-customatributo de dados às âncoras em templates/home.html :

Por exemplo:

<div>
  <!-- Coinbase hosted approach (script not required) -->
  <a
    class="btn btn-primary w-100"
    {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
    href="{{ checkout_link }}"
  >Purchase (hosted)</a>
  <!-- Coinbase embedded approach (script required) -->
  <div class="mt-2">
    <a
      class="btn btn-primary buy-with-crypto w-100"
      {% if user.is_authenticated %}data-custom="{{ user.pk }}"{% endif %}
      href="{{ checkout_link }}"
    >Purchase (embedded)</a>
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>
  </div>
</div>

Você pode então recuperar os metadados dentro da coinbase_webhookvisualização da seguinte forma:

# payments/views.py

@csrf_exempt
@require_http_methods(['POST'])
def coinbase_webhook(request):
    import logging

    request_data = request.body.decode('utf-8')
    request_sig = request.headers.get('X-CC-Webhook-Signature', None)
    webhook_secret = settings.COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET

    try:
        event = Webhook.construct_event(request_data, request_sig, webhook_secret)

        # List of all Coinbase webhook events:
        # https://commerce.coinbase.com/docs/api/#webhooks

        if event['type'] == 'charge:confirmed':
            logger.info('Payment confirmed.')
            customer_id = event['data']['metadata']['custom'] # new
            # TODO: run some custom code here
            # you can also use 'customer_id'
            # to fetch an actual Django user

    except (SignatureVerificationError, WebhookInvalidPayload) as e:
        return HttpResponse(e, status=400)

    logger.info(f'Received event: id={event.id}, type={event.type}')
    return HttpResponse('ok', status=200)

Tenha em mente que o webhook recebe data-customcomo texto simples. Certifique-se de analisá-lo para um número inteiro antes de usá-lo para buscar o usuário no banco de dados.

Registrar o ponto final

Navegue até https://commerce.coinbase.com/dashboard/settings , role para baixo até "Assinaturas do Webhook" e clique em "Adicionar um endpoint":

Coinbase Commerce Webhook

Insira o URL do seu endpoint e pressione "Salvar".

A URL precisa começar com HTTPS, o que significa que você precisa implantar seu aplicativo antes de testá-lo.

Em seguida, clique em "Mostrar segredo compartilhado" e copie o segredo:

Segredo do Webhook do Coinbase Commerce

Adicione o segredo compartilhado ao arquivo settings.py da seguinte forma:

# core/settings.py

COINBASE_COMMERCE_WEBHOOK_SHARED_SECRET = '<your coinbase webhook secret here>'

Testar o ponto final

Com seu aplicativo implantado, você pode enviar uma solicitação de webhook de teste do Commerce Dashboard . Navegue até "Assinaturas do webhook" e clique em "Detalhes" no ponto de extremidade do webhook:

Detalhes do webhook do Coinbase Commerce

Em seguida, clique em "Enviar teste":

Teste de detalhes do webhook do Coinbase Commerce

Por fim, selecione a opção "charge:confirmed" e clique novamente em "Enviar teste". Você deve ver o "Pagamento foi bem-sucedido". mensagem de registro.

Conclusão

Neste tutorial, você aprendeu como aceitar pagamentos criptográficos com o Coinbase Commerce. Agora você deve ser capaz de integrá-lo ao Django e verificar pagamentos por meio de um webhook.

Você pode encontrar o código nos seguintes repositórios no GitHub:

  1. django-coinbase-charges
  2. Django-coinbase-checkout

Fonte:  https://testdrive.io

#django #crypto #coinbase 

Aceitando Pagamentos De Criptografia Com Django E Coinbase

CovenantSQL: A Decentralized, Trusted, High Performance, SQL Database

CovenantSQL(CQL) is a Byzantine Fault Tolerant relational database built on SQLite:

  • ServerLess: Free, High Availabile, Auto Sync Database Service for Serverless App
  • SQL: Most SQL-92 support.
  • Decentralize: Running on Open Internet without Central Coordination.
  • Privacy: Access with Granted Permission and Encryption Pass.
  • Immutable: Query History in CQL is Immutable and Trackable.
  • Permission: Column Level ACL and SQL Pattern Whitelist.

What is CQL?

  • Open source alternative of Amazon QLDB
  • Low cost DBaaS
  • Just like filecoin + IPFS is the decentralized file system, CQL is the decentralized database

Quick Start

CQL client supports:

  • macOS X 10.9+
  • Linux 2.6.23+ (x86, x86_64, armeabi-v7a, arm64-v8a)

Developer Guide

How CQL works

3 Layers Arch

CovenantSQL 3 Layer design

  • Layer 1: Global Consensus Layer (the main chain, the middle ring in the architecture diagram):
    • There will only be one main chain throughout the network.
    • Mainly responsible for database Miner and the user’s contract matching, transaction settlement, anti-cheating, shard chain lock hash and other global consensus matters.
  • Layer 2: SQL Consensus Layer (shard chain, rings on both sides):
    • Each database will have its own separate shard chain.
    • Mainly responsible for: the signature, delivery and consistency of the various Transactions of the database. The data history of the permanent traceability is mainly implemented here, and the hash lock is performed in the main chain.
  • Layer 3: Datastore Layer (database engine with SQL-92 support):
    • Each Database has its own independent distributed engine.
    • Mainly responsible for: database storage & encryption, query processing & signature, efficient indexing.

For more details

Performance

Strong consistency bench result (2 miners, 8 core aws c5.2xlarge): CovenantSQL bench

As seen above, the concurrency pressure on the database increased gradually in the first 5 hours, and the write TPS also increased. When the TPS no longer grows, the concurrent pressure is maintained for 100 hours.

Demos

Use cases

Traditional App & ĐApp use cases

TestNet

中文简介

Download Details:

Author: CovenantSQL
Source Code: https://github.com/CovenantSQL/CovenantSQL 
License: Apache-2.0 license

#go #golang #crypto #database 

CovenantSQL: A Decentralized, Trusted, High Performance, SQL Database
Robert  Jack

Robert Jack

1660202939

DeFi Exchange Development Services

Create your own DeFi crypto exchange with cutting edge features from the expert DeFi exchange development services company.

DeFi exchange platform development company

DeFi or open finance is one of the most talked about topics of the crypto market as it has captured a wide range of Fintech Industry and blockchain arena with large benefits. The system has disrupted the traditional finance procedures to an improvised decentralized platform that provides much needed solutions like services like quick loans, lending and borrowing etc. DeFi exchange development provides a variety of services like the ability to manage their own funds by the DeFi participants, easy earning by staking, yield farming and many more. One of the notable highlights of the DeFi crypto exchange platform is its superfast transaction speed and automated transactions with smart contracts DeFi exchange platform development company

As a pioneer Decentralised finance exchange development company, Shamla tech helps to create your own DeFi crypto exchange to bring together global traders by providing a permissionless and trustworthy defi platform.

Benefits of DeFi in the crypto exchange

  • Decentralized platform
  • Secure Transactions
  • Tokenization of Assets
  • Cost-Effective Trade
  • High Transparency
  • Tokens Security
  • Easy cross border Trade
  • Peer-to-Peer Transactions
  • Multi-currency Support.

Features of our DeFi cryptocurrency exchange development

No Intermediary

The lack of intermediary offers great trading experience with improved security and trustworthy peer to peer transactions

Smart Contracts

Smart contracts offer completely reliable and super fast trade with automated transactions also avoiding manual errors.

Top notch Security

The decentralised system upholds security and privacy to the data and funds eliminating the possibility of any hack or unauthorized activity.

Low fees

The transaction fees are cut down drastically without the influence of third parties assuring easy and cheaper cross border trade.

Liquidity

Defi for crypto exchange enhances the liquidity with robust automated liquidity protocols allowing trouble-free trading.

Control over funds

Defi based cryptocurrency exchanges facilitate total ownership to the buyer and seller over their funds and data.

Voting options

Usage of governance tokens in the platform helps build a frictionless financial framework with voting rights for the users.

Transparency

Decentralised exchanges are known for their transparency and this helps the users to avoid any disputes or fraud.

Robust solutions from Leading DeFi exchange development services company

shamlatech is a one stop solution for all the cryptocurrency exchange development script and DeFi exchange development solutions to deal with every sector. We offer popular and trending P2P cryptocurrency exchange script developed skillfully by our developers. Our Decentralised finance based solutions are popular in this field and are experts in offering custom and scalable solutions of the desired platform.
Read more: DeFi exchange development solutions

#Defiexchange

#cryptocurrency 

#Defiexchangedevelopment

#defidevelopment 

#defi 

#exchanges 

#web-development 

#crypto 

#Decentralized platform


 

DeFi Exchange Development Services

What is BlockXpress (BX) | What is BX token

In this article, we'll discuss information about the BlockXpress project and BX token. What is BlockXpress (BX) | What is BX token?

BlockXpress's mission is to provide a one-stop crypto-native e-commerce hub. As we envision accelerating the mass adoption in the web3 e-commerce sector. Whether it's buying your favorite products using cryptocurrencies, P2P trading, buying crypto or even staking our native token $BX. Our crypto-native platform aims to provide a seamless experience to every user base. With technological advancement getting better every day, our team is committed to delivering the next leap in the e-commerce sector

Problem

As we come in the dawn of the new era, infinite possibilities have emerged. One that is about to drastically change is the financial system. From centralized to decentralized, we are more and more aware each day that people are craving for freedom and decentralization. Whether it is to banking the unbank or thru the barter process of selling things commercially without the limits of a normal e commerce we are used to.

Solution

And this is where BlockXpress comes in, in a seamless and our trustless needed technology. The community will have the freedom now to exchange products, without the worry of traditional centralize e-commerce platform and with complete anonymity.

With BlockXpress, use your crypto at will. Whenever you want and whatever you want. Swap your favorite cryptos into $BX token and spend it at as you wish!

Goal

Our project's ultimate goal and vision is to make the crypto adaption more appealing to the masses. To help the ecommerce market take the next leap forward to better serving the people on what they need and when they need it.

Crypto native e-commerce platform eliminates the barriers a traditional e-commerce platform has. Our e-commerce crypto native app will support from staking function, P2P trading to the listing of crypto-related services. With our straightforward UI, we believe that it will eliminate the friction of userbase acquisition.

Security & Audits

We did not only pass a smart contract audit but also passed the KYC of a well-reputable company. With two of the most reputable audit & KYC brands backing our project's name, we boast security and trust at its highest level to ensure the safety of the user base investments. We also believe that renouncing the contract improves the trust between the community and the team, in that said we have renounced the smart contract and have coded it in the simplest manner possible. With this, it would be easier to audit or inspect from a normal investor's point of view. As we believe that the value of the project comes from the community. And so we are committed to protecting the value of investors.

Platform

BlockXpress's mission is to provide a one-stop crypto-native e-commerce hub. As we envision accelerating the mass adoption in the web3 e-commerce sector. Whether it's P2P trading, buying crypto, listing your products on sale, purchasing your favorite leading brands, or even staking our native token $BX. Our crypto-native platform aims to provide a seamless experience to every user base. With technological advancement getting better every day, our team is committed to delivering the next leap in the e-commerce sector. The following feature will emerge as we progress throughout our roadmap

The shopping platform - Will be the flagship product of BlockXpress and will serve as the center of all ecommerce activities. 

P2P Trading - Peer to peer trading allows traders to trade directly with one another without the need for a centralized third party to facilitate the transactions. 

Service listing - On our platform aside from the different types of items. The platform also accepts the listing of crypto-related services. 

Staking - Launch of our staking platform which provides a steady return for our investors as we progress with our roadmap. To give back and value the investor's time and commitment to the project. 

NFT Marketplace - A place where the community can trade their NFTs.

How It Works

  • Sign up: Sign up for an account on BlockXpress
  • Browse: Browse products on the BlockXpress store
  • Buy Now: Choose a product and proceed to checkout.
  • Checkout: Fill up your billing details and proceed to the payment portal. Choose your payment method and pay with your preferred cryptocurrency.

How and Where to Buy BX token?

 BX token is now live on the Binance mainnet. The token address for BX is 0x2a6788bf2354ebc4940656d4721afa0ad0f25f6b. Be cautious not to purchase any other token with a smart contract different from this one (as this can be easily faked). We strongly advise to be vigilant and stay safe throughout the launch. Don’t let the excitement get the best of you.

Just be sure you have enough BNB in your wallet to cover the transaction fees.

You will have to first buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

We will use Binance Exchange here as it is one of the largest crypto exchanges that accept fiat deposits.

Once you finished the KYC process. You will be asked to add a payment method. Here you can either choose to provide a credit/debit card or use a bank transfer, and buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

☞ SIGN UP ON BINANCE

Next step

You need a wallet address to Connect to Pancakeswap Decentralized Exchange, we use Metamask wallet

If you don’t have a Metamask wallet, read this article and follow the steps ☞ What is Metamask wallet | How to Create a wallet and Use

Transfer $BNB to your new Metamask wallet from Binance wallet

Next step

Connect Metamask Wallet to Pancakeswap Decentralized Exchange and Buy, Swap BX token

Contract: 0x2a6788bf2354ebc4940656d4721afa0ad0f25f6b

The top exchange for trading in BX token is currently: PancakeSwap (V2)

Top exchanges for token-coin trading. Follow instructions and make unlimited money

BinancePoloniexBitfinexHuobiMXCProBITGate.io

🔺DISCLAIMER: The Information in the post isn’t financial advice, is intended FOR GENERAL INFORMATION PURPOSES ONLY. Trading Cryptocurrency is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money.

Find more information BX token ☞ Website 

I hope this post will help you. Don't forget to leave a like, comment and sharing it with others. Thank you!

#bitcoin #crypto 

What is BlockXpress (BX) | What is BX token

Buy, Sell and Trade Goldstar Coin (GSC) on Koinbazar

Warm Greetings!!!

We are happy to inform you that the Goldstar Coin (GSC) has been listed on Koinbazar.

Take a look at the Goldstar Coin (GSC) ,

Goldstar is the world's first smart contract marketing matrix plan and a part of the global decentralized ecosystem on the Binance blockchain.

1. Quick transactions

With the use of crypto tokens, customers may avoid the intermediaries that are a part of the conventional asset management system. This minimizes the transaction cost. The processing time for every exchange is being reduced as well. Besides, it's a cost-effective method of transferring values. The crypto tokens exist on the blockchain to be traded 24/7 globally.

2. Transparency

Crypto tokens exist on the blockchain. This allows users to trace their transaction history. Trades are automatically recorded on the blockchain. The transparency and immutability guarantee the authenticity of every token's history. The crypto tokens achieve a level of reliability that other assets can't deliver.

3. Liquidity

Tokenized assets are made available to a wider audience. It increases the market liquidity and prevents the "liquidity premium" involved with investments. Gold Star tokenized asset designs to be traded freely. This allows investors to get fractional ownership of the token's underlying asset. It has resulted in the liquidity of the existing market and investment opportunities for more investors.

Website Link -> https://goldstars.io/

Now you can buy, sell, and trade Goldstar Coin (GSC) in the INR Market of Koinbazar.

Trade GSC/INR -> https://www.koinbazar.com/trade/GSC_INR

Note:

Cryptocurrency trading is subject to high market risk. We request you to trade cautiously. Koinbazar will provide its best efforts to list quality cryptocurrencies, and we will not be responsible for your trading losses.

Happy Trading!!!

Team Koinbazar.

Follow our official social media profiles to get the upcoming trade contest & insights on your pocket!!!

    Facebook - https://www.facebook.com/koinbazar

    Twitter - https://twitter.com/koinbazar

    LinkedIn - https://www.linkedin.com/company/koinbazar

    Pinterest - https://in.pinterest.com/koinbazarexchange

    Instagram - https://www.instagram.com/koinbazar/

    YouTube - https://www.youtube.com/c/koinbazar

    Vk - https://vk.com/koinbazarexchange

    Medium - https://koinbazarexchange.medium.com/

    Telegram Group - https://t.me/koin_bazar

    Telegram Channel - https://t.me/KoinBazar

#crypto #cryptos #cryptocurrency #goldstarcoin 

Buy, Sell and Trade Goldstar Coin (GSC) on Koinbazar