×
微信咨询
微信二维码

长按图片识别添加或保存到相册

产品服务 帮助文档

LtStore - 来团云店小程序商城API架构详解

LtStore来团云店小程序商城API架构详解,涵盖前后端分离设计、URL路由解析、前端请求封装、后端控制器实现及数据流转,帮助开发者快速掌握接口开发与问题排查。

来团智慧商业小程序零代码开发平台 多行业适用

来团智慧商业小程序零代码开发平台 多行业适用

来团智慧商业小程序零代码开发平台,多行业适配。无需代码,拖拽式设计,轻松打造订货商城、会员制商城、分销商城及小程序官网。不仅能满足通用需求,还支持定制化,从页面布局到功能模块,随心定制,助您快速搭建专属商业小程序,抢占市场先机。

一、整体架构概览

LtStore 采用经典的 前后端分离 架构:

┌─────────────────────────────────────────────────────────────────────────┐
│                           小程序前端 (wxapp)                              │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  pages/goods/index.js                                          │    │
│  │  App._get('goods/detail', {goods_id: 1}, res => {...})        │    │
│  └───────────────────────────┬─────────────────────────────────────┘    │
└──────────────────────────────┼────────────────────────────────────────────┘
                               │ HTTP请求
                               ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                                 后端 (source)                           │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  URL: https://domain.com/index.php?s=/api/goods/detail         │    │
│  │                    │                                            │    │
│  │                    ▼                                            │    │
│  │  api/controller/Goods.php -> detail()                          │    │
│  │                    │                                            │    │
│  │                    ▼                                            │    │
│  │  api/model/Goods.php -> getDetails()                            │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────┘

二、URL 路由解析机制

2.1 请求URL结构

当小程序调用 App._get('goods/detail', {...}) 时,实际发送的请求URL为:

https://域名/index.php?s=/api/goods/detail&goods_id=1&wxapp_id=10001&token=xxx

2.2 URL 解析过程

URL 解析遵循以下规则:

URL参数 解析结果
s=/api 模块 (module) = api
goods 控制器 (controller) = Goods
detail 操作/方法 (action) = detail
goods_id=1 传入的参数

文件映射关系:

URL部分 文件路径
api source/application/api/
Goods source/application/api/controller/Goods.php
detail source/application/api/controller/Goods.php 中的 detail() 方法

2.3 入口文件分析

web/index.php 是整个应用的入口:

<?php
// [ 应用入口文件 ]

// 定义运行目录
define('WEB_PATH', __DIR__ . '/');

// 定义应用目录
define('APP_PATH', WEB_PATH . '../source/application/');

// 加载框架引导文件
require APP_PATH . '../thinkphp/start.php';

ThinkPHP 会根据 URL 参数自动解析并加载对应的控制器。

三、前端 API 请求机制

3.1 App.js 全局对象

小程序全局定义在 wxapp/app.js,封装了网络请求方法:

// wxapp/app.js 第28行
api_root: siteinfo.siteroot + 'index.php?s=/api/',

3.2 _get 方法实现

// wxapp/app.js 第169-220行
_get(url, data, success, fail, complete, check_login) {
    wx.showNavigationBarLoading();
    let _this = this;
    
    // 1. 构造请求参数
    data = data || {};
    data.wxapp_id = _this.getWxappId();  // 小程序ID
    
    // 2. 构造GET请求
    let request = () => {
      data.token = wx.getStorageSync('token');  // 用户登录令牌
      wx.request({
        url: _this.api_root + url,  // 完整URL = api_root + 'goods/detail'
        header: {
          'content-type': 'application/json'
        },
        data: data,  // 请求参数 {goods_id, wxapp_id, token}
        
        // 3. 成功回调处理
        success(res) {
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            _this.showError('网络请求出错');
            return false;
          }
          if (res.data.code === -1) {
            // 登录态失效,重新登录
            wx.hideNavigationBarLoading();
            _this.doLogin(2);
          } else if (res.data.code === 0) {
            // 业务错误
            _this.showError(res.data.msg, () => {
              fail && fail(res);
            });
            return false;
          } else {
            // 请求成功
            success && success(res.data);
          }
        },
        
        // 4. 失败回调处理
        fail(res) {
          _this.showError(res.errMsg, () => {
            fail && fail(res);
          });
        },
        
        // 5. 完成回调
        complete(res) {
          wx.hideNavigationBarLoading();
          complete && complete(res);
        },
      });
    };
    
    // 6. 判断是否需要验证登录
    check_login ? _this.doLogin(request) : request();
}

