pipeline-sdlc/wwwroot/api/wechat_binding.dspy

62 lines
2.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# wechat_binding.dspy - 微信用户绑定openid → 系统用户)
# action=get: 查当前用户绑定状态
# action=bind: 绑定自己 openid
# action=unbind: 解绑
import json
uid = await get_user()
if not uid:
return json.dumps({"success": False, "error": "请先登录"}, ensure_ascii=False)
action = (params_kw or {}).get('action', 'get')
dbname = get_module_dbname('pipeline-sdlc')
# 查用户 org_id
org_id = ''
try:
async with DBPools().sqlorContext('sage') as sor:
urecs = await sor.sqlExe("SELECT orgid FROM users WHERE id=${u}$", {"u": uid})
if urecs:
org_id = getattr(urecs[0], 'orgid', '') or ''
except Exception:
pass
if action == 'get':
async with DBPools().sqlorContext(dbname) as sor:
recs = await sor.sqlExe(
"SELECT openid FROM wechat_user_binding WHERE user_id=${u}$", {"u": uid})
bound = getattr(recs[0], 'openid', '') if recs else ''
return json.dumps({"success": True, "bound": bool(bound), "openid": bound}, ensure_ascii=False)
elif action == 'bind':
openid = (params_kw or {}).get('openid', '').strip()
if not openid:
return json.dumps({"success": False, "error": "openid 必填"}, ensure_ascii=False)
async with DBPools().sqlorContext(dbname) as sor:
# openid 唯一:检查是否已被其他账号绑定
recs = await sor.sqlExe(
"SELECT user_id FROM wechat_user_binding WHERE openid=${o}$", {"o": openid})
if recs and getattr(recs[0], 'user_id', '') != uid:
return json.dumps({"success": False, "error": "该微信已绑定其他账号"}, ensure_ascii=False)
existing = await sor.sqlExe(
"SELECT id FROM wechat_user_binding WHERE user_id=${u}$", {"u": uid})
if existing:
await sor.sqlExe(
"UPDATE wechat_user_binding SET openid=${o}$ WHERE user_id=${u}$",
{"o": openid, "u": uid})
else:
await sor.C('wechat_user_binding', {
'id': getID(), 'openid': openid, 'user_id': uid, 'org_id': org_id,
})
return json.dumps({"success": True}, ensure_ascii=False)
elif action == 'unbind':
async with DBPools().sqlorContext(dbname) as sor:
await sor.sqlExe(
"DELETE FROM wechat_user_binding WHERE user_id=${u}$", {"u": uid})
return json.dumps({"success": True}, ensure_ascii=False)
else:
return json.dumps({"error": "Unknown action: " + str(action)}, ensure_ascii=False)