功能概述

本系统基于ThinkPHP 6.x开发,实现微信生态下的多店铺电商平台与分销体系整合。系统特点包括:

  1. 多店铺独立运营管理

  2. 微信支付与分账功能

  3. 三级分销体系

  4. 会员积分与等级系统

  5. 商品库存与物流管理

  6. 数据统计与分析

核心代码实现

1. 配置文件 (config/wechat_shop.php)

<?php
return [
    // 微信支付配置
    'payment' => [
        'app_id' => env('WECHAT_PAYMENT_APPID'),
        'mch_id' => env('WECHAT_PAYMENT_MCHID'),
        'key' => env('WECHAT_PAYMENT_KEY'),
        'cert_path' => env('WECHAT_PAYMENT_CERT_PATH'),
        'key_path' => env('WECHAT_PAYMENT_KEY_PATH'),
        'profit_sharing' => env('WECHAT_PROFIT_SHARING', false), // 是否开启分账
    ],
    
    // 店铺配置
    'shop' => [
        'max_shops' => 10, // 最大店铺数量
        'default_commission_rate' => 0.1, // 默认佣金比例
        'settlement_days' => 7, // 结算周期(天)
    ],
    
    // 分销配置
    'distribution' => [
        'levels' => 3, // 分销层级
        'rates' => [0.5, 0.3, 0.2], // 各级佣金比例
        'condition' => 'order_completed', // 佣金结算条件
        'withdraw_min' => 100, // 最低提现金额(分)
    ],
    
    // 会员配置
    'member' => [
        'levels' => [
            1 => ['name' => '普通会员', 'discount' => 1.0, 'upgrade_condition' => 0],
            2 => ['name' => '白银会员', 'discount' => 0.95, 'upgrade_condition' => 1000],
            3 => ['name' => '黄金会员', 'discount' => 0.9, 'upgrade_condition' => 5000],
            4 => ['name' => '钻石会员', 'discount' => 0.85, 'upgrade_condition' => 20000],
        ],
        'points' => [
            'register' => 100, // 注册赠送积分
            'order' => 0.1, // 订单金额兑换比例(1元=0.1积分)
        ],
    ],
    
    // 数据库表名
    'tables' => [
        'shops' => 'ws_shops',
        'goods' => 'ws_goods',
        'orders' => 'ws_orders',
        'order_items' => 'ws_order_items',
        'members' => 'ws_members',
        'distribution' => 'ws_distribution',
        'withdrawals' => 'ws_withdrawals',
    ],
];

2. 控制器代码 (app/controller/ShopController.php)

<?php
namespace app\controller;

use think\facade\Config;
use think\facade\Request;
use think\facade\Db;
use app\service\WechatShopService;
use app\service\WechatPayService;
use app\model\WsShop;
use app\model\WsOrder;

class ShopController
{
    protected $shopService;
    protected $payService;
    
    public function __construct(WechatShopService $shopService, WechatPayService $payService)
    {
        $this->shopService = $shopService;
        $this->payService = $payService;
    }
    
