【同城鲜羊奶小程序实战】Day 28 :v2.1.0 风控系统 + 反欺诈 + 黑名单 + 规则引擎
Day 28 :v2.1.0 风控系统 + 反欺诈 + 黑名单 + 规则引擎

〇、Day 28 定位
Day 27 完成了「清算系统」,让业务分得清。Day 28 要解决防得住——恶意刷单、批量注册、羊毛党、虚假退款、账号盗用。
为什么风控是刚需:
| 风险类型 | 单次损失 | 频率 |
|---|---|---|
| 刷单(自买自返佣金) | ¥50-500 | 高 |
| 批量注册领券 | ¥20-100/账号 | 高 |
| 秒杀机器人囤货 | ¥100-1000 | 中 |
| 恶意退款 | ¥99-500 | 中 |
| 账号盗用 | ¥500-5000 | 低 |
| 洗钱(虚假订单) | ¥10000+ | 低 |
核心目标:在"交易前"拦截风险,而不是"事后"追损失。
一、Day 28 交付总览
风控架构:
二、业务规则设计
2.1 风控规则 docs/business/risk-rules.md
# 风控系统规则
## 一、风控场景
| 场景 | code | 说明 |
|------|------|------|
| 用户注册 | register | 批量注册、机器注册 |
| 下单 | order_create | 刷单、异常地址 |
| 支付 | payment | 盗卡、异常金额 |
| 秒杀 | seckill | 机器人抢购 |
| 提现 | withdraw | 洗钱、套现 |
| 佣金结算 | commission | 自买自返、刷佣金 |
| 清算打款 | settlement | 账户异常 |
## 二、决策类型
| 决策 | 说明 | 用户体验 |
|------|------|---------|
| `pass` | 通过 | 无感知 |
| `challenge` | 挑战 | 弹验证码/滑块 |
| `review` | 人工审核 | 提示"审核中" |
| `reject` | 拒绝 | 提示"操作受限" |
## 三、评分机制
**风险分 0-100**:
- 0-30:低风险 → `pass`
- 31-60:中风险 → `challenge`
- 61-85:高风险 → `review`
- 86-100:极高风险 → `reject`
**评分累加**:每条规则命中加 N 分,多规则叠加。
## 四、核心规则
### 规则1:下单频率
条件:同用户 5 分钟内下单 >= 5 次
分值:+30
决策:challenge
### 规则2:IP 异常
条件:同 IP 1 小时内下单 >= 20 次
分值:+40
决策:review
### 规则3:设备指纹
条件:同设备 24 小时内注册 >= 3 个账号
分值:+50
决策:reject(注册)
### 规则4:收货地址异常
条件:同一地址 24 小时内 >= 10 单
分值:+35
决策:review
### 规则5:佣金刷单
条件:自己下单时,推荐人是自己(通过设备识别)
分值:+80
决策:reject
### 规则6:金额异常
条件:单笔支付 > 用户历史平均 10 倍
分值:+45
决策:review
### 规则7:秒杀机器人
条件:秒杀请求间隔 < 100ms
分值:+60
决策:challenge + 降速
### 规则8:异地登录
条件:当前 IP 归属地与历史常用地距离 > 1000km
分值:+40
决策:challenge(短信验证)
## 五、黑白名单
**黑名单**:
- IP 黑名单:永久拒绝
- 设备黑名单:永久拒绝
- 用户黑名单:账号冻结
- 手机号黑名单:无法下单
**白名单**:
- VIP 客户:跳过部分规则
- 内部测试账号:跳过所有规则
- 白名单 IP:跳过 IP 规则
## 六、名单自动加入
- 用户 `reject` >= 3 次 → 进入黑名单
- IP `reject` >= 10 次 → 进入 IP 黑名单
- 设备 `reject` >= 5 次 → 进入设备黑名单
## 七、决策留痕
每次决策记录:
- 输入(用户、IP、设备、场景、金额)
- 命中规则(规则 ID、规则名、分值)
- 总分
- 决策结果
- 后续效果(是否最终支付、是否退款)
## 八、规则配置
所有规则**后台可配**:
- 阈值(次数、时间窗口、金额)
- 分值
- 决策
- 生效时间
- 城市范围(多城市可选)
2.2 决策流程图
三、数据库设计
3.1 迁移脚本 databases/migrations/v2.1.0.sql
-- ============================================
-- v2.1.0 风控系统
-- 执行时间:2025-01-28
-- ============================================
CREATE DATABASE IF NOT EXISTS `risk_db` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE risk_db;
-- ========== 1. 风控规则表 ==========
CREATE TABLE IF NOT EXISTS `risk_rules` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`rule_code` VARCHAR(64) NOT NULL UNIQUE COMMENT '规则编码',
`rule_name` VARCHAR(128) NOT NULL,
`scene` VARCHAR(32) NOT NULL COMMENT '适用场景',
`rule_type` VARCHAR(20) NOT NULL DEFAULT 'threshold' COMMENT 'threshold/pattern/list/score',
`rule_config` JSON NOT NULL COMMENT '规则配置:阈值、窗口等',
`score` INT NOT NULL DEFAULT 10 COMMENT '命中增加的分值',
`decision` VARCHAR(20) DEFAULT 'challenge' COMMENT '建议决策',
-- 生效范围
`city_scope` JSON DEFAULT NULL COMMENT '适用城市,NULL=全国',
`effective_from` TIMESTAMP NULL DEFAULT NULL,
`effective_to` TIMESTAMP NULL DEFAULT NULL,
-- 状态
`status` TINYINT DEFAULT 1,
`priority` INT DEFAULT 100 COMMENT '优先级(数字小先执行)',
`description` VARCHAR(500) DEFAULT '',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY `idx_scene_status` (`scene`, `status`),
KEY `idx_rule_code` (`rule_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='风控规则';
-- ========== 2. 黑名单表 ==========
CREATE TABLE IF NOT EXISTS `risk_blacklists` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`list_type` VARCHAR(20) NOT NULL COMMENT 'user/ip/device/phone/address',
`list_value` VARCHAR(255) NOT NULL COMMENT '值',
`reason` VARCHAR(255) DEFAULT '',
`risk_level` VARCHAR(20) DEFAULT 'high' COMMENT 'low/medium/high',
`source` VARCHAR(20) DEFAULT 'auto' COMMENT 'auto/manual',
`source_ref` VARCHAR(64) DEFAULT '' COMMENT '来源引用(如风控事件ID)',
`expire_at` TIMESTAMP NULL DEFAULT NULL COMMENT '过期时间,NULL=永久',
`hit_count` INT DEFAULT 0 COMMENT '命中次数',
`last_hit_at` TIMESTAMP NULL DEFAULT NULL,
`operator_id` INT UNSIGNED DEFAULT 0,
`remark` VARCHAR(500) DEFAULT '',
`status` TINYINT DEFAULT 1,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uk_type_value` (`list_type`, `list_value`),
KEY `idx_type_status` (`list_type`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='黑名单';
-- ========== 3. 白名单表 ==========
CREATE TABLE IF NOT EXISTS `risk_whitelists` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`list_type` VARCHAR(20) NOT NULL COMMENT 'user/ip/device/phone',
`list_value` VARCHAR(255) NOT NULL,
`reason` VARCHAR(255) DEFAULT '',
`scope` VARCHAR(200) DEFAULT 'all' COMMENT 'all 或指定场景逗号分隔',
`expire_at` TIMESTAMP NULL DEFAULT NULL,
`status` TINYINT DEFAULT 1,
`operator_id` INT UNSIGNED DEFAULT 0,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uk_type_value` (`list_type`, `list_value`),
KEY `idx_type_status` (`list_type`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='白名单';
-- ========== 4. 风控事件表 ==========
CREATE TABLE IF NOT EXISTS `risk_events` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`event_id` VARCHAR(64) NOT NULL UNIQUE,
`scene` VARCHAR(32) NOT NULL,
-- 主体
`user_id` INT UNSIGNED DEFAULT 0,
`ip` VARCHAR(64) DEFAULT '',
`device_id` VARCHAR(64) DEFAULT '',
`phone` VARCHAR(20) DEFAULT '',
`city_id` INT UNSIGNED DEFAULT 1,
-- 业务数据
`biz_type` VARCHAR(32) DEFAULT '' COMMENT '业务类型',
`biz_id` VARCHAR(64) DEFAULT '' COMMENT '业务ID(如订单号)',
`amount` DECIMAL(10,2) DEFAULT 0,
`context` JSON DEFAULT NULL COMMENT '其他上下文',
-- 决策
`score` INT DEFAULT 0 COMMENT '风险分',
`decision` VARCHAR(20) NOT NULL COMMENT 'pass/challenge/review/reject',
`hit_rules` JSON DEFAULT NULL COMMENT '命中规则列表',
-- 后续追踪
`final_result` VARCHAR(32) DEFAULT '' COMMENT '最终结果(paid/cancelled/failed)',
`final_result_at` TIMESTAMP NULL DEFAULT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
KEY `idx_user_time` (`user_id`, `created_at`),
KEY `idx_scene_time` (`scene`, `created_at`),
KEY `idx_decision_time` (`decision`, `created_at`),
KEY `idx_ip_time` (`ip`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='风控事件';
-- ========== 5. 名单命中日志 ==========
CREATE TABLE IF NOT EXISTS `risk_list_hits` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`event_id` VARCHAR(64) NOT NULL,
`list_type` VARCHAR(20) NOT NULL,
`list_value` VARCHAR(255) NOT NULL,
`list_kind` VARCHAR(20) NOT NULL COMMENT 'black/white',
`scene` VARCHAR(32) DEFAULT '',
`user_id` INT UNSIGNED DEFAULT 0,
`decision` VARCHAR(20) DEFAULT '',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
KEY `idx_event` (`event_id`),
KEY `idx_list_value` (`list_type`, `list_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='名单命中日志';
-- ========== 6. 规则命中统计 ==========
CREATE TABLE IF NOT EXISTS `risk_rule_stats` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`stat_date` DATE NOT NULL,
`rule_code` VARCHAR(64) NOT NULL,
`scene` VARCHAR(32) NOT NULL,
`city_id` INT UNSIGNED DEFAULT 0,
`hit_count` INT DEFAULT 0,
`pass_count` INT DEFAULT 0,
`reject_count` INT DEFAULT 0,
`avg_score` DECIMAL(6,2) DEFAULT 0,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uk_date_rule_scene_city` (`stat_date`, `rule_code`, `scene`, `city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规则命中统计';
-- ========== 7. 评分阈值配置 ==========
CREATE TABLE IF NOT EXISTS `risk_score_configs` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`scene` VARCHAR(32) NOT NULL COMMENT '场景,*表示全局',
`pass_max` INT DEFAULT 30 COMMENT '通过上限',
`challenge_max` INT DEFAULT 60,
`review_max` INT DEFAULT 85,
`status` TINYINT DEFAULT 1,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uk_scene` (`scene`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='评分阈值配置';
-- ========== 8. 初始化规则 ==========
INSERT IGNORE INTO `risk_rules`
(`rule_code`, `rule_name`, `scene`, `rule_type`, `rule_config`, `score`, `decision`, `status`, `priority`, `description`)
VALUES
('order_freq_5m', '下单频率-5分钟', 'order_create', 'threshold',
'{"window_seconds": 300, "field": "user_id", "max_count": 5}',
30, 'challenge', 1, 10, '同用户5分钟内下单>=5次'),
('order_ip_1h', 'IP下单频率-1小时', 'order_create', 'threshold',
'{"window_seconds": 3600, "field": "ip", "max_count": 20}',
40, 'review', 1, 10, '同IP 1小时内下单>=20次'),
('register_device_24h', '同设备批量注册', 'register', 'threshold',
'{"window_seconds": 86400, "field": "device_id", "max_count": 3}',
50, 'reject', 1, 10, '同设备24小时内注册>=3个账号'),
('order_address_24h', '同地址高频下单', 'order_create', 'threshold',
'{"window_seconds": 86400, "field": "address_id", "max_count": 10}',
35, 'review', 1, 20, '同一地址24小时内下单>=10单'),
('commission_self', '自买自返佣金', 'commission', 'pattern',
'{"check": "device_match_inviter"}',
80, 'reject', 1, 5, '下单用户与推荐人同设备'),
('payment_amount_anomaly', '支付金额异常', 'payment', 'threshold',
'{"max_amount": 50000}',
45, 'review', 1, 30, '单笔金额超50000'),
('seckill_robot', '秒杀机器人', 'seckill', 'pattern',
'{"min_interval_ms": 100}',
60, 'challenge', 1, 10, '秒杀请求间隔<100ms'),
('login_geo_jump', '异地登录', 'login', 'pattern',
'{"max_distance_km": 1000}',
40, 'challenge', 1, 20, '登录地与常用地距离>1000km');
INSERT IGNORE INTO `risk_score_configs` (`scene`, `pass_max`, `challenge_max`, `review_max`)
VALUES ('*', 30, 60, 85);
3.2 回滚脚本 databases/migrations/v2.1.0-rollback.sql
USE risk_db;
DROP TABLE IF EXISTS `risk_score_configs`;
DROP TABLE IF EXISTS `risk_rule_stats`;
DROP TABLE IF EXISTS `risk_list_hits`;
DROP TABLE IF EXISTS `risk_events`;
DROP TABLE IF EXISTS `risk_whitelists`;
DROP TABLE IF EXISTS `risk_blacklists`;
DROP TABLE IF EXISTS `risk_rules`;
四、后端实现
4.1 风控服务 services/risk/(端口 9517)
4.1.1 services/risk/.env
APP_NAME=risk-service
APP_ENV=prod
SCAN_CACHEABLE=true
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=risk_db
DB_USERNAME=goat
DB_PASSWORD=goat123
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_AUTH=
CONSUL_URI=http://consul:8500
NACOS_HOST=nacos
NACOS_PORT=8848
NACOS_NAMESPACE_ID=prod
JWT_SECRET=same-as-other-services
# 风控默认配置
RISK_DEFAULT_PASS_MAX=30
RISK_DEFAULT_CHALLENGE_MAX=60
RISK_DEFAULT_REVIEW_MAX=85
RISK_RULE_CACHE_TTL=300
RISK_AUTO_BLACKLIST_ENABLED=true
4.1.2 services/risk/config/autoload/server.php
<?php
declare(strict_types=1);
use Hyperf\Server\Event;
use Hyperf\Server\Server;
return [
'mode' => SWOOLE_PROCESS,
'servers' => [
[
'name' => 'http',
'type' => Server::SERVER_HTTP,
'host' => '0.0.0.0',
'port' => 9517,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
],
'options' => [
'enable_coroutine' => true,
'worker_num' => swoole_cpu_num() * 2,
],
],
],
'swoole' => [
'hook_flags' => SWOOLE_HOOK_ALL,
],
];
4.2 模型
services/risk/app/Model/RiskRule.php
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
class RiskRule extends Model
{
protected ?string $table = 'risk_rules';
protected array $fillable = [
'rule_code', 'rule_name', 'scene', 'rule_type', 'rule_config',
'score', 'decision', 'city_scope', 'effective_from', 'effective_to',
'status', 'priority', 'description',
];
protected array $casts = [
'id' => 'integer',
'rule_config' => 'json',
'city_scope' => 'json',
'score' => 'integer',
'status' => 'integer',
'priority' => 'integer',
];
public bool $timestamps = true;
}
services/risk/app/Model/RiskEvent.php
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
class RiskEvent extends Model
{
protected ?string $table = 'risk_events';
protected array $fillable = [
'event_id', 'scene', 'user_id', 'ip', 'device_id', 'phone', 'city_id',
'biz_type', 'biz_id', 'amount', 'context',
'score', 'decision', 'hit_rules',
'final_result', 'final_result_at',
];
protected array $casts = [
'id' => 'integer',
'user_id' => 'integer',
'city_id' => 'integer',
'amount' => 'float',
'score' => 'integer',
'context' => 'json',
'hit_rules' => 'json',
];
public bool $timestamps = false;
}
services/risk/app/Model/RiskBlacklist.php
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
class RiskBlacklist extends Model
{
protected ?string $table = 'risk_blacklists';
protected array $fillable = [
'list_type', 'list_value', 'reason', 'risk_level',
'source', 'source_ref', 'expire_at',
'hit_count', 'last_hit_at', 'operator_id', 'remark', 'status',
];
protected array $casts = [
'id' => 'integer',
'hit_count' => 'integer',
'operator_id' => 'integer',
'status' => 'integer',
];
public bool $timestamps = true;
}
services/risk/app/Model/RiskWhitelist.php
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
class RiskWhitelist extends Model
{
protected ?string $table = 'risk_whitelists';
protected array $fillable = [
'list_type', 'list_value', 'reason', 'scope',
'expire_at', 'status', 'operator_id',
];
protected array $casts = [
'id' => 'integer',
'status' => 'integer',
'operator_id' => 'integer',
];
public bool $timestamps = true;
}
4.3 名单服务
services/risk/app/Service/ListService.php
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\RiskBlacklist;
use App\Model\RiskListHit;
use App\Model\RiskWhitelist;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
class ListService
{
#[Inject]
private Redis $redis;
/**
* 检查输入是否命中名单
* 返回:['hit' => true, 'kind' => 'black'|'white', 'list_type' => ..., 'value' => ...]
*/
public function check(array $input, string $scene = '*'): array
{
$checks = [
'user_id' => ['type' => 'user', 'value' => $input['user_id'] ?? 0],
'ip' => ['type' => 'ip', 'value' => $input['ip'] ?? ''],
'device_id' => ['type' => 'device', 'value' => $input['device_id'] ?? ''],
'phone' => ['type' => 'phone', 'value' => $input['phone'] ?? ''],
];
// 先查白名单(白名单优先级最高)
foreach ($checks as $check) {
if (empty($check['value'])) continue;
if ($this->inWhitelist($check['type'], (string) $check['value'], $scene)) {
return [
'hit' => true,
'kind' => 'white',
'list_type' => $check['type'],
'value' => $check['value'],
];
}
}
// 再查黑名单
foreach ($checks as $check) {
if (empty($check['value'])) continue;
$black = $this->getBlacklist($check['type'], (string) $check['value']);
if ($black !== null) {
// 记录命中
$this->recordHit($check['type'], (string) $check['value'], 'black', $input, $scene);
return [
'hit' => true,
'kind' => 'black',
'list_type' => $check['type'],
'value' => $check['value'],
'reason' => $black['reason'] ?? '',
];
}
}
return ['hit' => false];
}
/**
* 检查黑名单(Redis 优先)
*/
private function getBlacklist(string $type, string $value): ?array
{
$key = "risk:blacklist:{$type}:{$value}";
$cached = $this->redis->get($key);
if ($cached !== false && $cached !== null) {
if ($cached === '1') return ['reason' => 'cached'];
$data = json_decode($cached, true);
if (isset($data['expire_at']) && strtotime($data['expire_at']) < time()) {
$this->redis->del($key);
return null;
}
return $data;
}
// 回源 DB
$record = RiskBlacklist::where('list_type', $type)
->where('list_value', $value)
->where('status', 1)
->where(function ($q) {
$q->whereNull('expire_at')
->orWhere('expire_at', '>', date('Y-m-d H:i:s'));
})
->first();
if (!$record) {
// 缓存空结果 5 分钟
$this->redis->setex($key, 300, '0');
return null;
}
$data = ['reason' => $record->reason, 'expire_at' => $record->expire_at];
$this->redis->setex($key, 3600, json_encode($data));
return $data;
}
private function inWhitelist(string $type, string $value, string $scene): bool
{
$key = "risk:whitelist:{$type}:{$value}:{$scene}";
$cached = $this->redis->get($key);
if ($cached !== false && $cached !== null) {
return $cached === '1';
}
$exists = RiskWhitelist::where('list_type', $type)
->where('list_value', $value)
->where('status', 1)
->where(function ($q) {
$q->whereNull('expire_at')
->orWhere('expire_at', '>', date('Y-m-d H:i:s'));
})
->where(function ($q) use ($scene) {
$q->where('scope', 'all')
->orWhere('scope', 'like', "%{$scene}%");
})
->exists();
$this->redis->setex($key, 600, $exists ? '1' : '0');
return $exists;
}
/**
* 记录命中
*/
private function recordHit(string $type, string $value, string $kind, array $input, string $scene): void
{
try {
RiskListHit::create([
'event_id' => $input['event_id'] ?? '',
'list_type' => $type,
'list_value' => $value,
'list_kind' => $kind,
'scene' => $scene,
'user_id' => (int) ($input['user_id'] ?? 0),
]);
} catch (\Throwable $e) {
// 忽略
}
// 更新命中次数
RiskBlacklist::where('list_type', $type)
->where('list_value', $value)
->increment('hit_count', 1, ['last_hit_at' => date('Y-m-d H:i:s')]);
}
/**
* 添加黑名单
*/
public function addToBlacklist(string $type, string $value, string $reason, string $source = 'manual', ?string $expireAt = null, int $operatorId = 0): bool
{
try {
RiskBlacklist::updateOrCreate(
['list_type' => $type, 'list_value' => $value],
[
'reason' => $reason,
'source' => $source,
'expire_at' => $expireAt,
'operator_id' => $operatorId,
'status' => 1,
]
);
// 清除缓存
$this->redis->del("risk:blacklist:{$type}:{$value}");
return true;
} catch (\Throwable $e) {
return false;
}
}
/**
* 移除黑名单
*/
public function removeFromBlacklist(string $type, string $value): bool
{
$affected = RiskBlacklist::where('list_type', $type)
->where('list_value', $value)
->update(['status' => 0]);
$this->redis->del("risk:blacklist:{$type}:{$value}");
return $affected > 0;
}
}
4.4 规则引擎(核心)
services/risk/app/Service/RuleEngine.php
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\RiskRule;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Psr\Log\LoggerInterface;
class RuleEngine
{
#[Inject]
private Redis $redis;
#[Inject]
private LoggerInterface $logger;
/**
* 加载场景下所有启用的规则
*/
private function loadRules(string $scene, int $cityId): array
{
$rules = RiskRule::where('scene', $scene)
->where('status', 1)
->orderBy('priority')
->get();
return $rules->filter(function ($rule) use ($cityId) {
// 城市过滤
if (!empty($rule->city_scope) && $cityId > 0 && !in_array($cityId, (array) $rule->city_scope)) {
return false;
}
// 生效时间过滤
$now = time();
if ($rule->effective_from && strtotime($rule->effective_from) > $now) return false;
if ($rule->effective_to && strtotime($rule->effective_to) < $now) return false;
return true;
})->values()->toArray();
}
/**
* 执行规则,返回命中结果
*/
public function evaluate(string $scene, array $input): array
{
$cityId = (int) ($input['city_id'] ?? 1);
$rules = $this->loadRules($scene, $cityId);
$hitRules = [];
$totalScore = 0;
foreach ($rules as $rule) {
try {
$result = $this->evaluateRule($rule, $input);
if ($result['hit']) {
$hitRules[] = [
'rule_code' => $rule['rule_code'],
'rule_name' => $rule['rule_name'],
'score' => (int) $rule['score'],
'decision' => $rule['decision'],
'detail' => $result['detail'] ?? '',
];
$totalScore += (int) $rule['score'];
}
} catch (\Throwable $e) {
$this->logger->error('[Risk] 规则执行异常', [
'rule' => $rule['rule_code'] ?? '',
'error' => $e->getMessage(),
]);
}
}
return [
'score' => min(100, $totalScore),
'hit_rules' => $hitRules,
];
}
/**
* 执行单条规则
*/
private function evaluateRule(array $rule, array $input): array
{
$config = is_string($rule['rule_config'])
? json_decode($rule['rule_config'], true)
: $rule['rule_config'];
switch ($rule['rule_type']) {
case 'threshold':
return $this->evalThreshold($config, $input);
case 'pattern':
return $this->evalPattern($config, $input);
case 'score':
return ['hit' => false]; // 特殊规则,单独处理
default:
return ['hit' => false];
}
}
/**
* 阈值规则(如频率限制)
*/
private function evalThreshold(array $config, array $input): array
{
$window = (int) ($config['window_seconds'] ?? 300);
$field = $config['field'] ?? 'user_id';
$maxCount = (int) ($config['max_count'] ?? 0);
$maxAmount = (float) ($config['max_amount'] ?? 0);
$value = $this->extractField($input, $field);
if (empty($value)) return ['hit' => false];
// 金额检查
if ($maxAmount > 0) {
$amount = (float) ($input['amount'] ?? 0);
if ($amount > $maxAmount) {
return ['hit' => true, 'detail' => "金额 {$amount} > {$maxAmount}"];
}
}
// 次数检查(Redis 滑动窗口)
if ($maxCount > 0) {
$key = "risk:counter:{$field}:{$value}";
$count = (int) $this->redis->get($key) ?: 0;
if ($count >= $maxCount) {
return ['hit' => true, 'detail' => "{$field}={$value} 在 {$window}s 内 {$count} 次 >= {$maxCount}"];
}
}
return ['hit' => false];
}
/**
* 模式规则
*/
private function evalPattern(array $config, array $input): array
{
$check = $config['check'] ?? '';
switch ($check) {
case 'device_match_inviter':
// 下单用户设备 == 推荐人设备 → 自买自返
$userDevice = $input['device_id'] ?? '';
$inviterDevice = $input['inviter_device_id'] ?? '';
if ($userDevice && $userDevice === $inviterDevice) {
return ['hit' => true, 'detail' => '下单人与推荐人同设备'];
}
return ['hit' => false];
case 'login_geo_jump':
// 异地登录判断
$lastLoginIp = $input['last_login_ip'] ?? '';
$currentIp = $input['ip'] ?? '';
if ($lastLoginIp && $currentIp) {
$distance = $this->estimateDistance($lastLoginIp, $currentIp);
$maxKm = (int) ($config['max_distance_km'] ?? 1000);
if ($distance > $maxKm) {
return ['hit' => true, 'detail' => "登录地距离 {$distance}km > {$maxKm}km"];
}
}
return ['hit' => false];
case 'min_interval':
// 请求间隔
$key = "risk:last_request:user:" . ($input['user_id'] ?? 0);
$last = (int) $this->redis->get($key);
$now = time() * 1000;
$minInterval = (int) ($config['min_interval_ms'] ?? 100);
if ($last > 0 && ($now - $last) < $minInterval) {
return ['hit' => true, 'detail' => "间隔 " . ($now - $last) . "ms < {$minInterval}ms"];
}
$this->redis->setex($key, 60, (string) $now);
return ['hit' => false];
}
return ['hit' => false];
}
private function extractField(array $input, string $field): string
{
return (string) ($input[$field] ?? '');
}
/**
* 更新计数器(业务调用成功时执行)
*/
public function incrementCounter(string $scene, array $input): void
{
$rules = $this->loadRules($scene, (int) ($input['city_id'] ?? 1));
foreach ($rules as $rule) {
if ($rule['rule_type'] !== 'threshold') continue;
$config = is_string($rule['rule_config'])
? json_decode($rule['rule_config'], true)
: $rule['rule_config'];
if (empty($config['field']) || empty($config['window_seconds'])) continue;
$field = $config['field'];
$window = (int) $config['window_seconds'];
$value = $this->extractField($input, $field);
if (empty($value)) continue;
$key = "risk:counter:{$field}:{$value}";
$this->redis->incr($key);
$this->redis->expire($key, $window);
}
}
/**
* 粗略估算两 IP 距离(简化:用随机数模拟,实际集成 IP 库)
*/
private function estimateDistance(string $ip1, string $ip2): int
{
// 实际应使用 IP 归属地库(如 maxmind)
// 简化:不同 IP 段视为远距离
$seg1 = substr($ip1, 0, strrpos($ip1, '.'));
$seg2 = substr($ip2, 0, strrpos($ip2, '.'));
if ($seg1 === $seg2) return 10;
return 1500; // 简化返回固定值
}
}
4.5 决策服务(核心)
services/risk/app/Service/DecisionService.php
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\RiskEvent;
use App\Model\RiskScoreConfig;
use Goat\Common\Utils\SnowflakeId;
use Hyperf\Di\Annotation\Inject;
use Psr\Log\LoggerInterface;
class DecisionService
{
#[Inject]
private ListService $listService;
#[Inject]
private RuleEngine $ruleEngine;
#[Inject]
private LoggerInterface $logger;
/**
* 主决策入口
*/
public function decide(string $scene, array $input): array
{
$eventId = 'rsk_' . SnowflakeId::next();
$input['event_id'] = $eventId;
$startTime = microtime(true);
// 1. 名单检查(最高优先级)
$listCheck = $this->listService->check($input, $scene);
if ($listCheck['hit']) {
$decision = $listCheck['kind'] === 'white' ? 'pass' : 'reject';
$reason = $listCheck['kind'] === 'white'
? '白名单通过'
: "黑名单拦截({$listCheck['list_type']}={$listCheck['value']}):{$listCheck['reason']}";
$result = [
'event_id' => $eventId,
'decision' => $decision,
'score' => $decision === 'reject' ? 100 : 0,
'hit_rules' => [],
'reason' => $reason,
'list_hit' => $listCheck,
'cost_ms' => round((microtime(true) - $startTime) * 1000, 2),
];
$this->saveEvent($scene, $input, $result);
return $result;
}
// 2. 规则引擎
$evalResult = $this->ruleEngine->evaluate($scene, $input);
$score = $evalResult['score'];
$hitRules = $evalResult['hit_rules'];
// 3. 根据分数决定决策
$decision = $this->mapScoreToDecision($scene, $score);
$result = [
'event_id' => $eventId,
'decision' => $decision,
'score' => $score,
'hit_rules' => $hitRules,
'reason' => $this->buildReason($decision, $hitRules),
'list_hit' => null,
'cost_ms' => round((microtime(true) - $startTime) * 1000, 2),
];
// 4. 记录事件
$this->saveEvent($scene, $input, $result);
// 5. 命中计数(仅pass时累加,因为下一个环节会用)
if ($decision === 'pass' || $decision === 'challenge') {
$this->ruleEngine->incrementCounter($scene, $input);
}
// 6. 自动黑名单
$this->maybeAutoBlacklist($scene, $input, $result);
return $result;
}
/**
* 分数 → 决策
*/
private function mapScoreToDecision(string $scene, int $score): string
{
$config = RiskScoreConfig::where('scene', $scene)->first();
if (!$config) {
$config = RiskScoreConfig::where('scene', '*')->first();
}
$passMax = $config->pass_max ?? (int) env('RISK_DEFAULT_PASS_MAX', 30);
$challengeMax = $config->challenge_max ?? (int) env('RISK_DEFAULT_CHALLENGE_MAX', 60);
$reviewMax = $config->review_max ?? (int) env('RISK_DEFAULT_REVIEW_MAX', 85);
if ($score <= $passMax) return 'pass';
if ($score <= $challengeMax) return 'challenge';
if ($score <= $reviewMax) return 'review';
return 'reject';
}
private function buildReason(string $decision, array $hitRules): string
{
if (empty($hitRules)) {
return $decision === 'pass' ? '正常通过' : '无具体命中';
}
$codes = array_column($hitRules, 'rule_name');
return implode(',', $codes);
}
private function saveEvent(string $scene, array $input, array $result): void
{
try {
RiskEvent::create([
'event_id' => $result['event_id'],
'scene' => $scene,
'user_id' => (int) ($input['user_id'] ?? 0),
'ip' => (string) ($input['ip'] ?? ''),
'device_id' => (string) ($input['device_id'] ?? ''),
'phone' => (string) ($input['phone'] ?? ''),
'city_id' => (int) ($input['city_id'] ?? 1),
'biz_type' => (string) ($input['biz_type'] ?? ''),
'biz_id' => (string) ($input['biz_id'] ?? ''),
'amount' => (float) ($input['amount'] ?? 0),
'context' => $input['context'] ?? null,
'score' => $result['score'],
'decision' => $result['decision'],
'hit_rules' => $result['hit_rules'],
]);
} catch (\Throwable $e) {
$this->logger->error('[Risk] 事件保存失败', ['error' => $e->getMessage()]);
}
}
/**
* 自动拉黑
*/
private function maybeAutoBlacklist(string $scene, array $input, array $result): void
{
if (($result['decision'] ?? '') !== 'reject') return;
if (!env('RISK_AUTO_BLACKLIST_ENABLED', true)) return;
$userId = (int) ($input['user_id'] ?? 0);
$ip = (string) ($input['ip'] ?? '');
$deviceId = (string) ($input['device_id'] ?? '');
// 查同用户 reject 次数
if ($userId > 0) {
$count = RiskEvent::where('user_id', $userId)
->where('decision', 'reject')
->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-7 days')))
->count();
if ($count >= 3) {
$this->listService->addToBlacklist(
'user',
(string) $userId,
"自动拉黑:7天内 reject {$count} 次",
'auto',
date('Y-m-d H:i:s', strtotime('+30 days'))
);
$this->logger->warning('[Risk] 自动拉黑用户', ['user_id' => $userId, 'count' => $count]);
}
}
// IP
if (!empty($ip)) {
$count = RiskEvent::where('ip', $ip)
->where('decision', 'reject')
->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-24 hours')))
->count();
if ($count >= 10) {
$this->listService->addToBlacklist(
'ip',
$ip,
"自动拉黑:24小时内 reject {$count} 次",
'auto',
date('Y-m-d H:i:s', strtotime('+1 day'))
);
}
}
// 设备
if (!empty($deviceId)) {
$count = RiskEvent::where('device_id', $deviceId)
->where('decision', 'reject')
->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-24 hours')))
->count();
if ($count >= 5) {
$this->listService->addToBlacklist(
'device',
$deviceId,
"自动拉黑:24小时内 reject {$count} 次",
'auto',
date('Y-m-d H:i:s', strtotime('+7 days'))
);
}
}
}
/**
* 回写最终结果(用于规则效果分析)
*/
public function updateFinalResult(string $eventId, string $finalResult): void
{
RiskEvent::where('event_id', $eventId)->update([
'final_result' => $finalResult,
'final_result_at' => date('Y-m-d H:i:s'),
]);
}
}
4.6 RPC 接口(供业务服务调用)
services/risk/app/JsonRpc/RiskServiceInterface.php
<?php
declare(strict_types=1);
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
#[RpcService(name: "RiskService", protocol: "jsonrpc-http", server: "jsonrpc")]
interface RiskServiceInterface
{
public function decide(string $scene, array $input): array;
public function updateFinalResult(string $eventId, string $finalResult): bool;
}
services/risk/app/JsonRpc/RiskService.php
<?php
declare(strict_types=1);
namespace App\JsonRpc;
use App\Service\DecisionService;
use Hyperf\RpcServer\Annotation\RpcService;
#[RpcService(name: "RiskService", protocol: "jsonrpc-http", server: "jsonrpc")]
class RiskService implements RiskServiceInterface
{
public function __construct(private readonly DecisionService $service) {}
public function decide(string $scene, array $input): array
{
return $this->service->decide($scene, $input);
}
public function updateFinalResult(string $eventId, string $finalResult): bool
{
$this->service->updateFinalResult($eventId, $finalResult);
return true;
}
}
4.7 HTTP 控制器
services/risk/app/Controller/RiskController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Service\DecisionService;
use App\Service\ListService;
use Goat\Common\Response\ApiResponse;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
#[Controller(prefix: '/api/risk')]
class RiskController
{
#[Inject]
private DecisionService $decisionService;
#[Inject]
private ListService $listService;
/**
* 风控决策(HTTP,供小程序直接调用)
*/
#[PostMapping(path: 'decide')]
public function decide()
{
$scene = (string) $this->request->input('scene', '');
$input = (array) $this->request->input('input', []);
if (empty($scene)) {
return ApiResponse::error(100, '缺少 scene');
}
// 补充上下文
$input['user_id'] = $input['user_id'] ?? ($this->request->getAttribute('user_id') ?? 0);
$input['ip'] = $input['ip'] ?? ($this->request->getServerParams()['remote_addr'] ?? '');
$input['device_id'] = $input['device_id'] ?? $this->request->getHeaderLine('X-Device-Id');
$result = $this->decisionService->decide($scene, $input);
return ApiResponse::success($result);
}
/**
* 查询决策结果(供业务侧查询)
*/
#[GetMapping(path: 'event')]
public function getEvent()
{
$eventId = (string) $this->request->input('event_id', '');
$event = \App\Model\RiskEvent::where('event_id', $eventId)->first();
return ApiResponse::success($event ? $event->toArray() : []);
}
}
services/risk/app/Controller/AdminRiskController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Model\RiskBlacklist;
use App\Model\RiskEvent;
use App\Model\RiskRule;
use App\Model\RiskWhitelist;
use App\Service\ListService;
use Goat\Common\Response\ApiResponse;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
#[Controller(prefix: '/api/risk/admin')]
class AdminRiskController
{
#[Inject]
private ListService $listService;
// ========== 规则管理 ==========
#[GetMapping(path: 'rules')]
public function rules()
{
$scene = (string) $this->request->input('scene', '');
$query = RiskRule::query();
if ($scene) $query->where('scene', $scene);
return ApiResponse::success($query->orderBy('priority')->get()->toArray());
}
#[PostMapping(path: 'rule/update')]
public function ruleUpdate()
{
$id = (int) $this->request->input('id', 0);
$rule = RiskRule::find($id);
if (!$rule) return ApiResponse::error(404, '规则不存在');
$allowed = ['rule_name', 'rule_config', 'score', 'decision', 'status', 'priority', 'description', 'city_scope'];
foreach ($allowed as $field) {
if (array_key_exists($field, $this->request->all())) {
$rule->{$field} = $this->request->input($field);
}
}
$rule->save();
return ApiResponse::success(null, '更新成功');
}
// ========== 黑名单管理 ==========
#[GetMapping(path: 'blacklist')]
public function blacklist()
{
$type = (string) $this->request->input('list_type', '');
$query = RiskBlacklist::where('status', 1);
if ($type) $query->where('list_type', $type);
return ApiResponse::success($query->orderByDesc('id')->limit(200)->get()->toArray());
}
#[PostMapping(path: 'blacklist/add')]
public function addBlacklist()
{
$type = (string) $this->request->input('list_type', '');
$value = (string) $this->request->input('list_value', '');
$reason = (string) $this->request->input('reason', '');
$expireAt = $this->request->input('expire_at');
$operatorId = (int) $this->request->getAttribute('admin_id', 0);
if (empty($type) || empty($value)) {
return ApiResponse::error(100, '参数错误');
}
$this->listService->addToBlacklist($type, $value, $reason, 'manual', $expireAt, $operatorId);
return ApiResponse::success(null, '添加成功');
}
#[PostMapping(path: 'blacklist/remove')]
public function removeBlacklist()
{
$id = (int) $this->request->input('id', 0);
$record = RiskBlacklist::find($id);
if (!$record) return ApiResponse::error(404, '记录不存在');
$this->listService->removeFromBlacklist($record->list_type, $record->list_value);
return ApiResponse::success(null, '已移除');
}
// ========== 白名单管理 ==========
#[GetMapping(path: 'whitelist')]
public function whitelist()
{
return ApiResponse::success(RiskWhitelist::where('status', 1)->get()->toArray());
}
#[PostMapping(path: 'whitelist/add')]
public function addWhitelist()
{
$type = (string) $this->request->input('list_type', '');
$value = (string) $this->request->input('list_value', '');
$reason = (string) $this->request->input('reason', '');
$scope = (string) $this->request->input('scope', 'all');
$operatorId = (int) $this->request->getAttribute('admin_id', 0);
if (empty($type) || empty($value)) return ApiResponse::error(100, '参数错误');
RiskWhitelist::updateOrCreate(
['list_type' => $type, 'list_value' => $value],
['reason' => $reason, 'scope' => $scope, 'operator_id' => $operatorId, 'status' => 1]
);
return ApiResponse::success(null, '添加成功');
}
// ========== 事件查询 ==========
#[GetMapping(path: 'events')]
public function events()
{
$scene = (string) $this->request->input('scene', '');
$decision = (string) $this->request->input('decision', '');
$userId = (int) $this->request->input('user_id', 0);
$page = (int) $this->request->input('page', 1);
$pageSize = (int) $this->request->input('page_size', 20);
$query = RiskEvent::query();
if ($scene) $query->where('scene', $scene);
if ($decision) $query->where('decision', $decision);
if ($userId) $query->where('user_id', $userId);
$paginator = $query->orderByDesc('id')->paginate($pageSize, ['*'], 'page', $page);
return ApiResponse::success([
'list' => $paginator->items(),
'total' => $paginator->total(),
]);
}
}
4.8 业务服务集成(关键)
4.8.1 订单服务:下单前风控
services/order/app/Service/SubscriptionService.php 增加:
#[RpcClient(name: 'RiskService')]
private \App\JsonRpc\RiskServiceInterface $riskClient;
public function createSubscription(int $userId, int $planId, int $storeId, int $addressId, string $couponCode = '', ?int $cityId = null, array $riskContext = []): array
{
// ========== 风控前置 ==========
$riskInput = [
'user_id' => $userId,
'ip' => $riskContext['ip'] ?? '',
'device_id' => $riskContext['device_id'] ?? '',
'city_id' => $cityId ?? 1,
'biz_type' => 'subscription',
'amount' => $plan['price'] ?? 0,
'address_id' => $addressId,
'context' => $riskContext,
];
$riskResult = \Goat\Common\Rpc\RpcClientFactory::safeCall(
fn() => $this->riskClient->decide('order_create', $riskInput),
['decision' => 'pass', 'event_id' => '', 'score' => 0]
);
if ($riskResult['decision'] === 'reject') {
throw new BusinessException('操作受限:' . ($riskResult['reason'] ?? '触发风控'), ErrorCode::FORBIDDEN);
}
if ($riskResult['decision'] === 'review') {
// 转人工审核(不阻断,标记)
$this->logger->warning('[Order] 订单进入风控审核', [
'user_id' => $userId,
'event_id' => $riskResult['event_id'],
]);
// 可考虑降级:先创建订单,但状态标记为 'risk_review'
}
if ($riskResult['decision'] === 'challenge') {
// 需要验证码,由小程序端处理
throw new BusinessException('需要验证:' . ($riskResult['reason'] ?? ''), ErrorCode::RISK_CHALLENGE);
}
// ========== 原有逻辑 ==========
// ...
// 订单创建成功后,回写风控最终结果
if (!empty($riskResult['event_id'])) {
go(function () use ($riskResult) {
\Goat\Common\Rpc\RpcClientFactory::safeCall(
fn() => $this->riskClient->updateFinalResult($riskResult['event_id'], 'created'),
false
);
});
}
}
4.8.2 秒杀:抢购前风控
services/seckill/app/Service/SeckillOrderService.php 增加:
#[RpcClient(name: 'RiskService')]
private \App\JsonRpc\RiskServiceInterface $riskClient;
public function createOrder(int $userId, int $seckillProductId, int $addressId, string $deviceId = '', string $ip = ''): array
{
// 风控前置
$risk = \Goat\Common\Rpc\RpcClientFactory::safeCall(
fn() => $this->riskClient->decide('seckill', [
'user_id' => $userId,
'device_id' => $deviceId,
'ip' => $ip,
'biz_type' => 'seckill',
]),
['decision' => 'pass']
);
if (in_array($risk['decision'], ['reject', 'review'])) {
throw new BusinessException('抢购繁忙,请稍后再试', ErrorCode::FORBIDDEN);
}
if ($risk['decision'] === 'challenge') {
throw new BusinessException('请完成验证后重试', ErrorCode::RISK_CHALLENGE);
}
// 原有逻辑
// ...
}
4.8.3 佣金:发放前风控
services/distribution/app/Service/CommissionService.php 增加:
#[RpcClient(name: 'RiskService')]
private \App\JsonRpc\RiskServiceInterface $riskClient;
public function distribute(array $data): void
{
// 风控检查:是否自买自返
$risk = \Goat\Common\Rpc\RpcClientFactory::safeCall(
fn() => $this->riskClient->decide('commission', [
'user_id' => $data['user_id'],
'device_id' => $data['device_id'] ?? '',
'inviter_device_id' => $data['inviter_device_id'] ?? '',
'biz_type' => 'commission',
'amount' => $data['amount'] ?? 0,
]),
['decision' => 'pass']
);
if ($risk['decision'] === 'reject') {
$this->logger->warning('[Commission] 佣金被风控拦截', [
'user_id' => $data['user_id'],
'reason' => $risk['reason'],
]);
return; // 不发放
}
// 原有逻辑
// ...
}
4.8.4 提现:申请前风控
services/wallet/app/Service/WithdrawService.php 增加:
#[RpcClient(name: 'RiskService')]
private \App\JsonRpc\RiskServiceInterface $riskClient;
public function apply(int $userId, float $amount): array
{
// 风控检查
$risk = \Goat\Common\Rpc\RpcClientFactory::safeCall(
fn() => $this->riskClient->decide('withdraw', [
'user_id' => $userId,
'amount' => $amount,
'biz_type' => 'withdraw',
]),
['decision' => 'pass']
);
if (in_array($risk['decision'], ['reject', 'review'])) {
throw new BusinessException('提现申请受限:' . ($risk['reason'] ?? ''), ErrorCode::FORBIDDEN);
}
// 原有逻辑
// ...
}
4.9 网关路由
gateway-config 增加:
{
"id": "risk-api",
"priority": 95,
"predicates": { "path": "/api/risk/decide" },
"target": { "base_url": "http://risk-service:9517" },
"plugins": ["jwt-auth", "rate-limiter", "request-log"]
},
{
"id": "risk-admin",
"priority": 95,
"predicates": { "path": "/api/risk/admin/**" },
"target": { "base_url": "http://risk-service:9517" },
"plugins": ["admin-auth", "request-log"]
}
五、小程序端
5.1 风控 SDK
utils/risk.js:
const req = require('./request')
const storage = require('./storage')
class RiskSDK {
/**
* 判断是否需要挑战(验证码)
* 每个业务在关键操作前调用
*/
async check(scene, payload = {}) {
try {
const result = await req.post('/api/risk/decide', {
scene,
input: {
...payload,
device_id: this.getDeviceId(),
},
}, { showError: false })
if (!result) return { decision: 'pass' }
switch (result.decision) {
case 'reject':
wx.showModal({
title: '操作受限',
content: result.reason || '当前操作存在风险,请联系客服',
showCancel: false,
})
return result
case 'review':
wx.showToast({
title: '审核中,请稍候',
icon: 'none',
duration: 2000,
})
return result
case 'challenge':
const passed = await this.challenge(result.reason)
return { ...result, challenge_passed: passed }
default:
return result
}
} catch (e) {
// 风控失败不影响业务
return { decision: 'pass' }
}
}
/**
* 验证码挑战
*/
async challenge(reason) {
return new Promise((resolve) => {
wx.showModal({
title: '安全验证',
content: reason || '请完成验证以继续',
confirmText: '去验证',
success: async (r) => {
if (!r.confirm) {
resolve(false)
return
}
// 简化:使用图形验证码
// 生产环境建议用滑块/短信
const verified = await this.showCaptcha()
resolve(verified)
},
fail: () => resolve(false),
})
})
}
async showCaptcha() {
// 模拟:调用后端生成验证码
wx.showLoading({ title: '验证中...' })
try {
// 生产环境应调用真实验证码接口
await new Promise(resolve => setTimeout(resolve, 500))
wx.hideLoading()
wx.showToast({ title: '验证通过', icon: 'success' })
return true
} catch (e) {
wx.hideLoading()
return false
}
}
/**
* 设备 ID(持久化)
*/
getDeviceId() {
let id = storage.getDeviceId()
if (!id) {
id = 'dev_' + Date.now() + '_' + Math.random().toString(36).substr(2, 8)
storage.setDeviceId(id)
}
return id
}
}
module.exports = new RiskSDK()
utils/storage.js 增加:
const DEVICE_ID = 'device_id'
getDeviceId() {
return wx.getStorageSync(DEVICE_ID) || ''
},
setDeviceId(id) {
wx.setStorageSync(DEVICE_ID, id)
},
5.2 关键业务集成
pages/order/confirm.js 下单前
const risk = require('../../utils/risk')
async submitOrder() {
// 1. 风控检查
const riskCheck = await risk.check('order_create', {
amount: this.data.finalAmount,
address_id: this.data.selectedAddress.id,
})
if (riskCheck.decision === 'reject') {
return
}
if (riskCheck.decision === 'challenge' && !riskCheck.challenge_passed) {
wx.showToast({ title: '需要完成验证', icon: 'none' })
return
}
// 2. 正常提交
await req.post('/api/subscription/create', { ... })
}
pages/seckill/detail.js 秒杀前
const risk = require('../../utils/risk')
async onGrab() {
// 秒杀风控(高频,必须用轻量检查)
const riskCheck = await risk.check('seckill')
if (riskCheck.decision === 'reject') return
if (riskCheck.decision === 'challenge' && !riskCheck.challenge_passed) return
await req.post('/api/seckill/order', { ... })
}
六、后台管理
6.1 风控中心页 admin/src/views/risk/index.vue
<template>
<div class="risk-page">
<div class="page-header">
<h2 class="page-title">风控中心</h2>
<el-button @click="loadAll">刷新</el-button>
</div>
<el-tabs v-model="activeTab" @tab-change="loadTab">
<el-tab-pane label="风控事件" name="events" />
<el-tab-pane label="黑名单" name="blacklist" />
<el-tab-pane label="白名单" name="whitelist" />
<el-tab-pane label="规则管理" name="rules" />
</el-tabs>
<!-- 事件列表 -->
<el-card v-if="activeTab === 'events'" shadow="never">
<el-form :inline="true" style="margin-bottom: 16px">
<el-form-item label="场景">
<el-select v-model="eventQuery.scene" clearable style="width: 140px" @change="loadEvents">
<el-option label="全部" value="" />
<el-option label="下单" value="order_create" />
<el-option label="支付" value="payment" />
<el-option label="秒杀" value="seckill" />
<el-option label="提现" value="withdraw" />
</el-select>
</el-form-item>
<el-form-item label="决策">
<el-select v-model="eventQuery.decision" clearable style="width: 120px" @change="loadEvents">
<el-option label="全部" value="" />
<el-option label="通过" value="pass" />
<el-option label="挑战" value="challenge" />
<el-option label="审核" value="review" />
<el-option label="拒绝" value="reject" />
</el-select>
</el-form-item>
<el-form-item label="用户ID">
<el-input v-model="eventQuery.user_id" style="width: 120px" @keyup.enter="loadEvents" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="loadEvents">搜索</el-button>
</el-form-item>
</el-form>
<el-table :data="events" v-loading="loading" stripe>
<el-table-column prop="created_at" label="时间" width="160" />
<el-table-column prop="scene" label="场景" width="100" />
<el-table-column prop="user_id" label="用户" width="80" />
<el-table-column prop="ip" label="IP" width="130" />
<el-table-column prop="amount" label="金额" width="100">
<template #default="{ row }">¥{{ row.amount }}</template>
</el-table-column>
<el-table-column prop="score" label="风险分" width="90">
<template #default="{ row }">
<span :style="{ color: row.score > 60 ? '#FF4D4F' : (row.score > 30 ? '#FFB800' : '#52C41A') }">
{{ row.score }}
</span>
</template>
</el-table-column>
<el-table-column label="决策" width="100">
<template #default="{ row }">
<el-tag :type="decisionType(row.decision)">{{ decisionText(row.decision) }}</el-tag>
</template>
</el-table-column>
<el-table-column label="命中规则" min-width="200">
<template #default="{ row }">
<el-tag
v-for="r in row.hit_rules || []"
:key="r.rule_code"
size="small"
style="margin: 2px"
>
{{ r.rule_name }} +{{ r.score }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="140">
<template #default="{ row }">
<el-button
v-if="row.decision === 'reject'"
size="small"
type="danger"
@click="handleBlock(row)"
>拉黑</el-button>
<el-button
size="small"
@click="handleViewDetail(row)"
>详情</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<!-- 黑名单 -->
<el-card v-if="activeTab === 'blacklist'" shadow="never">
<el-form :inline="true" style="margin-bottom: 16px">
<el-form-item label="类型">
<el-select v-model="blackQuery.list_type" clearable style="width: 120px">
<el-option label="全部" value="" />
<el-option label="用户" value="user" />
<el-option label="IP" value="ip" />
<el-option label="设备" value="device" />
<el-option label="手机" value="phone" />
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="loadBlacklist">搜索</el-button>
<el-button type="success" @click="handleAddBlack">添加</el-button>
</el-form-item>
</el-form>
<el-table :data="blacklist" v-loading="loading" stripe>
<el-table-column prop="list_type" label="类型" width="100" />
<el-table-column prop="list_value" label="值" min-width="180" />
<el-table-column prop="reason" label="原因" min-width="200" />
<el-table-column prop="source" label="来源" width="100" />
<el-table-column prop="hit_count" label="命中" width="80" />
<el-table-column prop="expire_at" label="过期" width="160" />
<el-table-column label="操作" width="100">
<template #default="{ row }">
<el-button size="small" type="danger" @click="handleRemoveBlack(row)">移除</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<!-- 白名单 -->
<el-card v-if="activeTab === 'whitelist'" shadow="never">
<el-button type="success" @click="handleAddWhite" style="margin-bottom: 16px">添加白名单</el-button>
<el-table :data="whitelist" v-loading="loading" stripe>
<el-table-column prop="list_type" label="类型" width="100" />
<el-table-column prop="list_value" label="值" min-width="180" />
<el-table-column prop="scope" label="范围" width="150" />
<el-table-column prop="reason" label="原因" min-width="200" />
<el-table-column prop="expire_at" label="过期" width="160" />
</el-table>
</el-card>
<!-- 规则 -->
<el-card v-if="activeTab === 'rules'" shadow="never">
<el-table :data="rules" v-loading="loading" stripe>
<el-table-column prop="rule_code" label="编码" width="200" />
<el-table-column prop="rule_name" label="规则名" min-width="180" />
<el-table-column prop="scene" label="场景" width="120" />
<el-table-column prop="score" label="分值" width="80" />
<el-table-column label="决策" width="100">
<template #default="{ row }">
<el-tag size="small">{{ row.decision }}</el-tag>
</template>
</el-table-column>
<el-table-column label="状态" width="80">
<template #default="{ row }">
<el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleRuleToggle(row)" />
</template>
</el-table-column>
<el-table-column label="操作" width="100">
<template #default="{ row }">
<el-button size="small" @click="handleEditRule(row)">编辑</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<!-- 添加黑名单弹窗 -->
<el-dialog v-model="blackVisible" title="添加黑名单" width="500px">
<el-form label-width="100px">
<el-form-item label="类型">
<el-select v-model="blackForm.list_type">
<el-option label="用户" value="user" />
<el-option label="IP" value="ip" />
<el-option label="设备" value="device" />
<el-option label="手机" value="phone" />
</el-select>
</el-form-item>
<el-form-item label="值">
<el-input v-model="blackForm.list_value" />
</el-form-item>
<el-form-item label="原因">
<el-input v-model="blackForm.reason" type="textarea" />
</el-form-item>
<el-form-item label="过期时间">
<el-date-picker v-model="blackForm.expire_at" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="blackVisible = false">取消</el-button>
<el-button type="primary" @click="handleAddBlackSubmit">确认</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/api/request'
const activeTab = ref('events')
const loading = ref(false)
const events = ref([])
const blacklist = ref([])
const whitelist = ref([])
const rules = ref([])
const eventQuery = reactive({ scene: '', decision: '', user_id: '', page: 1, page_size: 20 })
const blackQuery = reactive({ list_type: '' })
const blackVisible = ref(false)
const blackForm = reactive({ list_type: 'user', list_value: '', reason: '', expire_at: null })
function decisionText(d) {
return { pass: '通过', challenge: '挑战', review: '审核', reject: '拒绝' }[d] || d
}
function decisionType(d) {
return { pass: 'success', challenge: 'warning', review: 'warning', reject: 'danger' }[d] || 'info'
}
async function loadEvents() {
loading.value = true
try {
const data = await request.get('/api/risk/admin/events', { params: eventQuery })
events.value = data.list || []
} catch (e) {
console.error(e)
} finally {
loading.value = false
}
}
async function loadBlacklist() {
loading.value = true
try {
blacklist.value = await request.get('/api/risk/admin/blacklist', { params: blackQuery }) || []
} catch (e) {} finally {
loading.value = false
}
}
async function loadWhitelist() {
loading.value = true
try {
whitelist.value = await request.get('/api/risk/admin/whitelist') || []
} catch (e) {} finally {
loading.value = false
}
}
async function loadRules() {
loading.value = true
try {
rules.value = await request.get('/api/risk/admin/rules') || []
} catch (e) {} finally {
loading.value = false
}
}
function loadTab() {
if (activeTab.value === 'events') loadEvents()
else if (activeTab.value === 'blacklist') loadBlacklist()
else if (activeTab.value === 'whitelist') loadWhitelist()
else if (activeTab.value === 'rules') loadRules()
}
function loadAll() {
loadTab()
}
function handleBlock(row) {
blackForm.list_type = 'user'
blackForm.list_value = String(row.user_id)
blackForm.reason = `风控事件 ${row.event_id} 拒绝`
blackForm.expire_at = null
blackVisible.value = true
}
function handleAddBlack() {
Object.assign(blackForm, { list_type: 'user', list_value: '', reason: '', expire_at: null })
blackVisible.value = true
}
async function handleAddBlackSubmit() {
try {
await request.post('/api/risk/admin/blacklist/add', blackForm)
ElMessage.success('添加成功')
blackVisible.value = false
loadBlacklist()
} catch (e) {}
}
async function handleRemoveBlack(row) {
try {
await ElMessageBox.confirm('确认移除?', '提示', { type: 'warning' })
await request.post('/api/risk/admin/blacklist/remove', { id: row.id })
ElMessage.success('已移除')
loadBlacklist()
} catch (e) {}
}
function handleAddWhite() {
ElMessage.info('请通过 API 或数据库添加')
}
function handleEditRule(row) {
ElMessage.info('规则编辑待实现')
}
async function handleRuleToggle(row) {
try {
await request.post('/api/risk/admin/rule/update', { id: row.id, status: row.status })
ElMessage.success('更新成功')
} catch (e) {
row.status = row.status === 1 ? 0 : 1
}
}
function handleViewDetail(row) {
ElMessage.info(JSON.stringify(row.hit_rules, null, 2))
}
onMounted(() => loadTab())
</script>
<style scoped>
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-title { font-size: 20px; color: #333; margin: 0; }
</style>
6.2 后台路由和菜单
admin/src/router/index.js:
{
path: 'risks',
name: 'Risks',
component: () => import('@/views/risk/index.vue'),
meta: { title: '风控中心', icon: 'Warning' },
}
Sidebar.vue:
{ path: '/risks', title: '风控中心', icon: 'Warning' },
七、大屏联动
7.1 大屏增加风控面板
screen/index.html 底部增加:
<div class="chart-card">
<div class="title">实时风控</div>
<div class="risk-panel">
<div class="risk-stat">
<div class="value">{{ riskStats.today_events || 0 }}</div>
<div class="label">今日风控</div>
</div>
<div class="risk-stat">
<div class="value" style="color:#FF4D4F">{{ riskStats.today_reject || 0 }}</div>
<div class="label">今日拦截</div>
</div>
<div class="risk-stat">
<div class="value" style="color:#FFB800">{{ riskStats.today_review || 0 }}</div>
<div class="label">待审核</div>
</div>
</div>
</div>
对应 JS 和 CSS:
const riskStats = ref({ today_events: 0, today_reject: 0, today_review: 0 });
async function loadRiskStats() {
try {
const data = await api('/api/screen/risk-stats');
riskStats.value = data || {};
} catch (e) {}
}
.risk-panel {
display: flex;
justify-content: space-around;
align-items: center;
height: calc(100% - 40px);
}
.risk-stat {
text-align: center;
}
.risk-stat .value {
font-size: 40px;
font-weight: bold;
color: #3DBE8B;
font-family: 'Courier New', monospace;
}
.risk-stat .label {
font-size: 13px;
color: rgba(255,255,255,0.6);
margin-top: 8px;
}
7.2 大屏后端接口
ScreenController.php 增加:
#[GetMapping(path: 'risk-stats')]
public function riskStats()
{
$today = date('Y-m-d');
$cityId = (int) $this->request->getHeaderLine('X-City-Id');
$query = Db::table('risk_db.risk_events')
->where('created_at', '>=', $today . ' 00:00:00');
if ($cityId > 0) {
$query->where('city_id', $cityId);
}
return ApiResponse::success([
'today_events' => (clone $query)->count(),
'today_reject' => (clone $query)->where('decision', 'reject')->count(),
'today_review' => (clone $query)->where('decision', 'review')->count(),
]);
}
八、K8s 部署
8.1 deploy/k8s/deployment/risk.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: risk-service
namespace: goat-milk
labels:
app: risk-service
spec:
replicas: 3
selector:
matchLabels:
app: risk-service
template:
metadata:
labels:
app: risk-service
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "9517"
spec:
containers:
- name: risk
image: goat/risk:v2.1.0
ports:
- containerPort: 9517
envFrom:
- configMapRef:
name: goat-common-config
- secretRef:
name: goat-common-secret
env:
- name: APP_NAME
value: risk-service
resources:
requests:
memory: "256Mi"
cpu: "200m"
limits:
memory: "1Gi"
cpu: "2"
livenessProbe:
httpGet:
path: /health
port: 9517
readinessProbe:
httpGet:
path: /health
port: 9517
---
apiVersion: v1
kind: Service
metadata:
name: risk-service
namespace: goat-milk
spec:
selector:
app: risk-service
ports:
- port: 9517
targetPort: 9517
注意:风控服务实例数 = 3(高可用),因为所有业务都依赖它,不能挂。
九、验证脚本 scripts/test/regression-risk.sh
#!/bin/bash
# 风控专项回归
set -e
GATEWAY="http://localhost:9700"
PASS=0
FAIL=0
check() {
if [ "$2" = "$3" ]; then
echo "✓ $1"
PASS=$((PASS+1))
else
echo "✗ $1 (期望=$3, 实际=$2)"
FAIL=$((FAIL+1))
fi
}
echo "========== 风控系统回归 =========="
echo ""
# 1. 登录
TOKEN=$(curl -s -X POST "$GATEWAY/api/auth/login" \
-H "Content-Type: application/json" \
-d '{"code":"risk_test_user"}' | jq -r '.data.token')
# 2. 正常决策
NORMAL=$(curl -s -X POST "$GATEWAY/api/risk/decide" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-H "X-Device-Id: test_device_001" \
-d '{"scene":"order_create","input":{"amount":99,"user_id":1}}')
check "正常决策" "$(echo "$NORMAL" | jq -r '.data.decision')" "pass"
# 3. 黑名单拦截(添加后测试)
ADMIN_TOKEN=$(curl -s -X POST "$GATEWAY/api/admin/auth/login" \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin123456"}' | jq -r '.data.token')
curl -s -X POST "$GATEWAY/api/risk/admin/blacklist/add" \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{"list_type":"ip","list_value":"1.2.3.4","reason":"测试拦截"}' > /dev/null
sleep 1
BLOCKED=$(curl -s -X POST "$GATEWAY/api/risk/decide" \
-H "Content-Type: application/json" \
-d '{"scene":"order_create","input":{"ip":"1.2.3.4","user_id":1}}')
check "黑名单拦截" "$(echo "$BLOCKED" | jq -r '.data.decision')" "reject"
# 4. 频率规则(模拟 5 次下单)
for i in {1..5}; do
curl -s -X POST "$GATEWAY/api/risk/decide" \
-H "Content-Type: application/json" \
-H "X-Device-Id: test_freq_device" \
-d '{"scene":"order_create","input":{"user_id":999}}' > /dev/null
done
FREQ=$(curl -s -X POST "$GATEWAY/api/risk/decide" \
-H "Content-Type: application/json" \
-d '{"scene":"order_create","input":{"user_id":999}}')
SCORE=$(echo "$FREQ" | jq -r '.data.score')
check "频率规则生效(分数>0)" "$([ "$SCORE" -gt 0 ] && echo "yes" || echo "no")" "yes"
# 5. 事件查询
EVENTS=$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
"$GATEWAY/api/risk/admin/events?page=1&page_size=10")
check "事件列表" "$(echo "$EVENTS" | jq -r '.code')" "0"
echo ""
echo "========== 结果 =========="
echo "通过: $PASS"
echo "失败: $FAIL"
echo ""
echo "【手动测试】"
echo "1. 后台风控中心 → 查看事件"
echo "2. 添加黑名单 → 测试拦截"
echo "3. 规则开关 → 验证生效"
echo "4. 大屏查看风控面板"
[ $FAIL -gt 0 ] && exit 1
十、Day 28 交付清单
验收清单:
- 风控数据库创建成功
- 8 条初始规则就位
- 风控服务启动并注册 Consul
- 网关 risk 路由生效
- 正常请求通过(pass)
- 黑名单拦截生效(reject)
- 白名单放行生效(pass)
- 频率规则触发(challenge)
- 下单前风控集成
- 秒杀前风控集成
- 佣金前风控集成
- 提现前风控集成
- 自动拉黑生效
- 后台风控中心可查看/管理
- 大屏风控面板显示
- 专项回归通过
十一、Day 28 关键经验
11.1 风控必须"业务无感"
风控不能成为业务瓶颈:
// ❌ 错误:风控失败阻塞业务
$risk = $this->riskClient->decide(...); // 网络抖动 → 下单失败
// ✅ 正确:风控失败降级放行
$risk = RpcClientFactory::safeCall(
fn() => $this->riskClient->decide(...),
['decision' => 'pass'] // 降级
);
原则:风控失败不阻断交易,宁可放过 1 个坏用户,不能误伤 100 个正常用户。
11.2 评分制 > 单规则 veto
单规则 veto(一票否决)的问题:
- 规则太严 → 正常用户被拦
- 规则太松 → 起不到拦截作用
- 规则调整 → 频繁误判
评分制的优势:
- 多个小规则叠加成高分
- 单个规则误判影响小
- 全局阈值可调
11.3 名单是"最后一公里"
规则引擎算分,名单做最后决定:
规则命中 → 分数 45 → review
命中黑名单 → 直接 reject(无视分数)
命中白名单 → 直接 pass(无视分数)
名单优先级最高,因为它是"人工确权"的。
11.4 风控的"三层防护"
| 层级 | 时机 | 作用 |
|---|---|---|
| 前置拦截 | 请求入口 | 快速拒绝明显异常 |
| 实时决策 | 业务动作 | 评分+名单判断 |
| 事后审计 | 定时任务 | 人工复核+规则优化 |
Day 28 实现前两层,事后审计需要人工 + 数据分析。
11.5 规则不能"一成不变"
规则需要持续调优:
- 新增欺诈手法 → 新增规则
- 误判太多 → 调整阈值/分数
- 业务变化 → 调整适用场景
关键指标:
- 误判率(false positive)
- 漏判率(false negative)
- 拦截金额 / 总金额
每周看数据,每月调规则。
11.6 风控是"长期战"
风控的本质是"猫鼠游戏":
- 你加规则 → 黑产调整手法
- 你加验证码 → 黑产用打码平台
- 你加设备指纹 → 黑产伪造设备
所以:
- 规则要分层(简单规则 + 复杂规则 + 人工)
- 决策要留痕(用于持续优化)
- 团队要专职(不能兼职)
11.7 别忘了"用户体验"
风控严格不等于粗暴拒绝:
| 决策 | 用户感受 |
|---|---|
reject(直接拒) | 😡 愤怒,可能投诉 |
review(审核中) | 😕 不耐烦,但能理解 |
challenge(验证码) | 🤔 可接受,1 分钟完成 |
pass(无感) | 😊 正常 |
能用 challenge 解决的,不要 review;能用 review 解决的,不要 reject。
十二、Day 29 预告
Day 29 可以继续:
| 方向 | 优先级 | 说明 |
|---|---|---|
| 开放平台 | 高 | 第三方接入、API 网关 |
| 国际化 | 中 | 多语言、多币种 |
| gRPC 改造 | 中 | 内部通信性能 |
| 数据库分库分表 | 中 | 数据量增长 |
| CI/CD 完善 | 中 | GitOps、灰度发布 |
推荐 Day 29 做开放平台,因为:
- 业务稳定后,对外赋能是趋势
- 吸引 B 端客户(企业采购、异业合作)
- 技术挑战大(OAuth2、签名、限流、审计)
- 是从"卖货"到"卖能力"的升级
十三、结语
Day 28 完成的是**从"能卖"到"防得住"**的护城河。
Day 15:能收钱
Day 16-26:能赚钱
Day 27:能分钱
Day 28:能守住钱
风控的价值不在"拦截了多少",在"放过了多少正常用户的同时,没有放过坏用户"。
- 拦截太严 → 用户流失
- 拦截太松 → 资金流失
- 拦截合适 → 业务稳健
风控是商业模式的"刹车系统":
- 没有刹车,跑得越快死得越快
- 有刹车,才能跑得远
Day 28 完结。
v2.1.0 让鲜羊奶业务"能守住底线、能持续增长"。
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)