3.3 请求参数说明

参数名 来源 说明
url 传入 API接口名称,如 goods/detail
goods_id 传入 业务参数,商品ID
wxapp_id 自动添加 小程序ID,用于识别多小程序
token 自动添加 用户登录令牌,用于身份验证

3.4 前端调用示例

// wxapp/pages/goods/index.js 第74行
App._get('goods/detail', {
    goods_id: options.id
}, res => {
    // res.data = { code: 1, msg: 'success', data: {...} }
    that.setData({ detail: res.data.detail });
});

3.5 返回数据结构

所有API返回统一JSON格式:

{
    "code": 1,           // 1=成功, 0=业务错误, -1=登录态失效
    "msg": "success",    // 提示信息
    "data": {            // 业务数据
        "detail": {...},
        "cart_total_num": 0
    }
}

四、后端控制器实现

4.1 Goods 控制器

// source/application/api/controller/Goods.php

namespace apppicontroller;

use apppimodelGoods as GoodsModel;
use apppimodelCart as CartModel;
use apppicontrollerBase;

class Goods extends Base
{
    /**
     * 商品详情
     * @param int $goods_id 商品ID
     */
    public function detail($goods_id)
    {
        // 获取用户信息(false表示不强制登录)
        $user = $this->getUser(false);
        
        // 获取商品详情
        $model = new GoodsModel;
        $goods = $model->getDetails($goods_id, $this->getUser(false));
        
        if ($goods === false) {
            return $this->renderError($model->getError() ?: '商品信息不存在');
        }
        
        // 返回成功数据
        return $this->renderSuccess([
            'detail' => $goods,           // 商品详情
            'cart_total_num' => $user ? (new CartModel($user))->getTotalNum() : 0,
        ]);
    }
}

4.2 Base 控制器基类

所有API控制器都继承自 api/controller/Base,提供了常用方法:

// source/application/api/controller/Base.php

namespace apppicontroller;

use appcommonmodelUser as UserModel;

class Base extends 	hinkController
{
    protected $user;  // 当前登录用户
    
    /**
     * 获取当前用户
     * @param bool $is_force 是否强制登录
     * @return UserModel|false
     */
    protected function getUser($is_force = true)
    {
        // 从请求头获取token
        $token = $this->request->header('token') 
              ?? $this->request->param('token');
        
        if (empty($token)) {
            if ($is_force) {
                $this->renderError('请先登录');
            }
            return false;
        }
        
        // 从缓存/数据库验证token
        $userId = Cache::get('token_' . $token);
        if (!$userId) {
            if ($is_force) {
                $this->renderError('登录已失效');
            }
            return false;
        }
        
        // 获取用户信息
        $user = UserModel::get($userId);
        $this->user = $user;
        return $user;
    }
    
    /**
     * 返回成功JSON
     * @param mixed $data 数据
     * @param array $msg 提示信息
     */
    protected function renderSuccess($data = [], $msg = [])
    {
        return json([
            'code' => 1,
            'msg' => $msg['success'] ?? 'success',
            'data' => $data
        ]);
    }
    
    /**
     * 返回错误JSON
     * @param string $msg 错误信息
     */
    protected function renderError($msg = '')
    {
        return json([
            'code' => 0,
            'msg' => $msg,
            'data' => []
        ]);
    }
}

五、数据流转完整流程

┌──────────────────────────────────────────────────────────────────────────┐
│                           小程序前端                                      │
│                                                                          │
│  1. pages/goods/index.js                                                │
│     App._get('goods/detail', {goods_id: 1}, res => {...})              │
│                                                                          │
│  2. app.js _get()                                                       │
│     - 拼接URL: api_root + 'goods/detail'                                │
│     - 添加参数: wxapp_id, token                                          │
│     - 发送wx.request请求                                                │
└────────────────────────────────┬─────────────────────────────────────────┘
                                 │ HTTP请求
                                 │ https://domain.com/index.php?s=/api/goods/detail
                                 │ &goods_id=1&wxapp_id=10001&token=xxx
                                 ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                             后端                                      │
