
Sending Notifications to Sellers About Fund Transfers in Binance P2P Chat Using WebSocket and Python Automation
In the world of cryptocurrency trading automation, communication with counterparties remains a crucial element. On Binance P2P, it is often necessary to notify the seller or buyer that the payment has been made. This can be done automatically — without manual input — using a WebSocket connection and Python.
In this article, we’ll walk through how to obtain the necessary chat credentials, connect to Binance's WebSocket service, and send a message in the P2P chat to notify the seller about a fund transfer. This is especially useful if you’re building a P2P bot or automating P2P trading operations.
To begin, we need to obtain the chatWssUrl, listenKey, and listenToken to connect to the WebSocket channel.
retrieveChatCredential Function
def retrieveChatCredential():
# You Api Key on binance
api_key = "11111"
# You Apy Secret on binance
secret_key = "11111"
base_url = "https://api.binance.com"
endpoint = "/sapi/v1/c2c/chat/retrieveChatCredential"
timestamp = int(time.time() * 1000)
query_string = f"timestamp={timestamp}"
signature = hmac.new(
secret_key.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
headers = {
"clientType": "web",
"X-MBX-APIKEY": api_key
}
url = f"{base_url}{endpoint}?{query_string}&signature={signature}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print("Error:", response.status_code, response.text)
return None
Once the credentials are retrieved, we construct the connection URL:
We use the websocket-client library to establish a connection and listen for real-time events from the P2P chat.
chatWssUrl = res_detail['data']['chatWssUrl']
listenKey = res_detail['data']['listenKey']
listenToken = res_detail['data']['listenToken']
chat_wss_url = f"{chatWssUrl}/{listenKey}?token={listenToken}&clientType=web"
🔌 Establishing a WebSocket Connection
def connect_to_websocket():
global reconnect_attempts, ws
reconnect_attempts = 0
ws = websocket.WebSocketApp(
chat_wss_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
When the appropriate moment comes (e.g., after transferring funds to the seller), you can call this function:
def send_message(content, order_no):
if ws_connection:
# ============================================================
# 💖 Donation Notice
#
# English:
# ⚠️ Full functionality is available only after making a donation.
# After your donation, provide the transaction hash and we will unlock the feature for you.
#
# Spanish:
# ⚠️ La funcionalidad completa está disponible solo después de realizar una donación.
# Después de tu donación, proporciona el hash de la transacción y desbloquearemos la función.
# ============================================================
try:
ws_connection.send(json.dumps(response_message))
print(f"Message sent to chat: {content}")
log.logging(f"Message sent payload: {json.dumps(response_message)}")
except Exception as e:
log.logging(f"Message sending error: {str(e)}")
Example call:
send_message("Hello, the payment has been made. Please release the crypto.", "789456123ABCDEF")
Full implementation:
import uuid
import websocket
import time
import hmac
import hashlib
import requests
import json
# You Api Key on binance
api_key = "11111"
# You Apy Secret on binance
secret_key = "11111"
def retrieveChatCredential():
base_url = "https://api.binance.com"
endpoint = "/sapi/v1/c2c/chat/retrieveChatCredential"
timestamp = int(time.time() * 1000)
query_string = f"timestamp={timestamp}"
signature = hmac.new(
secret_key.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
headers = {
"clientType": "web",
"X-MBX-APIKEY": api_key
}
url = f"{base_url}{endpoint}?{query_string}&signature={signature}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print("Error:", response.status_code, response.text)
return None
res_detail = retrieveChatCredential()
if res_detail:
chatWssUrl = res_detail['data']['chatWssUrl']
listenKey = res_detail['data']['listenKey']
listenToken = res_detail['data']['listenToken']
chat_wss_url = f"{chatWssUrl}/{listenKey}?token={listenToken}&clientType=web"
#print("WebSocket URL:", chat_wss_url)
else:
raise Exception("Failed to obtain credentials for WebSocket.")
def generate_uuid():
return str(uuid.uuid4())
def send_message(content, order_no):
if ws_connection:
# ============================================================
# 💖 Donation Notice
#
# English:
# ⚠️ Full functionality is available only after making a donation.
# After your donation, provide the transaction hash and we will unlock the feature for you.
#
# Spanish:
# ⚠️ La funcionalidad completa está disponible solo después de realizar una donación.
# Después de tu donación, proporciona el hash de la transacción y desbloquearemos la función.
# ============================================================
try:
ws_connection.send(json.dumps(response_message))
print(f"Message sent to chat: {content} for orderNo: {order_no} ")
except Exception as e:
print(f"Message sent error: {str(e)}")
def on_open(ws):
global ws_connection
ws_connection = ws
print("WebSocket connection established for Chat")
def on_message(ws, message):
try:
parsed_message = json.loads(message)
print(f"parsed_message: {parsed_message}")
except json.JSONDecodeError:
print("Error JSON:", message)
def on_error(ws, error):
print("Error WebSocket:", error)
def on_close(ws, close_status_code, close_msg):
global reconnect_attempts
print("WebSocket connection closed.", close_msg)
if reconnect_attempts < 5:
reconnect_attempts += 1
print(f"Attempting to reconnect ({reconnect_attempts})...")
time.sleep(5)
connect_to_websocket()
else:
print("The maximum number of reconnection attempts has been reached.")
reconnect_attempts = 0
ws_connection = None
def connect_to_websocket():
global reconnect_attempts, ws
reconnect_attempts = 0
ws = websocket.WebSocketApp(
chat_wss_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
connect_to_websocket()
📈 Faster Transactions — sellers receive notifications more quickly.
🔒 Improved Security — fewer manual actions mean fewer mistakes.
⏱ Time Saving — especially valuable when handling a large volume of trades.
🧠 Bot Integration — automation logic can be embedded into your P2P trading bot.
This type of automation is especially useful for high-volume operations or when managing multiple orders. The bot can instantly notify the seller that the payment has been sent, reducing the overall time required to complete a trade.
We offer a ready-made solution — P2Pay Binance Bot, which includes all the necessary functionality. This bot automatically tracks order statuses, processes crypto payouts to sellers' bank accounts (cards), and simultaneously sends notifications and messages to the chat.
As a result, the P2Pay Binance Bot fully automates the deal processing and communication workflow, ensuring both convenience and security.
Automating Binance P2P chat using Python and WebSocket is a powerful tool for developers building bots or optimizing trading workflows. With access to the chatWssUrl and listenToken, you can connect to the chat, listen for events, and send real-time messages to inform your counterparty about payments.
This article is part of our complete learning guide covering professional cross-exchange cryptocurrency arbitrage.
This article is part of our complete learning guide covering Binance P2P automation, merchant tools and automated trading.
Explore our official technical reference for Binance SAPI endpoints, including C2C ads management, deposit/withdrawal logs, and REST API examples.
Explore Binance API Documentation →