    /**
     * 创建店铺
     */
    public function createShop()
    {
        $data = Request::only([
            'name', 'logo', 'description', 
            'owner_id', 'contact', 'address'
        ]);
        
        try {
            $shop = $this->shopService->createShop($data);
            return json(['code' => 0, 'data' => $shop]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 添加商品
     */
    public function addGoods()
    {
        $data = Request::only([
            'shop_id', 'name', 'category_id',
            'price', 'original_price', 'stock',
            'images', 'description', 'specs'
        ]);
        
        try {
            $goods = $this->shopService->addGoods($data);
            return json(['code' => 0, 'data' => $goods]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 创建订单
     */
    public function createOrder()
    {
        $data = Request::only([
            'shop_id', 'member_id', 'items',
            'address_id', 'remark', 'coupon_id'
        ]);
        
        try {
            $order = $this->shopService->createOrder($data);
            return json(['code' => 0, 'data' => $order]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 微信支付下单
     */
    public function wechatPay()
    {
        $orderId = Request::param('order_id');
        $openid = Request::param('openid');
        
        try {
            $order = WsOrder::find($orderId);
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            
            $payment = $this->payService->createPayment($order, $openid);
            return json(['code' => 0, 'data' => $payment]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 支付回调通知
     */
    public function payNotify()
    {
        try {
            $result = $this->payService->handleNotify();
            
            // 处理订单支付成功逻辑
            $this->shopService->processPaidOrder($result['out_trade_no']);
            
            return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } catch (\Exception $e) {
            return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA['.$e->getMessage().']]></return_msg></xml>';
        }
    }
    
    /**
     * 申请分销
     */
    public function applyDistribution()
    {
        $memberId = Request::param('member_id');
        
        try {
            $result = $this->shopService->applyDistribution($memberId);
            return json(['code' => 0, 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 获取分销订单
     */
    public function distributionOrders()
    {
        $memberId = Request::param('member_id');
        $status = Request::param('status', 'pending');
        
        try {
            $orders = $this->shopService->getDistributionOrders($memberId, $status);
            return json(['code' => 0, 'data' => $orders]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 申请提现
     */
    public function applyWithdrawal()
    {
        $data = Request::only(['member_id', 'amount', 'bank_info']);
        
        try {
            $result = $this->shopService->applyWithdrawal($data);
            return json(['code' => 0, 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 获取店铺统计
     */
    public function shopStats()
    {
        $shopId = Request::param('shop_id');
        $params = Request::get();
        
        try {
            $stats = $this->shopService->getShopStats($shopId, $params);
            return json(['code' => 0, 'data' => $stats]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
}

3. 服务层代码 (app/service/WechatShopService.php)

<?php
namespace app\service;

use think\facade\Config;
use think\facade\Db;
use app\model\WsShop;
use app\model\WsGoods;
use app\model\WsOrder;
use app\model\WsMember;
use app\model\WsDistribution;
use app\model\WsWithdrawal;

class WechatShopService
{
    /**
     * 创建店铺
     */
    public function createShop($data)
    {
        Db::startTrans();
        try {
            // 检查用户是否已有店铺
            $exist = WsShop::where('owner_id', $data['owner_id'])->count();
            if ($exist >= Config::get('wechat_shop.shop.max_shops')) {
                throw new \Exception('您已达到最大店铺创建数量');
            }
            
            // 创建店铺
            $shop = WsShop::create([
                'name' => $data['name'],
                'logo' => $data['logo'],
                'description' => $data['description'],
                'owner_id' => $data['owner_id'],
                'contact' => $data['contact'],
                'address' => $data['address'],
                'status' => 'pending',
                'create_time' => time(),
            ]);
            
            // 初始化店铺设置
            Db::name('ws_shop_settings')->insert([
                'shop_id' => $shop->id,
                'commission_rate' => Config::get('wechat_shop.shop.default_commission_rate'),
                'settlement_days' => Config::get('wechat_shop.shop.settlement_days'),
            ]);
            
            Db::commit();
            return $shop;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
    
    /**
     * 添加商品
     */
    public function addGoods($data)
    {
        Db::startTrans();
        try {
            // 验证店铺
            $shop = WsShop::find($data['shop_id']);
            if (!$shop || $shop->status != 'normal') {
                throw new \Exception('店铺不存在或未通过审核');
            }
            
            // 创建商品
            $goods = WsGoods::create([
                'shop_id' => $data['shop_id'],
                'name' => $data['name'],
                'category_id' => $data['category_id'],
                'price' => $data['price'],
                'original_price' => $data['original_price'],
                'stock' => $data['stock'],
                'images' => is_array($data['images']) ? json_encode($data['images']) : $data['images'],
                'description' => $data['description'],
                'specs' => is_array($data['specs']) ? json_encode($data['specs']) : $data['specs'],
                'status' => 'on',
                'create_time' => time(),
            ]);
            
            // 处理SKU
            if (!empty($data['skus'])) {
                $skuData = [];
                foreach ($data['skus'] as $sku) {
                    $skuData[] = [
                        'goods_id' => $goods->id,
                        'specs' => json_encode($sku['specs']),
                        'price' => $sku['price'],
                        'original_price' => $sku['original_price'],
                        'stock' => $sku['stock'],
                        'code' => $sku['code'] ?? '',
                    ];
                }
                Db::name('ws_goods_skus')->insertAll($skuData);
            }
            
            Db::commit();
            return $goods;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
    
    /**
     * 创建订单
     */
    public function createOrder($data)
    {
        Db::startTrans();
        try {
            // 验证店铺
            $shop = WsShop::find($data['shop_id']);
            if (!$shop || $shop->status != 'normal') {
                throw new \Exception('店铺不存在或未通过审核');
            }
            
            // 验证会员
            $member = WsMember::find($data['member_id']);
            if (!$member) {
                throw new \Exception('会员不存在');
            }
            
            // 验证商品
            $items = json_decode($data['items'], true);
            $goodsList = [];
            $totalAmount = 0;
            $totalPoints = 0;
            
            foreach ($items as $item) {
                $goods = WsGoods::find($item['goods_id']);
                if (!$goods || $goods->shop_id != $data['shop_id'] || $goods->status != 'on') {
                    throw new \Exception("商品ID {$item['goods_id']} 不可用");
                }
                
                // 检查库存
                if ($goods->stock < $item['quantity']) {
                    throw new \Exception("商品 {$goods->name} 库存不足");
                }
                
                // 计算价格
                $price = $this->calculateMemberPrice($goods->price, $member->level);
                $subtotal = $price * $item['quantity'];
                
                $goodsList[] = [
                    'goods' => $goods,
                    'quantity' => $item['quantity'],
                    'price' => $price,
                    'subtotal' => $subtotal,
                ];
                
                $totalAmount += $subtotal;
                $totalPoints += $subtotal * Config::get('wechat_shop.member.points.order');
            }
            
            // 生成订单号
            $orderNo = 'O' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
            
            // 创建订单
            $order = WsOrder::create([
                'order_no' => $orderNo,
                'shop_id' => $data['shop_id'],
                'member_id' => $data['member_id'],
                'total_amount' => $totalAmount,
                'actual_amount' => $totalAmount, // 实际支付金额(未计算优惠券等)
                'points_earned' => $totalPoints,
                'status' => 'pending',
                'pay_status' => 'unpaid',
                'shipping_status' => 'unshipped',
                'address_info' => $this->getAddressInfo($data['address_id']),
                'remark' => $data['remark'],
                'create_time' => time(),
            ]);
            
            // 创建订单商品项
            $orderItems = [];
            foreach ($goodsList as $item) {
                $orderItems[] = [
                    'order_id' => $order->id,
                    'goods_id' => $item['goods']->id,
                    'goods_name' => $item['goods']->name,
                    'goods_image' => json_decode($item['goods']->images, true)[0],
                    'quantity' => $item['quantity'],
                    'price' => $item['price'],
                    'subtotal' => $item['subtotal'],
                ];
                
                // 扣减库存
                WsGoods::update([
                    'stock' => Db::raw('stock-'.$item['quantity']),
                ], ['id' => $item['goods']->id]);
            }
            Db::name('ws_order_items')->insertAll($orderItems);
            
            // 处理分销关系
            $this->processDistribution($order, $member);
            
            Db::commit();
            return $order;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
    
    /**
     * 处理支付成功订单
     */
    public function processPaidOrder($orderNo)
    {
        Db::startTrans();
        try {
            $order = WsOrder::where('order_no', $orderNo)->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            
            // 更新订单状态
            $order->pay_status = 'paid';
            $order->pay_time = time();
            $order->status = 'processing';
            $order->save();
            
            // 更新会员积分
            if ($order->points_earned > 0) {
                WsMember::update([
                    'points' => Db::raw('points+'.$order->points_earned),
                ], ['id' => $order->member_id]);
                
                // 检查会员升级
                $this->checkMemberUpgrade($order->member_id);
            }
            
            // 处理分销订单状态
            Db::name('ws_distribution')
                ->where('order_id', $order->id)
                ->update([
                    'status' => 'paid',
                    'update_time' => time(),
                ]);
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
    
    /**
     * 申请成为分销商
     */
    public function applyDistribution($memberId)
    {
        Db::startTrans();
        try {
            $member = WsMember::find($memberId);
            if (!$member) {
                throw new \Exception('会员不存在');
            }
            
            // 检查是否已是分销商
            if ($member->is_distributor) {
                throw new \Exception('您已是分销商');
            }
            
            // 检查申请条件(例如:购买过商品)
            $orderCount = WsOrder::where('member_id', $memberId)
                ->where('pay_status', 'paid')
                ->count();
                
            if ($orderCount < 1) {
                throw new \Exception('您需要至少完成一笔订单才能申请成为分销商');
            }
            
            // 更新会员分销状态
            $member->is_distributor = 1;
            $member->distributor_status = 'pending';
            $member->distributor_apply_time = time();
            $member->save();
            
            Db::commit();
            return $member;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
    
    /**
     * 获取分销订单
     */
    public function getDistributionOrders($memberId, $status = 'pending')
    {
        $orders = Db::name('ws_distribution')
            ->alias('d')
            ->join('ws_order o', 'd.order_id=o.id')
            ->join('ws_member m', 'o.member_id=m.id')
            ->where('d.distributor_id', $memberId)
            ->where('d.status', $status)
            ->field('d.*, o.order_no, o.total_amount, o.create_time as order_time, m.nickname, m.avatar')
            ->select();
            
        return $orders;
    }
    
    /**
     * 申请提现
     */
    public function applyWithdrawal($data)
    {
        Db::startTrans();
        try {
            $member = WsMember::find($data['member_id']);
            if (!$member || !$member->is_distributor || $member->distributor_status != 'approved') {
                throw new \Exception('您不是有效的分销商');
            }
            
            // 检查可提现余额
            $available = Db::name('ws_distribution')
                ->where('distributor_id', $data['member_id'])
                ->where('status', 'completed')
                ->where('is_withdrawn', 0)
                ->sum('amount');
                
            if ($available < $data['amount']) {
                throw new \Exception('可提现余额不足');
            }
            
            // 检查最低提现金额
            $minWithdraw = Config::get('wechat_shop.distribution.withdraw_min');
            if ($data['amount'] < $minWithdraw) {
                throw new \Exception('最低提现金额为' . ($minWithdraw / 100) . '元');
            }
            
            // 创建提现申请
            $withdrawal = WsWithdrawal::create([
                'member_id' => $data['member_id'],
                'amount' => $data['amount'],
                'bank_info' => $data['bank_info'],
                'status' => 'pending',
                'apply_time' => time(),
            ]);
            
            // 标记分销记录为提现中
            Db::name('ws_distribution')
                ->where('distributor_id', $data['member_id'])
                ->where('status', 'completed')
                ->where('is_withdrawn', 0)
                ->order('id', 'asc')
                ->limit(100) // 防止一次处理太多
                ->update([
                    'withdrawal_id' => $withdrawal->id,
                    'is_withdrawn' => 1,
                ]);
            
            Db::commit();
            return $withdrawal;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
    
    /**
     * 获取店铺统计
     */
    public function getShopStats($shopId, $params = [])
    {
        $startDate = $params['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
        $endDate = $params['end_date'] ?? date('Y-m-d');
        
        // 基础统计
        $stats = [
            'order_count' => WsOrder::where('shop_id', $shopId)
                ->whereBetweenTime('create_time', $startDate, $endDate)
                ->count(),
            'paid_order_count' => WsOrder::where('shop_id', $shopId)
                ->where('pay_status', 'paid')
                ->whereBetweenTime('create_time', $startDate, $endDate)
                ->count(),
            'total_amount' => WsOrder::where('shop_id', $shopId)
                ->where('pay_status', 'paid')
                ->whereBetweenTime('create_time', $startDate, $endDate)
                ->sum('total_amount'),
            'avg_order_amount' => WsOrder::where('shop_id', $shopId)
                ->where('pay_status', 'paid')
                ->whereBetweenTime('create_time', $startDate, $endDate)
                ->avg('total_amount'),
        ];
        
        // 商品销售排行
        $topGoods = Db::name('ws_order_items')
            ->alias('oi')
            ->join('ws_order o', 'oi.order_id=o.id')
            ->where('o.shop_id', $shopId)
            ->where('o.pay_status', 'paid')
            ->whereBetweenTime('o.create_time', $startDate, $endDate)
            ->field('oi.goods_id, oi.goods_name, sum(oi.quantity) as total_quantity, sum(oi.subtotal) as total_amount')
            ->group('oi.goods_id')
            ->order('total_quantity', 'desc')
            ->limit(10)
            ->select();
            
        $stats['top_goods'] = $topGoods;
        
        // 分销统计
        $distributionStats = Db::name('ws_distribution')
            ->alias('d')
            ->join('ws_order o', 'd.order_id=o.id')
            ->where('o.shop_id', $shopId)
            ->where('o.pay_status', 'paid')
            ->whereBetweenTime('o.create_time', $startDate, $endDate)
            ->field('d.level, count(*) as order_count, sum(d.amount) as total_amount')
            ->group('d.level')
            ->select();
            
        $stats['distribution'] = $distributionStats;
        
        return $stats;
    }
    
    /**
     * 计算会员价格
     */
    protected function calculateMemberPrice($price, $level)
    {
        $levels = Config::get('wechat_shop.member.levels');
        if (isset($levels[$level])) {
            return round($price * $levels[$level]['discount'], 2);
        }
        return $price;
    }
    
    /**
     * 获取地址信息
     */
    protected function getAddressInfo($addressId)
    {
        // 实际项目中从地址表获取
        return json_encode(['id' => $addressId, 'info' => '模拟地址信息']);
    }
    
    /**
     * 处理分销关系
     */
    protected function processDistribution($order, $member)
    {
        $distributionLevels = Config::get('wechat_shop.distribution.levels');
        $distributionRates = Config::get('wechat_shop.distribution.rates');
        
        // 查找上级分销商
        $parents = $this->findDistributionParents($member->id, $distributionLevels);
        
        $distributionData = [];
        foreach ($parents as $level => $parent) {
            $rate = $distributionRates[$level] ?? 0;
            $amount = round($order->total_amount * $rate, 2);
            
            if ($amount > 0) {
                $distributionData[] = [
                    'order_id' => $order->id,
                    'distributor_id' => $parent['id'],
                    'member_id' => $member->id,
                    'level' => $level + 1,
                    'rate' => $rate,
                    'amount' => $amount,
                    'status' => 'pending',
                    'create_time' => time(),
                ];
            }
        }
        
        if (!empty($distributionData)) {
            Db::name('ws_distribution')->insertAll($distributionData);
        }
    }
    
    /**
     * 查找分销上级
     */
    protected function findDistributionParents($memberId, $maxLevel = 3)
    {
        $parents = [];
        $currentId = $memberId;
        
        for ($i = 0; $i < $maxLevel; $i++) {
            $parent = Db::name('ws_member_relation')
                ->where('member_id', $currentId)
                ->find();
                
            if (!$parent || !$parent['parent_id']) {
                break;
            }
            
            // 检查上级是否是分销商
            $distributor = WsMember::where('id', $parent['parent_id'])
                ->where('is_distributor', 1)
                ->where('distributor_status', 'approved')
                ->find();
                
            if ($distributor) {
                $parents[$i] = [
                    'id' => $distributor->id,
                    'level' => $i + 1,
                ];
                $currentId = $distributor->id;
            } else {
                break;
            }
        }
        
        return $parents;
    }
    
    /**
     * 检查会员升级
     */
    protected function checkMemberUpgrade($memberId)
    {
        $member = WsMember::find($memberId);
        $levels = Config::get('wechat_shop.member.levels');
        
        $totalSpent = WsOrder::where('member_id', $memberId)
            ->where('pay_status', 'paid')
            ->sum('total_amount');
            
        foreach ($levels as $level => $config) {
            if ($totalSpent >= $config['upgrade_condition'] && $level > $member->level) {
                $member->level = $level;
                $member->save();
                break;
            }
        }
    }
}

4. 微信支付服务类 (app/service/WechatPayService.php)

<?php
namespace app\service;

use think\facade\Config;
use EasyWeChat\Factory;
use app\model\WsOrder;

class WechatPayService
{
    protected $payment;
    
    public function __construct()
    {
        $config = Config::get('wechat_shop.payment');
        $this->payment = Factory::payment([
            'app_id' => $config['app_id'],
            'mch_id' => $config['mch_id'],
            'key' => $config['key'],
            'cert_path' => $config['cert_path'],
            'key_path' => $config['key_path'],
        ]);
    }
    
    /**
     * 创建支付订单
     */
    public function createPayment($order, $openid)
    {
        $body = '订单支付-' . $order->order_no;
        $totalFee = $order->actual_amount * 100; // 转为分
        
        $result = $this->payment->order->unify([
            'body' => $body,
            'out_trade_no' => $order->order_no,
            'total_fee' => $totalFee,
            'notify_url' => url('/shop/pay/notify')->domain(true)->build(),
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ]);
        
        if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
            throw new \Exception($result['return_msg'] ?? $result['err_code_des'] ?? '支付创建失败');
        }
        
        // 获取JSAPI调起支付参数
        $jssdk = $this->payment->jssdk;
        $config = $jssdk->sdkConfig($result['prepay_id']);
        
        return [
            'order_no' => $order->order_no,
            'config' => $config,
        ];
    }
    
    /**
     * 处理支付回调
     */
    public function handleNotify()
    {
        $response = $this->payment->handlePaidNotify(function($message, $fail) {
            // 检查订单是否存在
            $order = WsOrder::where('order_no', $message['out_trade_no'])->find();
            if (!$order) {
                return $fail('订单不存在');
            }
            
            // 检查订单状态
            if ($order->pay_status != 'unpaid') {
                return true; // 已处理过
            }
            
            // 检查金额是否一致
            if ($order->actual_amount * 100 != $message['total_fee']) {
                return $fail('金额不一致');
            }
            
            // 处理分账
            if (Config::get('wechat_shop.payment.profit_sharing')) {
                $this->processProfitSharing($order);
            }
            
            return [
                'out_trade_no' => $message['out_trade_no'],
                'transaction_id' => $message['transaction_id'],
                'total_fee' => $message['total_fee'],
                'time_end' => $message['time_end'],
            ];
        });
        
        return $response;
    }
    
    /**
     * 处理分账
     */
    protected function processProfitSharing($order)
    {
        // 查找需要分账的分销订单
        $distributions = Db::name('ws_distribution')
            ->where('order_id', $order->id)
            ->where('status', 'pending')
            ->select();
            
        if (empty($distributions)) {
            return;
        }
        
        // 构造分账接收方列表
        $receivers = [];
        foreach ($distributions as $dist) {
            $receivers[] = [
                'type' => 'PERSONAL_OPENID', // 分给个人
                'account' => $this->getMemberOpenId($dist['distributor_id']),
                'amount' => $dist['amount'] * 100, // 转为分
                'description' => '订单'.$order->order_no.'的分销佣金',
            ];
        }
        
        // 添加店铺分账
        $shopRate = Config::get('wechat_shop.shop.default_commission_rate');
        $shopAmount = $order->actual_amount * (1 - $shopRate) * 100;
        $receivers[] = [
            'type' => 'MERCHANT_ID', // 分给商户
            'account' => Config::get('wechat_shop.payment.mch_id'),
            'amount' => $shopAmount,
            'description' => '订单'.$order->order_no.'的店铺收入',
        ];
        
        // 调用分账API
        $result = $this->payment->profit_sharing->addReceiver($receivers);
        if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
            throw new \Exception('分账接收方添加失败: '.($result['err_code_des'] ?? ''));
        }
        
        // 发起分账请求
        $result = $this->payment->profit_sharing->share(
            $order->order_no,
            $order->transaction_id,
            $receivers
        );
        
        if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
            throw new \Exception('分账失败: '.($result['err_code_des'] ?? ''));
        }
        
        // 更新分销订单状态
        Db::name('ws_distribution')
            ->where('order_id', $order->id)
            ->update([
                'status' => 'paid',
                'update_time' => time(),
            ]);
    }
    
    /**
     * 获取会员微信openid
     */
    protected function getMemberOpenId($memberId)
    {
        // 实际项目中从会员表获取
        return '模拟OpenID_' . $memberId;
    }
}

数据库迁移文件

<?php
use think\migration\Migrator;
use think\migration\db\Column;

class CreateWechatShopTables extends Migrator
{
    public function change()
    {
        // 店铺表
        $table = $this->table('ws_shops', ['comment' => '微信店铺表']);
        $table->addColumn('name', 'string', ['limit' => 100, 'comment' => '店铺名称'])
              ->addColumn('logo', 'string', ['limit' => 255, 'comment' => '店铺logo'])
              ->addColumn('description', 'string', ['limit' => 500, 'null' => true, 'comment' => '店铺描述'])
              ->addColumn('owner_id', 'integer', ['comment' => '店主ID'])
              ->addColumn('contact', 'string', ['limit' => 50, 'comment' => '联系方式'])
              ->addColumn('address', 'string', ['limit' => 255, 'comment' => '店铺地址'])
              ->addColumn('status', 'string', ['limit' => 20, 'default' => 'pending', 'comment' => '状态'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addColumn('update_time', 'integer', ['null' => true, 'comment' => '更新时间'])
              ->addIndex(['owner_id'])
              ->addIndex(['status'])
              ->create();
              
        // 店铺设置表
        $table = $this->table('ws_shop_settings', ['comment' => '店铺设置表']);
        $table->addColumn('shop_id', 'integer', ['comment' => '店铺ID'])
              ->addColumn('commission_rate', 'decimal', ['precision' => 5, 'scale' => 2, 'comment' => '佣金比例'])
              ->addColumn('settlement_days', 'integer', ['comment' => '结算周期(天)'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addColumn('update_time', 'integer', ['null' => true, 'comment' => '更新时间'])
              ->addIndex(['shop_id'], ['unique' => true])
              ->create();
              
        // 商品表
        $table = $this->table('ws_goods', ['comment' => '商品表']);
        $table->addColumn('shop_id', 'integer', ['comment' => '店铺ID'])
              ->addColumn('name', 'string', ['limit' => 100, 'comment' => '商品名称'])
              ->addColumn('category_id', 'integer', ['comment' => '分类ID'])
              ->addColumn('price', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '售价'])
              ->addColumn('original_price', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '原价'])
              ->addColumn('stock', 'integer', ['default' => 0, 'comment' => '库存'])
              ->addColumn('images', 'text', ['comment' => '商品图片(JSON)'])
              ->addColumn('description', 'text', ['null' => true, 'comment' => '商品描述'])
              ->addColumn('specs', 'text', ['null' => true, 'comment' => '规格(JSON)'])
              ->addColumn('status', 'string', ['limit' => 20, 'default' => 'on', 'comment' => '状态'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addColumn('update_time', 'integer', ['null' => true, 'comment' => '更新时间'])
              ->addIndex(['shop_id'])
              ->addIndex(['category_id'])
              ->addIndex(['status'])
              ->create();
              
        // 商品SKU表
        $table = $this->table('ws_goods_skus', ['comment' => '商品SKU表']);
        $table->addColumn('goods_id', 'integer', ['comment' => '商品ID'])
              ->addColumn('specs', 'text', ['comment' => '规格(JSON)'])
              ->addColumn('price', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '售价'])
              ->addColumn('original_price', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '原价'])
              ->addColumn('stock', 'integer', ['default' => 0, 'comment' => '库存'])
              ->addColumn('code', 'string', ['limit' => 50, 'null' => true, 'comment' => 'SKU编码'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addColumn('update_time', 'integer', ['null' => true, 'comment' => '更新时间'])
              ->addIndex(['goods_id'])
              ->create();
              
        // 订单表
        $table = $this->table('ws_orders', ['comment' => '订单表']);
        $table->addColumn('order_no', 'string', ['limit' => 50, 'comment' => '订单编号'])
              ->addColumn('shop_id', 'integer', ['comment' => '店铺ID'])
              ->addColumn('member_id', 'integer', ['comment' => '会员ID'])
              ->addColumn('total_amount', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '订单总金额'])
              ->addColumn('actual_amount', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '实际支付金额'])
              ->addColumn('points_earned', 'integer', ['default' => 0, 'comment' => '获得积分'])
              ->addColumn('status', 'string', ['limit' => 20, 'default' => 'pending', 'comment' => '订单状态'])
              ->addColumn('pay_status', 'string', ['limit' => 20, 'default' => 'unpaid', 'comment' => '支付状态'])
              ->addColumn('shipping_status', 'string', ['limit' => 20, 'default' => 'unshipped', 'comment' => '发货状态'])
              ->addColumn('address_info', 'text', ['comment' => '收货地址(JSON)'])
              ->addColumn('remark', 'string', ['limit' => 255, 'null' => true, 'comment' => '备注'])
              ->addColumn('pay_time', 'integer', ['null' => true, 'comment' => '支付时间'])
              ->addColumn('shipping_time', 'integer', ['null' => true, 'comment' => '发货时间'])
              ->addColumn('complete_time', 'integer', ['null' => true, 'comment' => '完成时间'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addColumn('update_time', 'integer', ['null' => true, 'comment' => '更新时间'])
              ->addIndex(['order_no'], ['unique' => true])
              ->addIndex(['shop_id'])
              ->addIndex(['member_id'])
              ->addIndex(['status'])
              ->addIndex(['create_time'])
              ->create();
              
        // 订单商品表
        $table = $this->table('ws_order_items', ['comment' => '订单商品表']);
        $table->addColumn('order_id', 'integer', ['comment' => '订单ID'])
              ->addColumn('goods_id', 'integer', ['comment' => '商品ID'])
              ->addColumn('goods_name', 'string', ['limit' => 100, 'comment' => '商品名称'])
              ->addColumn('goods_image', 'string', ['limit' => 255, 'comment' => '商品图片'])
              ->addColumn('quantity', 'integer', ['comment' => '数量'])
              ->addColumn('price', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '单价'])
              ->addColumn('subtotal', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '小计'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addIndex(['order_id'])
              ->addIndex(['goods_id'])
              ->create();
              
        // 会员表
        $table = $this->table('ws_members', ['comment' => '会员表']);
        $table->addColumn('openid', 'string', ['limit' => 50, 'comment' => '微信openid'])
              ->addColumn('unionid', 'string', ['limit' => 50, 'null' => true, 'comment' => '微信unionid'])
              ->addColumn('nickname', 'string', ['limit' => 50, 'comment' => '昵称'])
              ->addColumn('avatar', 'string', ['limit' => 255, 'null' => true, 'comment' => '头像'])
              ->addColumn('mobile', 'string', ['limit' => 20, 'null' => true, 'comment' => '手机号'])
              ->addColumn('level', 'integer', ['default' => 1, 'comment' => '会员等级'])
              ->addColumn('points', 'integer', ['default' => 0, 'comment' => '积分'])
              ->addColumn('is_distributor', 'boolean', ['default' => 0, 'comment' => '是否是分销商'])
              ->addColumn('distributor_status', 'string', ['limit' => 20, 'null' => true, 'comment' => '分销商状态'])
              ->addColumn('distributor_apply_time', 'integer', ['null' => true, 'comment' => '分销申请时间'])
              ->addColumn('register_time', 'integer', ['comment' => '注册时间'])
              ->addColumn('last_login_time', 'integer', ['null' => true, 'comment' => '最后登录时间'])
              ->addIndex(['openid'], ['unique' => true])
              ->addIndex(['unionid'])
              ->addIndex(['mobile'])
              ->addIndex(['level'])
              ->create();
              
        // 会员关系表
        $table = $this->table('ws_member_relation', ['comment' => '会员关系表']);
        $table->addColumn('member_id', 'integer', ['comment' => '会员ID'])
              ->addColumn('parent_id', 'integer', ['comment' => '上级ID'])
              ->addColumn('level', 'integer', ['comment' => '层级'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addIndex(['member_id', 'parent_id'], ['unique' => true])
              ->addIndex(['parent_id'])
              ->create();
              
        // 分销表
        $table = $this->table('ws_distribution', ['comment' => '分销表']);
        $table->addColumn('order_id', 'integer', ['comment' => '订单ID'])
              ->addColumn('distributor_id', 'integer', ['comment' => '分销商ID'])
              ->addColumn('member_id', 'integer', ['comment' => '下单会员ID'])
              ->addColumn('level', 'integer', ['comment' => '分销层级'])
              ->addColumn('rate', 'decimal', ['precision' => 5, 'scale' => 2, 'comment' => '佣金比例'])
              ->addColumn('amount', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '佣金金额'])
              ->addColumn('status', 'string', ['limit' => 20, 'default' => 'pending', 'comment' => '状态'])
              ->addColumn('is_withdrawn', 'boolean', ['default' => 0, 'comment' => '是否已提现'])
              ->addColumn('withdrawal_id', 'integer', ['null' => true, 'comment' => '提现记录ID'])
              ->addColumn('create_time', 'integer', ['comment' => '创建时间'])
              ->addColumn('update_time', 'integer', ['null' => true, 'comment' => '更新时间'])
              ->addIndex(['order_id'])
              ->addIndex(['distributor_id'])
              ->addIndex(['member_id'])
              ->addIndex(['status'])
              ->create();
              
        // 提现表
        $table = $this->table('ws_withdrawals', ['comment' => '提现表']);
        $table->addColumn('member_id', 'integer', ['comment' => '会员ID'])
              ->addColumn('amount', 'decimal', ['precision' => 10, 'scale' => 2, 'comment' => '提现金额'])
              ->addColumn('bank_info', 'text', ['comment' => '银行信息(JSON)'])
              ->addColumn('status', 'string', ['limit' => 20, 'default' => 'pending', 'comment' => '状态'])
              ->addColumn('apply_time', 'integer', ['comment' => '申请时间'])
              ->addColumn('complete_time', 'integer', ['null' => true, 'comment' => '完成时间'])
              ->addIndex(['member_id'])
              ->addIndex(['status'])
              ->create();
    }
}

使用说明

1. 系统部署

  1. 安装ThinkPHP 6.x框架

  2. 执行数据库迁移命令创建所需表

  3. 配置微信支付和分账信息

  4. 配置路由指向ShopController

2. 功能使用

2.1 店铺管理
  1. ​​创建店铺​​:

    • 调用/shop/create接口创建店铺

    • 店铺需要审核通过后才能使用

  2. ​​商品管理​​:

    • 调用/shop/goods/add接口添加商品

    • 支持多规格SKU管理

2.2 订单流程
  1. ​​创建订单​​:

    • 调用/shop/order/create接口创建订单

    • 系统自动计算会员折扣价

  2. ​​微信支付​​:

    • 调用/shop/pay接口获取支付参数

    • 前端使用JSAPI调起微信支付

  3. ​​支付回调​​:

    • 系统自动处理支付成功逻辑

    • 更新订单状态、分配佣金、赠送积分

2.3 分销系统
  1. ​​申请分销​​:

    • 会员满足条件后可申请成为分销商

    • 调用/shop/distribution/apply接口

  2. ​​分销关系​​:

    • 系统自动记录三级分销关系

    • 订单支付后计算各级佣金

  3. ​​佣金提现​​:

    • 分销商可申请提现佣金

    • 调用/shop/withdrawal/apply接口

2.4 会员系统
  1. ​​会员等级​​:

    • 根据消费金额自动升级

    • 不同等级享受不同折扣

  2. ​​积分系统​​:

    • 购物赠送积分

    • 积分可用于抵扣或兑换商品

3. API接口

  • POST /shop/create创建店铺

  • POST /shop/goods/add添加商品

  • POST /shop/order/create创建订单

  • POST /shop/pay微信支付下单

  • POST /shop/pay/notify支付回调通知

  • POST /shop/distribution/apply申请分销

  • GET /shop/distribution/orders获取分销订单

  • POST /shop/withdrawal/apply申请提现

  • GET /shop/stats获取店铺统计

系统特点

  1. ​​多店铺支持​​:支持多个商家独立运营

  2. ​​微信生态整合​​:深度整合微信支付、分账、公众号等功能

  3. ​​三级分销体系​​:完善的佣金计算与结算机制

  4. ​​会员成长体系​​:自动升级与积分奖励

  5. ​​数据统计​​:多维度的销售与分销数据分析

  6. ​​高扩展性​​:支持定制化开发与功能扩展

这个系统适合想要在微信生态中搭建多店铺电商平台的企业,特别适合需要发展分销团队的社交电商场景。系统可根据实际业务需求进行定制扩展。

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