bKash API 接入孟加拉原生支付详细教程
1. bKash简介
bKash是孟加拉国领先的移动金融服务提供商,由BRAC银行运营。它允许用户通过手机进行汇款、支付账单、购物等金融交易。
2. 准备工作
2.1 注册bKash商户账户
- 访问bKash商户门户
- 填写申请表格并提供所需文件(营业执照、税号等)
- 等待审核(通常需要3-5个工作日)
2.2 API凭证获取
审核通过后,你将获得:
- Merchant ID (商户ID)
- Username (用户名)
- Password (密码)
- App Key (应用密钥)
3. bKash API接入详细步骤
3.1 环境准备
- 测试环境:使用bKash提供的沙盒环境进行开发测试
- 生产环境:完成测试后切换至正式API端点
API基础URL:
测试环境: https://tokenized.sandbox.bka.sh/v1.2.0-beta
生产环境: https://tokenized.pay.bka.sh/v1.2.0-beta
3.2 获取访问令牌(Access Token)
每次调用API前需要先获取有效令牌:
import requests
def get_bkash_token():
url = "https://tokenized.sandbox.bka.sh/v1.2.0-beta/tokenized/checkout/token/grant"
headers = {
"Content-Type": "application/json",
"username": "YOUR_USERNAME", # bKash提供的用户名
"password": "YOUR_PASSWORD" # bKash提供的密码
}
data = {
"app_key": "YOUR_APP_KEY", # bKash提供的App Key
"app_secret": "YOUR_APP_SECRET" # bKash提供的App Secret
}
response = requests.post(url, json=data, headers=headers)
if response.status_code == 200:
return response.json()["id_token"]
else:
raise Exception("Failed to get token")
3.3 创建支付请求(Payment Create)
def create_payment(amount, order_id, callback_url):
token = get_bkash_token()
url = f"{BASE_URL}/tokenized/checkout/create"
headers={
"Authorization": token,
"X-APP-KEY":"YOUR_APP_KEY",
"Content-Type":"application/json"
}
data={
"mode":"0011",#固定值,表示Tokenized支付模式
"payerReference":"customer123",#客户唯一标识
callbackURL:callback_url,#回调地址
amount:str(amount),#金额必须转为字符串
currency:"BDT",#孟加拉塔卡
intent:"sale",
merchantInvoiceNumber:order_id,#商户订单号
}
response=requests.post(url,json=data,headers=headers)
if response.status_code==200:
return response.json()["bkashURL"] #返回支付页面URL else:
raise Exception("Payment creation failed")
4.Payment Execution(执行付款)
当用户完成bKASH应用内授权后,您需要使用paymentID来执行实际扣款:
url=f"{BASE_URL}/tokenize/checkout/execute"
headers={ 'authorization':f'Bearer {toke}', 'x-app-key':'YOU APP KEY', }
data={'paymentID': payment id} respose=requestspost.(urL,jso=data headrs=headrs)
if respnse.stts_cde==20O retrn resonse.jon().get('transactionStatus') eli rais Exepton("Paymet execution filed") ```
5.Handle Callback(处理回调)
在创建付款时指定的callback URL将收到以下格式的POST通知:
{
“status”:”success”|“failure”,
“paymentID”:”TR00123456”,
“merchantInvoiceNumber”:”ORD12345”
}
您应该验证交易状态并更新您的系统记录。
6.Query Payment Status(查询交易状态)
对于未收到回调的情况可主动查询:
pytho def query_paymnt(paymen_d):
tokn=get_bkas_tken()
url=f"{BAS_URL}tknzed/chckut/pyment/stus"
heders={ 'Authrization':f'Bare {tken}', X-App-Key':'YO AP KEY', } params={'paymntD': payent_d} respons=rquest.get(rl,prams=prams heders=headrs) retrn rsponse.jon() ```
---
完整实现建议包括错误处理、日志记录和定时对账机制。注意所有金额必须以字符串形式传递且单位为BDT。
7. 高级功能实现
7.1 退款处理
bKash支持全额或部分退款,需在交易完成后的规定时间内操作:
def process_refund(payment_id, amount, reason="Customer request"):
token = get_bkash_token()
url = f"{BASE_URL}/tokenized/checkout/payment/refund"
headers = {
"Authorization": token,
"X-APP-KEY": "YOUR_APP_KEY",
"Content-Type": "application/json"
}
data = {
"paymentID": payment_id,
"amount": str(amount), # 必须为字符串格式
"trxID": "", # 可选参数,原始交易ID
"sku": "", # SKU编码(可选)
"reason": reason # 退款原因说明
}
response = requests.post(url, json=data, headers=headers)
if response.status_code == 200:
return response.json()["transactionStatus"]
else:
raise Exception(f"Refund failed: {response.text}")
7.2 IPN (Instant Payment Notification)配置
建议设置IPN接收实时支付通知:
- 商户后台配置:登录bKash Merchant Portal → Settings → Notification → Set IPN URL
- 服务器端验证:
from flask import Flask, request
app = Flask(__name__)
@app.route('/bkash/callback', methods=['POST'])
def handle_ipn():
data = request.get_json()
# Step1: Verify signature
received_signature=request.headers.get('X-BKASH-SIGNATURE')
your_api_secret="YOUR_SECRET_KEY"
expected_sig=hmac.new(your_api_secret.encode(),
json.dumps(data).encode(),
hashlib.sha256).hexdigest()
if not hmac.compare_digest(received_signature,expected_sig):
return {"status":"Invalid Signature"},403
# Step2: Process notification types
if data['type']=='PaymentSuccess':
update_order_status(data['merchantInvoiceNumber'],'paid')
elif data['type']=='PaymentFailure':
log_failed_payment(data)
return {"status":"OK"},200
if __name__='__main__':
app.run(port=5000)
8.Security Best Practices(安全最佳实践)
1.敏感数据加密
- API密钥和令牌必须加密存储(推荐使用AWS KMS/HashiCorp Vault)
- HTTPS是强制要求,禁用HTTP协议
2.请求验证
#在所有API调用前添加参数校验函数示例:
def validate_payload(amount,invoice_no):
if not isinstance(amount,(int float)) or amount<=0:
raise ValueError("Amount must be positive number")
if len(invoice_no)>50 or not invoice_no.isalnum():
raise ValueError("Invalid Invoice Number format")
3.防重复攻击
建议在服务端实现:
import redis
r=redis.Redis()
def check_duplicate_request(request_id):
key=f"bkash_req:{request_id}"
if r.exists(key):
raise DuplicateRequestError()
r.setex(key ,3600,"processed")#缓存一小时```
9.Troubleshooting Guide(常见问题排查)
| Error Code | Meaning | Solution |
|------------|---------|----------|
| `2055` | Invalid App Key | Check merchant credentials |
| `5014` | Insufficient Balance | Ask customer to top up bKash account |
| `6000` | System Maintenance Retry later |
---
完整项目应包含:定期对账脚本、自动化测试用例和监控仪表板。生产环境部署时考虑以下增强措施:
1.灾备方案:维护备用API端点列表自动切换
2.性能优化:Token缓存机制减少认证调用频率(注意有效期通常为30分钟)