│                                                                          │
│  3. 入口: web/index.php                                                  │
│     加载 thinkphp/start.php                                               │
│                                                                          │
│  4. 路由解析                                                              │
│     URL: /api/goods/detail                                               │
│     → module=api, controller=Goods, action=detail                       │
│                                                                          │
│  5. 控制器: api/controller/Goods.php                                     │
│     public function detail($goods_id)                                   │
│     - $this->getUser(false) 获取用户                                    │
│     - GoodsModel::getDetails() 获取商品                                 │
│     - $this->renderSuccess() 返回JSON                                   │
│                                                                          │
│  6. 模型: api/model/Goods.php                                           │
│     public function getDetails($goods_id, $user)                        │
│     - 查询商品基础信息                                                   │
│     - 查询SKU规格价格                                                    │
│     - 计算会员价格 (如果有用户)                                           │
│     - 返回完整商品数据                                                   │
└────────────────────────────────┬─────────────────────────────────────────┘
                                 │ HTTP响应
                                 │ {code: 1, msg: "success", data: {...}}
                                 ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                           小程序前端                                      │
│                                                                          │
│  7. wx.request success回调                                               │
│     - res.data.code === 1                                                │
│     - success(res.data) 触发业务回调                                     │
│                                                                          │
│  8. pages/goods/index.js                                                │
│     that.setData({ detail: res.data.detail })                          │
│     - 更新页面数据                                                       │
│     - 触发页面渲染                                                       │
└──────────────────────────────────────────────────────────────────────────┘

六、路由配置

6.1 路由模式

项目使用的是 PATH_INFO 模式,配置如下:

// source/application/config.php

// 开启路由
'url_route_on' => true,

// 路由配置文件
'route_config_file' => ['route'],

// URL参数分隔符
'url_param_type' => 0,

6.2 路由规则

默认路由规则:

URL格式 解析
/module/controller/action 模块/控制器/操作
/controller/action 当前模块/控制器/操作
/action 当前控制器/操作

所以 /api/goods/detail 会解析为:

  • 模块: api (对应 application/api/)
  • 控制器: Goods (对应 application/api/controller/Goods.php)
  • 操作: detail (对应 Goods 类中的 detail() 方法)

七、添加新 API 接口示例

7.1 前端调用

// 小程序端调用
App._get('goods/getRecommend', {
    goods_id: 1,
    page: 1
}, res => {
    console.log(res.data.list);
});

7.2 后端控制器

// source/application/api/controller/Goods.php 中添加

/**
 * 获取推荐商品
 */
public function getRecommend()
{
    $goods_id = $this->request->param('goods_id', 0, 'intval');
    $page = $this->request->param('page', 1, 'intval');
    
    // 业务逻辑...
    $list = (new GoodsModel)->getRecommendList($goods_id, $page);
    
    return $this->renderSuccess([
        'list' => $list
    ]);
}

7.3 后端模型

// source/application/api/model/Goods.php 中添加

/**
 * 获取推荐商品列表
 * @param int $goods_id 当前商品ID
 * @param int $page 页码
 * @return array
 */
public function getRecommendList($goods_id, $page = 1)
{
    return self::where([
        'goods_id' => ['<>', $goods_id],
        'is_delete' => 0,
        'status' => 1
    ])
    ->page($page, 10)
    ->select();
}

八、常见问题排查

8.1 接口返回 404

  • 检查URL是否正确:/api/goods/detail
  • 检查控制器文件是否存在:application/api/controller/Goods.php
  • 检查方法名是否正确:public function detail()

8.2 接口返回 -1 (未登录)

  • 检查token是否正确传递
  • 检查token是否过期
  • 确认用户是否已登录

8.3 接口返回 0 (业务错误)

  • 查看msg字段了解具体错误信息
  • 检查传入参数是否正确
  • 查看后端日志

8.4 数据为空

  • 检查数据库是否有数据
  • 检查查询条件是否正确
  • 检查是否返回了错误

九、总结

LtStore 的 API 架构遵循以下原则:

  1. 统一返回格式: 所有API返回 {code, msg, data} 格式
  2. 自动参数注入: wxapp_id 和 token 自动添加
  3. 分层设计: Controller(控制器) → Model(模型) → Database(数据库)
  4. 错误处理: 统一错误码和错误信息
  5. 用户认证: 基于Token的身份验证机制

这种架构使得前后端开发分离清晰,易于维护和扩展。

大纲

文章目录

    联系我们
    联系方式
    • 官方服务热线:17721141027
    • 邮箱:kf@ilaituan.com
    • QQ:20262336
    扫码添加客服
    微信
    联系我们