feat(v1.1.0): 支付改由 epay 插件承载、插件纳入版本库,补齐媒体上传/LBS/互动/优惠券/后台看板,并修复余额充值资损

## 一、支付:改由已安装的 epay 插件承载(不再自研签名)
- 下单:\addons\epay\library\Service::submitOrder($amount 元, $orderNo, 'wechat', $body, $notifyUrl, null, 'miniapp', $openid)
- 验签:Service::checkNotify('wechat')(内部 $pay->verify());应答:$pay->success()(v2 = XML)
- 业务编排仍在 application/api/controller/Pay.php,不改插件源码:
  POST /pay/prepay(取调起参数,下发前剔除 appId);POST /pay/notify(公开路由:插件验签 → 金额核对 → 幂等分派)
- 配置真源 = addons/epay/config.php(后台「插件管理 → 微信支付宝整合插件 → 配置」);
  fc_config 的 wx.mchId / wx.apiKey / wx.payNotifyUrl 废弃;后台「系统设置」支付表单改只读并跳插件配置页
- 插件 API 保持 version=v2(PHP 7.4 可跑);certs/* 为 0 字节占位,不含任何真实密钥
- 修复 BUG-015:Pay::notify() 与基类站内信同名且签名不兼容导致 /pay/* 全 500,动作改名 notifyCallback()

## 二、插件纳入 Git 版本管理
- .gitignore 移除 /addons/* 与 /public/assets/addons/*(保留 .gitkeep 占位)
- 入库 addons/epay、addons/wechat、public/assets/addons/*、addons/.htaccess(deny from all)
- config.php 入库为空白模板;服务器请在填好密钥后执行
  git update-index --skip-worktree addons/epay/config.php,避免真实密钥回传仓库

## 三、安全修复:余额充值资损(高危,已实测复现)
- 现象:POST /order/recharge {payType:'balance'} 只加余额不扣款(余额 134.50 → 1022.50),等于凭空增发余额,
  可再去买会员 / 付费发布 / 解锁联系方式
- 修复:/order/recharge 仅接受 payType=wxpay,balance → 「余额充值仅支持微信支付」,其它 → 「支付方式不支持」;
  订单恒为 status=pending、pay_type=wxpay、paytime=null;入账只发生在 /pay/notify 回调(Order::creditRecharge)
  或后台「会员管理 → 余额充值」(fc/userext/recharge)
- 小程序充值页同步为「仅微信支付」+ 防重复提交 + onShow 刷新资产;mock / 用例 / 文档同步

## 四、其他 v1.1.0 能力
- 媒体上传:POST /post/upload(图片 ≤10MB / 视频 ≤50MB,真落盘),发布页 uni.uploadFile 真上传
- LBS:fc_post.lat/lng、首页 sort=nearby(距离升序、无坐标排最后)、卡片 distance、详情页地图
- 互动:举报 POST /report(原因字典)、收藏 / 关注(fc_favorite / fc_follow、/favorite/*、/follow/toggle)
- 交易:余额充值 POST /order/recharge、优惠券 /coupon/list|receive(fc_coupon / fc_user_coupon、我的资产券)
- 发布计费:会员发布折扣(discountRate/discountText)+ 免费发布条数(freeQuota*)
- 后台新增:数据总览 fc/dashboard、系统设置 fc/setting、优惠券管理 fc/coupon(含菜单与权限节点)

## 五、本批审核修复
- 详情页:游客不再请求登录态接口(避免 401 被清 token 踢去登录);微信付费查看改为支付后轮询解锁,
  不再读取 wxpay 分支未返回的 contact;加防重复提交
- 发布页:freeLeftToday → freeQuotaLeft / freeQuotaCycle / freeUnlimited(对齐后端出参);
  上传图预览拼后端域名(新增 format.js#assetUrl,后端返回相对路径)
- 收藏空态「去首页」:switchTab → reLaunch(项目用自绘 fc-tabbar,无 tabBar,switchTab 必然失败)
- 会员券 days=0 显示「永久有效」;manifest.json 补 requiredPrivateInfos(getLocation / chooseLocation)
- 后端:publishConfig 补 discountRate/discountText 与 memberPostDiscountText();优惠券总开关 coupon.enabled
  真生效(关闭后 list/receive 拒绝);后台 fc/Coupon 的 add/edit 补 strip_tags 过滤(防存储型 XSS)、
  补 searchFields='name',列表 name 列再做一次 HTML 转义
- FcInstall:补清理后台菜单缓存 __menu__(否则新菜单要等缓存过期才显示),并同步 README 说明
- 后台语言包 fc/setting.php 按「支付只读 + 跳插件配置」的新页面重写
- 文档同步:uniapp/docs/{01,03,04}、uniapp/README.md、docs/05-后端实现规范.md、后台 README 上线步骤

## 六、校验结果(全部通过)
- 后端端到端:tools/verify-api.mjs 226/226(含新增「拒绝余额充值(资损防护)」用例)
- 小程序:uniapp/tests/run.mjs 167/167;validate.mjs 0 错 0 警;check-scss 19/19
- 后台:check-admin-i18n 0 错 0 警;check-theme 0 错 0 警;9 个页面 HTTP 200 全中文
- php -l 改动/新增 PHP 文件 0 语法错误;探针复测:余额不再增长、epay 插件下单/验签链路通
这个提交包含在:
2026-10-19 10:03:13 +08:00
父节点 592c5af931
当前提交 63fdfe87d7
共有 1086 个文件被更改,包括 68849 次插入 和 276 次删除

1
addons/wechat/.addonrc 普通文件
查看文件

@@ -0,0 +1 @@
{"files":["application\/admin\/lang\/zh-cn\/wechat\/autoreply.php","application\/admin\/lang\/zh-cn\/wechat\/config.php","application\/admin\/lang\/zh-cn\/wechat\/response.php","application\/admin\/model\/WechatAutoreply.php","application\/admin\/model\/WechatContext.php","application\/admin\/model\/WechatCaptcha.php","application\/admin\/model\/WechatConfig.php","application\/admin\/model\/WechatResponse.php","application\/admin\/view\/wechat\/response\/select.html","application\/admin\/view\/wechat\/response\/add.html","application\/admin\/view\/wechat\/response\/edit.html","application\/admin\/view\/wechat\/response\/index.html","application\/admin\/view\/wechat\/menu\/index.html","application\/admin\/view\/wechat\/autoreply\/add.html","application\/admin\/view\/wechat\/autoreply\/edit.html","application\/admin\/view\/wechat\/autoreply\/index.html","application\/admin\/view\/wechat\/config\/add.html","application\/admin\/view\/wechat\/config\/edit.html","application\/admin\/view\/wechat\/config\/index.html","application\/admin\/controller\/wechat\/Response.php","application\/admin\/controller\/wechat\/Autoreply.php","application\/admin\/controller\/wechat\/Config.php","application\/admin\/controller\/wechat\/Menu.php","public\/assets\/js\/backend\/wechat\/autoreply.js","public\/assets\/js\/backend\/wechat\/config.js","public\/assets\/js\/backend\/wechat\/response.js","public\/assets\/js\/backend\/wechat\/menu.js","public\/assets\/addons\/wechat\/images\/mobile_index.png","public\/assets\/addons\/wechat\/images\/mobile_header_bg.png","public\/assets\/addons\/wechat\/images\/weixin_icon.png","public\/assets\/addons\/wechat\/images\/mobile_footer_bg.png","public\/assets\/addons\/wechat\/css\/menu.css"],"license":"regular","licenseto":"26425","licensekey":"IafQnvsMgWuA382t WNVtAQbS7OFZNjPNfUp5xg==","domains":["gynhc.com"],"licensecodes":[],"validations":["baca5b0e114fc9a55d47e7adb2332062"],"menus":["wechat","wechat\/autoreply","wechat\/autoreply\/index","wechat\/autoreply\/add","wechat\/autoreply\/edit","wechat\/autoreply\/del","wechat\/autoreply\/multi","wechat\/config","wechat\/config\/index","wechat\/config\/add","wechat\/config\/edit","wechat\/config\/del","wechat\/config\/multi","wechat\/menu","wechat\/menu\/index","wechat\/menu\/add","wechat\/menu\/edit","wechat\/menu\/del","wechat\/menu\/remote","wechat\/menu\/sync","wechat\/menu\/multi","wechat\/response","wechat\/response\/index","wechat\/response\/add","wechat\/response\/edit","wechat\/response\/del","wechat\/response\/select","wechat\/response\/multi"]}

110
addons/wechat/Wechat.php 普通文件
查看文件

@@ -0,0 +1,110 @@
<?php
namespace addons\wechat;
use app\common\library\Menu;
use think\Addons;
/**
* 微信插件
*/
class Wechat extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
$menu = [
[
'name' => 'wechat',
'title' => '微信管理',
'icon' => 'fa fa-wechat',
'sublist' => [
[
'name' => 'wechat/autoreply',
'title' => '自动回复管理',
'icon' => 'fa fa-reply-all',
'sublist' => [
['name' => 'wechat/autoreply/index', 'title' => '查看'],
['name' => 'wechat/autoreply/add', 'title' => '添加'],
['name' => 'wechat/autoreply/edit', 'title' => '修改'],
['name' => 'wechat/autoreply/del', 'title' => '删除'],
['name' => 'wechat/autoreply/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/config',
'title' => '配置管理',
'icon' => 'fa fa-cog',
'sublist' => [
['name' => 'wechat/config/index', 'title' => '查看'],
['name' => 'wechat/config/add', 'title' => '添加'],
['name' => 'wechat/config/edit', 'title' => '修改'],
['name' => 'wechat/config/del', 'title' => '删除'],
['name' => 'wechat/config/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/menu',
'title' => '菜单管理',
'icon' => 'fa fa-list',
'sublist' => [
['name' => 'wechat/menu/index', 'title' => '查看'],
['name' => 'wechat/menu/add', 'title' => '添加'],
['name' => 'wechat/menu/edit', 'title' => '修改'],
['name' => 'wechat/menu/del', 'title' => '删除'],
['name' => 'wechat/menu/remote', 'title' => '加载远程菜单'],
['name' => 'wechat/menu/sync', 'title' => '同步'],
['name' => 'wechat/menu/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/response',
'title' => '资源管理',
'icon' => 'fa fa-list-alt',
'sublist' => [
['name' => 'wechat/response/index', 'title' => '查看'],
['name' => 'wechat/response/add', 'title' => '添加'],
['name' => 'wechat/response/edit', 'title' => '修改'],
['name' => 'wechat/response/del', 'title' => '删除'],
['name' => 'wechat/response/select', 'title' => '选择'],
['name' => 'wechat/response/multi', 'title' => '批量更新'],
]
]
]
]
];
Menu::create($menu);
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
Menu::delete('wechat');
return true;
}
/**
* 插件启用方法
*/
public function enable()
{
Menu::enable('wechat');
}
/**
* 插件禁用方法
*/
public function disable()
{
Menu::disable('wechat');
}
}

100
addons/wechat/config.php 普通文件
查看文件

@@ -0,0 +1,100 @@
<?php
return [
[
'name' => 'app_id',
'title' => '微信公众号app_id',
'type' => 'string',
'content' => [],
'value' => '',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'secret',
'title' => '微信公众号secret',
'type' => 'string',
'content' => [],
'value' => '',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'token',
'title' => 'token',
'type' => 'string',
'content' => [],
'value' => '',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'aes_key',
'title' => 'aes_key',
'type' => 'string',
'content' => [],
'value' => '',
'rule' => '',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'debug',
'title' => '调试模式',
'type' => 'radio',
'content' => [
'否',
'是',
],
'value' => '0',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'log_level',
'title' => '日志记录等级',
'type' => 'select',
'content' => [
'debug' => 'debug',
'info' => 'info',
'notice' => 'notice',
'warning' => 'warning',
'error' => 'error',
'critical' => 'critical',
'alert' => 'alert',
'emergency' => 'emergency',
],
'value' => 'info',
'rule' => 'required',
'msg' => '',
'tip' => '生产环境日志记录等级',
'ok' => '',
'extend' => '',
],
[
'name' => 'oauth_callback',
'title' => '登录回调',
'type' => 'string',
'content' => [],
'value' => 'https://www.example.com/addons/wechat/index/callback',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
];

查看文件

@@ -0,0 +1,74 @@
<?php
namespace addons\wechat\controller;
use addons\wechat\library\Wechat;
use addons\wechat\model\WechatCaptcha;
use fast\Http;
/**
* 微信验证码验证接口
*/
class Captcha extends \think\addons\Controller
{
/**
* 验证码检测接口
*/
public function check()
{
$captcha = $this->request->post("captcha");
$event = $this->request->post("event");
$result = WechatCaptcha::check($captcha, $event, null, false);
if ($result) {
$this->success("验证码正确");
} else {
$this->error("验证码错误");
}
}
/**
* 验证码发送接口
*/
public function send()
{
$ip = $this->request->ip();
$event = $this->request->post("event");
if (!$event) {
$this->error("参数错误");
}
$captch = WechatCaptcha::where('ip', $ip)
->where('event', $event)
->whereTime('createtime', '-2 minutes')
->find();
if ($captch) {
$this->error("获取频繁,请稍后重试");
}
$token = Wechat::getAccessToken();
if (!$token) {
$this->error("发送失败,请稍后重试");
}
$context = \fast\Random::alnum(6);
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$token}";
$params = [
'expire_seconds' => 120,
'action_name' => 'QR_STR_SCENE',
'action_info' => [
'scene' => [
'scene_str' => "captcha_" . $event . "_" . $ip . "_" . $context,
]
],
];
//获取验证码
$result = Http::sendRequest($url, json_encode($params));
if ($result['ret']) {
$msg = (array)json_decode($result['msg'], true);
if (isset($msg['ticket']) && isset($msg['url'])) {
\think\Cookie::set('captcha_' . $event, $context);
$this->success("", null, ['image' => "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($msg['ticket']), 'url' => $msg['url']]);
}
}
$this->error("获取失败!请稍后重试");
}
}

查看文件

@@ -0,0 +1,166 @@
<?php
namespace addons\wechat\controller;
use addons\wechat\library\Config;
use addons\wechat\model\WechatAutoreply;
use addons\wechat\model\WechatCaptcha;
use addons\wechat\model\WechatContext;
use addons\wechat\model\WechatResponse;
use addons\wechat\model\WechatConfig;
use EasyWeChat\Factory;
use addons\wechat\library\Wechat as WechatService;
use addons\wechat\library\Config as ConfigService;
use think\Log;
/**
* 微信接口
*/
class Index extends \think\addons\Controller
{
public $app = null;
public function _initialize()
{
parent::_initialize();
$this->app = Factory::officialAccount(Config::load());
}
/**
*
*/
public function index()
{
$this->error("当前插件暂无前台页面");
}
/**
* 微信API对接接口
*/
public function api()
{
$this->app->server->push(function ($message) {
$wechatService = new WechatService;
$matches = null;
$openid = $message['FromUserName'] ?? '';
$to_openid = $message['ToUserName'] ?? '';
$unknownMessage = WechatConfig::getValue('default.unknown.message');
$unknownMessage = $unknownMessage ?: "";
switch ($message['MsgType']) {
case 'event': //事件消息
$event = $message['Event'];
$eventkey = $message['EventKey'] ?: $message['Event'];
//验证码消息
if (in_array($event, ['subscribe', 'SCAN']) && preg_match("/^(qrscene_)?captcha_([a-zA-Z0-9]+)_([0-9\.]+)_([0-9a-zA-Z]{6})/", $eventkey, $matches)) {
return WechatCaptcha::send($openid, $matches[2], $matches[3], $matches[4]);
}
switch ($event) {
case 'subscribe'://添加关注
$subscribeMessage = WechatConfig::getValue('default.subscribe.message');
$subscribeMessage = $subscribeMessage ?: "欢迎关注我们!";
return $subscribeMessage;
case 'unsubscribe'://取消关注
return '';
case 'LOCATION'://获取地理位置
return '';
case 'VIEW': //跳转链接,eventkey为链接
return '';
case 'SCAN': //扫码
return '';
default:
break;
}
$wechatResponse = WechatResponse::where(["eventkey" => $eventkey, 'status' => 'normal'])->find();
if ($wechatResponse) {
$responseContent = (array)json_decode($wechatResponse['content'], true);
$wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
$data = ['eventkey' => $eventkey, 'command' => '', 'refreshtime' => time(), 'openid' => $openid];
if ($wechatContext) {
$wechatContext->save($data);
} else {
$wechatContext = WechatContext::create($data, true);
}
$result = $wechatService->response($this, $openid, '', $responseContent, $wechatContext);
if ($result) {
return $result;
}
}
return $unknownMessage;
case 'text': //文字消息
case 'image': //图片消息
case 'voice': //语音消息
case 'video': //视频消息
case 'location': //坐标消息
case 'link': //链接消息
default: //其它消息
//自动回复处理
if ($message['MsgType'] == 'text') {
$autoreply = null;
$autoreplyList = WechatAutoreply::where('status', 'normal')->field('id,text,eventkey')->order('weigh DESC,id DESC')->select();
try {
foreach ($autoreplyList as $index => $item) {
//完全匹配和正则匹配
if ($item['text'] == $message['Content'] || (in_array(mb_substr($item['text'], 0, 1), ['#', '~', '/']) && preg_match($item['text'], $message['Content'], $matches))) {
$autoreply = $item;
break;
}
}
} catch (\Exception $e) {
}
if ($autoreply) {
$wechatResponse = WechatResponse::where(["eventkey" => $autoreply['eventkey'], 'status' => 'normal'])->find();
if ($wechatResponse) {
$responseContent = (array)json_decode($wechatResponse['content'], true);
$wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
$result = $wechatService->response($this, $openid, $message['Content'], $responseContent, $wechatContext, $matches);
if ($result) {
return $result;
}
}
}
}
return $unknownMessage;
}
return ""; //SUCCESS
});
$response = $this->app->server->serve();
// 将响应输出
$response->send();
return;
}
/**
* 登录回调
*/
public function callback()
{
}
/**
* 支付回调
*/
public function notify()
{
Log::record(file_get_contents('php://input'), "notify");
$response = $this->app->handlePaidNotify(function ($message, $fail) {
// 你的逻辑
return true;
// 或者错误消息
$fail('Order not exists.');
});
$response->send();
return;
}
}

10
addons/wechat/info.ini 普通文件
查看文件

@@ -0,0 +1,10 @@
name = wechat
title = 微信管理
intro = 在线管理微信公众号插件
author = FastAdmin
website =
version = 1.2.5
state = 1
url = /addons/wechat
license = regular
licenseto = 26425

81
addons/wechat/install.sql 普通文件
查看文件

@@ -0,0 +1,81 @@
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_autoreply` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '标题',
`text` varchar(100) NOT NULL DEFAULT '' COMMENT '触发文本',
`eventkey` varchar(50) NOT NULL DEFAULT '' COMMENT '响应事件',
`remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',
`weigh` int(10) NOT NULL DEFAULT '0' COMMENT '权重',
`createtime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '添加时间',
`updatetime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
`status` varchar(30) NOT NULL DEFAULT '' COMMENT '状态',
PRIMARY KEY (`id`),
KEY `eventkey` (`eventkey`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='微信自动回复表';
BEGIN;
INSERT INTO `__PREFIX__wechat_autoreply`(`id`, `title`, `text`, `eventkey`, `remark`, `weigh`, `createtime`, `updatetime`, `status`) VALUES (1, '输入hello', 'hello', '58c7d908c4570', '', 1, 1493366855, 1493366855, 'normal');
INSERT INTO `__PREFIX__wechat_autoreply`(`id`, `title`, `text`, `eventkey`, `remark`, `weigh`, `createtime`, `updatetime`, `status`) VALUES (2, '输入你好', '你好', '58fdfaa9e1965', '', 2, 1493704976, 1493704976, 'normal');
COMMIT;
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_captcha` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`event` varchar(100) DEFAULT '' COMMENT '事件',
`openid` varchar(255) DEFAULT NULL COMMENT '用户openid',
`context` varchar(20) DEFAULT NULL COMMENT '上下文',
`code` varchar(30) DEFAULT NULL COMMENT '验证码',
`times` int(10) unsigned DEFAULT '0' COMMENT '验证次数',
`ip` varchar(50) DEFAULT '' COMMENT 'IP',
`createtime` bigint(16) DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `ip` (`ip`,`event`) USING BTREE,
KEY `openid` (`openid`(191),`event`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='微信公众号验证码';
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_config` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '' COMMENT '配置名称',
`title` varchar(50) NOT NULL DEFAULT '' COMMENT '配置标题',
`value` text NOT NULL COMMENT '配置值',
`createtime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`updatetime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='微信配置表';
BEGIN;
INSERT INTO `__PREFIX__wechat_config` VALUES ('1', 'menu', '公众号菜单', '[{\"name\":\"外部链接\",\"sub_button\":[{\"name\":\"百度\",\"type\":\"view\",\"url\":\"https:\\/\\/www.baidu.com\"},{\"name\":\"微信开放平台\",\"type\":\"view\",\"url\":\"https:\\/\\/open.weixin.qq.com\"}]},{\"name\":\"在线客服\",\"type\":\"click\",\"key\":\"58cb852984970\"},{\"name\":\"关于我们\",\"type\":\"click\",\"key\":\"58bf944aa0777\"}]', '1497398820', '1500538185'), ('2', 'service', '客服配置', '{\"onlinetime\":\"09:00-18:00\",\"offlinemsg\":\"请在工作时间联系客服!\",\"nosessionmsg\":\"当前没有客服在线!请稍后重试!\",\"waitformsg\":\"请问有什么可以帮到您?\"}', '1497429674', '1497429674'), ('3', 'signin', '连续登录配置', '{\"s1\":\"100\",\"s2\":\"200\",\"s3\":\"300\",\"sn\":\"500\"}', '1497429711', '1497429711');
COMMIT;
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_context` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`openid` varchar(64) NOT NULL DEFAULT '',
`type` varchar(30) NOT NULL DEFAULT '' COMMENT '类型',
`eventkey` varchar(64) NOT NULL DEFAULT '',
`command` varchar(64) NOT NULL DEFAULT '',
`message` varchar(255) NOT NULL DEFAULT '' COMMENT '内容',
`refreshtime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '最后刷新时间',
`createtime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`updatetime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `openid` (`openid`,`eventkey`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信上下文表';
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_response` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '资源名',
`eventkey` varchar(128) NOT NULL DEFAULT '' COMMENT '事件',
`type` enum('text','image','news','voice','video','music','link','app') NOT NULL DEFAULT 'text' COMMENT '类型',
`content` text NOT NULL COMMENT '内容',
`remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',
`createtime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`updatetime` bigint(16) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
`status` varchar(30) NOT NULL DEFAULT '' COMMENT '状态',
PRIMARY KEY (`id`),
UNIQUE KEY `eventkey` (`eventkey`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='微信资源表';
BEGIN;
INSERT INTO `__PREFIX__wechat_response` VALUES ('1', '签到送积分', '58adaf7876aab', 'app', '{\"app\":\"signin\"}', '', '1487777656', '1487777656', 'normal'), ('2', '关于我们', '58bf944aa0777', 'app', '{\"app\":\"page\",\"id\":\"1\"}', '', '1488950346', '1488950346', 'normal'), ('3', '自动回复1', '58c7d908c4570', 'text', '{\"content\":\"world\"}', '', '1489492232', '1489492232', 'normal'), ('5', '自动回复2', '58fdfaa9e1965', 'text', '{\"content\":\"你好!我是自动回复!\"}', '', '1493039785', '1493039785', 'normal');
COMMIT;

查看文件

@@ -0,0 +1,82 @@
<?php
namespace addons\wechat\library;
/**
* 微信配置类
*/
class Config
{
public static function load()
{
$config = get_addon_config('wechat');
return [
/**
* 账号基本信息,请从微信公众平台/开放平台获取
*/
'app_id' => $config['app_id'], // AppID
'secret' => $config['secret'], // AppSecret
'token' => $config['token'], // Token
'aes_key' => $config['aes_key'], // EncodingAESKey,安全模式下请一定要填写!!!
/**
* 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
* 使用自定义类名时,构造函数将会接收一个 `EasyWeChat\Kernel\Http\Response` 实例
*/
'response_type' => 'array',
/**
* 日志配置
*
* level: 日志级别, 可选为:debug/info/notice/warning/error/critical/alert/emergency
* path:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'single',
'path' => ROOT_PATH . '/runtime/log/easywechat.log',
'level' => 'debug',
],
// 生产环境
'prod' => [
'driver' => 'daily',
'path' => ROOT_PATH . '/runtime/log/easywechat.log',
'level' => $config['log_level'],
],
],
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* http://docs.guzzlephp.org/en/stable/request-config.html
*
* - retries: 重试次数,默认 1,指定当 http 请求失败时重试的次数。
* - retry_delay: 重试延迟间隔(单位:ms),默认 500
* - log_template: 指定 HTTP 日志模板,请参考:https://github.com/guzzle/guzzle/blob/master/src/MessageFormatter.php
*/
'http' => [
'max_retries' => 1,
'retry_delay' => 500,
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
],
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => $config['oauth_callback'],
],
];
}
}

查看文件

@@ -0,0 +1,27 @@
<?php
namespace addons\wechat\library;
use addons\signin\model\Signin;
use addons\third\model\Third;
use app\common\model\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use fast\Date;
use fast\Http;
use fast\Random;
use think\Session;
use think\Config;
/**
* 微信服务类
*/
interface Response
{
public function available();
public function config();
public function response($obj, $openid, $message, $content, $context, $matches = null, $keyword = '');
}

查看文件

@@ -0,0 +1,129 @@
<?php
namespace addons\wechat\library;
use addons\signin\model\Signin;
use addons\third\model\Third;
use app\common\model\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use fast\Date;
use fast\Http;
use fast\Random;
use think\Session;
use think\Config;
/**
* 微信服务类
*/
class Wechat
{
protected $appList = [];
public static function getAppList()
{
$appList = [];
$dirList = scandir(__DIR__ . '/response');
foreach ($dirList as $key => $value) {
if (in_array($value, ['.', '..'])) {
unset($dirList[$key]);
} else {
$name = substr($value, 0, -4);
$className = '\\addons\\wechat\\library\\response\\' . $name;
$appList[strtolower($name)] = new $className();
}
}
return $appList;
}
public static function appConfig()
{
$appConfigList = [];
$appList = self::getAppList();
foreach ($appList as $key => $value) {
if (method_exists($value, 'config')) {
$appConfigList[$key] = $value->config();
$appConfigList[$key]['available'] = $value->available();
$appConfigList[$key]['name'] .= ($appConfigList[$key]['available'] ? '' : '(未安装或未启用)');
}
}
return $appConfigList;
}
/**
* 应用交互
* @return array|bool|mixed|string
*/
public function response($obj, $openid, $message, $content, $context, $matches = null)
{
if (isset($content['app'])) {
$response = '';
$entry = null;
$keyword = isset($content['searchregexindex']) && $content['searchregexindex'] > -1 && $matches && isset($matches[$content['searchregexindex']])
? $matches[$content['searchregexindex']] : $message;
$appList = self::getAppList();
if (isset($appList[$content['app']])) {
$app = $appList[$content['app']];
if (method_exists($app, 'response')) {
$entry = $app->response($obj, $openid, $message, $content, $context, $matches, $keyword);
}
}
if ($entry) {
if (is_string($entry)) {
return $entry;
}
if ($entry instanceof News) {
$news = $entry;
} elseif ($entry instanceof NewsItem) {
$news = new News([$entry]);
} elseif (is_array($entry) || $entry instanceof \think\Model) {
if (isset($entry['title']) || isset($entry['description'])) {
$items = [
new NewsItem([
'title' => $entry['title'] ?? ($entry['nickname'] ?? ''),
'description' => $entry['description'] ?? '',
'url' => $entry['fullurl'],
'image' => cdnurl($entry['image'], true),
]),
];
$news = new News($items);
} else {
$items = [];
foreach ($entry as $item) {
if ($item instanceof NewsItem) {
$items[] = $item;
} else {
$items[] = new NewsItem([
'title' => $item['title'] ?? ($item['nickname'] ?? ''),
'description' => $item['description'] ?? '',
'url' => $item['fullurl'],
'image' => cdnurl($item['image'], true),
]);
}
}
$news = new News($items);
}
}
if (isset($news)) {
$response = $news;
}
}
} else {
$response = $content['content'] ?? '';
}
return $response;
}
/**
* 获取Token
*/
public static function getAccessToken()
{
$app = Factory::officialAccount(\addons\wechat\library\Config::load());
$accessToken = $app->access_token;
$token = $accessToken ? $accessToken->getToken() : [];
return $token['access_token'] ?? '';
}
}

查看文件

@@ -0,0 +1,94 @@
<?php
namespace addons\wechat\library\response;
use addons\wechat\library\Response;
class Ask implements Response
{
public function available()
{
$info = get_addon_info('ask');
return $info && $info['state'];
}
public function config()
{
$disabled = $this->available() ? '' : 'disabled="disabled"';
return [
'name' => '知识付费问答社区',
'config' => [
[
'type' => 'text',
'caption' => '问题ID',
'field' => 'question_id',
'extend' => 'class="form-control selectpage" data-source="ask/question/index" data-field="title" ' . $disabled,
'options' => ''
],
[
'type' => 'text',
'caption' => '文章ID',
'field' => 'article_id',
'extend' => 'class="form-control selectpage" data-source="ask/article/index" data-field="title"' . $disabled,
'options' => ''
],
[
'type' => 'radio',
'caption' => '开启搜索问题',
'field' => 'searchquestion',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'radio',
'caption' => '开启搜索文章',
'field' => 'searcharticle',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
]
]
];
}
public function response($obj, $openid, $message, $content, $context, $matches = null, $keyword = '')
{
if (!$this->available()) {
return "请先在后台管理安装并启用《知识付费问答》插件";
}
if (isset($content['question_id']) && $content['question_id']) {
$entry = \addons\ask\model\Question::get($content['question_id']);
} elseif (isset($content['article_id']) && $content['article_id']) {
$entry = \addons\ask\model\Article::get($content['article_id']);
}
if (!$entry && $content['searchquestion']) {
$entry = \addons\ask\model\Question::where("title", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searcharticle']) {
$entry = \addons\ask\model\Article::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息";
}
return $entry;
}
}

查看文件

@@ -0,0 +1,71 @@
<?php
namespace addons\wechat\library\response;
use addons\wechat\library\Response;
class Blog implements Response
{
public function available()
{
$info = get_addon_info('blog');
return $info && $info['state'];
}
public function config()
{
$disabled = $this->available() ? '' : 'disabled="disabled"';
return [
'name' => '简单博客',
'config' => [
[
'type' => 'text',
'caption' => '博客日志ID',
'field' => 'post_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="blog/post/index" data-field="title" ' . $disabled,
'options' => '',
],
[
'type' => 'radio',
'caption' => '开启搜索日志',
'field' => 'searchpost',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
]
]
];
}
public function response($obj, $openid, $message, $content, $context, $matches = null, $keyword = '')
{
if (!$this->available()) {
return "请先在后台管理安装并启用《简单博客》插件";
}
$entry = \addons\blog\model\Post::get($content['post_id']);
if ($entry) {
$entry['image'] = $entry['thumb'];
}
if (!$entry && $content['searchpost']) {
$entry = \addons\blog\model\Post::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息$keyword" . json_encode($matches);
}
return $entry;
}
}

查看文件

@@ -0,0 +1,119 @@
<?php
namespace addons\wechat\library\response;
use addons\wechat\library\Response;
class Cms implements Response
{
public function available()
{
$info = get_addon_info('cms');
return $info && $info['state'];
}
public function config()
{
$disabled = $this->available() ? '' : 'disabled="disabled"';
return [
'name' => 'CMS内容管理系统',
'config' => [
[
'type' => 'text',
'caption' => '文章ID',
'field' => 'archives_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="cms/archives/index" data-field="title" ' . $disabled,
'options' => ''
],
[
'type' => 'text',
'caption' => '单页ID',
'field' => 'page_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="cms/page/index" data-field="title" ' . $disabled,
'options' => ''
],
[
'type' => 'text',
'caption' => '专题ID',
'field' => 'special_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="cms/special/index" data-field="title" ' . $disabled,
'options' => ''
],
[
'type' => 'radio',
'caption' => '开启搜索文章',
'field' => 'searcharchives',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'radio',
'caption' => '开启搜索单页',
'field' => 'searchpage',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'radio',
'caption' => '开启搜索专题',
'field' => 'searchspecial',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
]
]
];
}
public function response($obj, $openid, $message, $content, $context, $matches = null, $keyword = '')
{
if (!$this->available()) {
return "请先在后台管理安装并启用《CMS内容管理系统》插件";
}
$entry = null;
if (isset($content['archives_id']) && $content['archives_id']) {
$entry = \addons\cms\model\Archives::get($content['archives_id']);
} elseif (isset($content['page_id']) && $content['page_id']) {
$entry = \addons\cms\model\Page::get($content['page_id']);
} elseif (isset($content['special_id']) && $content['special_id']) {
$entry = \addons\cms\model\Special::get($content['special_id']);
}
if (!$entry && $content['searcharchives']) {
$entry = \addons\cms\model\Archives::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searchpage']) {
$entry = \addons\cms\model\Page::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searchspecial']) {
$entry = \addons\cms\model\Special::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息";
}
return $entry;
}
}

查看文件

@@ -0,0 +1,70 @@
<?php
namespace addons\wechat\library\response;
use addons\signin\library\Service;
use addons\third\model\Third;
use addons\wechat\library\Response;
use app\common\model\User;
use fast\Date;
class Signin implements Response
{
public function available()
{
$info = get_addon_info('signin');
return $info && $info['state'];
}
public function config()
{
$disabled = $this->available() ? '' : 'disabled="disabled"';
return [
'name' => '会员签到送积分',
'config' => []
];
}
public function response($obj, $openid, $message, $content, $context, $matches = null, $keyword = '')
{
$signinInfo = get_addon_info('signin');
if (!$this->available()) {
return "请先在后台管理安装并启用《会员签到》插件";
}
$thirdInfo = get_addon_info('third');
if (!$thirdInfo || !$thirdInfo['state']) {
return "请先在后台管理安装并启用《第三方登录》插件";
}
$user = $this->getUserByOpenid($openid);
if (!$user) {
return "请先在会员中心绑定微信登录,<a href='" . addon_url('third/index/connect', [':platform' => 'wechat'], true, true) . "'>点击这里绑定</a>";
}
if (version_compare($signinInfo['version'], '1.0.5', '<')) {
return "请升级《会员签到》插件到最新版本";
}
$result = Service::dosign($user->id);
if (isset($result['errmsg'])) {
return $result['errmsg'];
} else {
return '签到成功!连续签到' . $result['successions'] . '天!获得' . $result['score'] . '积分';
}
}
/**
* 根据Openid获取用户信息
* @param string $openid 微信OpenID
* @return User|null
*/
public function getUserByOpenid($openid)
{
$third = Third::where('platform', 'wechat')->where('openid', $openid)->find();
if ($third && $third->user_id) {
return User::get($third->user_id);
}
return null;
}
}

查看文件

@@ -0,0 +1,96 @@
<?php
namespace addons\wechat\library\response;
use addons\wechat\library\Response;
class Vote implements Response
{
public function available()
{
$info = get_addon_info('vote');
return $info && $info['state'];
}
public function config()
{
$disabled = $this->available() ? '' : 'disabled="disabled"';
return [
'name' => '在线投票系统',
'config' => [
[
'type' => 'text',
'caption' => '投票主题ID',
'field' => 'subject_id',
'extend' => 'class="form-control selectpage" data-source="vote/subject/index" data-field="title" ' . $disabled,
'rule' => '',
'options' => ''
],
[
'type' => 'text',
'caption' => '参赛人员ID',
'field' => 'player_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="vote/player/index" data-field="nickname" ' . $disabled,
'options' => ''
],
[
'type' => 'radio',
'caption' => '开启搜索主题',
'field' => 'searchsubject',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'radio',
'caption' => '开启搜索参赛人员',
'field' => 'searchplayer',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
],
[
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
]
]
];
}
public function response($obj, $openid, $message, $content, $context, $matches = null, $keyword = '')
{
if (!$this->available()) {
return "请先在后台管理安装并启用《在线投票系统》插件";
}
if (isset($content['subject_id']) && $content['subject_id']) {
$entry = \addons\vote\model\Subject::all($content['subject_id']);
} elseif (isset($content['player_id']) && $content['player_id']) {
$entry = \addons\vote\model\Player::all($content['player_id']);
}
if (!$entry && $content['searchsubject']) {
$entry = \addons\vote\model\Subject::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searchplayer']) {
$entry = \addons\vote\model\Player::where("nickname", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息";
}
return $entry;
}
}

查看文件

@@ -0,0 +1,16 @@
<?php
namespace addons\wechat\model;
use think\Model;
class WechatAutoreply extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}

查看文件

@@ -0,0 +1,77 @@
<?php
namespace addons\wechat\model;
use fast\Random;
use think\Cookie;
use think\Model;
class WechatCaptcha extends Model
{
// 表名
protected $name = 'wechat_captcha';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = '';
// 追加属性
protected $append = [
];
/**
* 发送验证码
* @param $openid string 用户OpenID
* @param $event string 事件
* @param $ip string IP地址
* @param $context string 上下文
* @return string
*/
public static function send($openid, $event, $ip, $context = '')
{
$captcha = self::where(['openid' => $openid, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
if ($captcha) {
return "验证码发送速度过快,请稍后重试";
}
$code = Random::numeric(config('captcha.length'));
$data = [
'event' => $event,
'openid' => $openid,
'code' => $code,
'ip' => $ip,
'context' => $context
];
self::create($data);
return "你的验证码是:{$code},2分钟内输入有效";
}
/**
* 检测验证码
* @param $code string 验证码
* @param $event string 事件
* @param $ip string IP
* @param $afterdelete bool 是否删除验证码
* @return bool
*/
public static function check($code, $event, $ip = null, $afterdelete = true)
{
$ip = is_null($ip) ? request()->ip() : $ip;
$context = Cookie::get('captcha_' . $event);
$captcha = self::where(['ip' => $ip, 'event' => $event, 'context' => $context])->whereTime('createtime', '-2 minutes')->find();
if ($captcha && $captcha->code == $code && $captcha->times < 10 && $context) {
$captcha->setInc("times");
if ($afterdelete) {
$captcha->delete();
}
return true;
}
//验证大于10次或超时
if ($captcha && ($captcha->times >= 10 || time() - $captcha->createtime > 120)) {
$captcha->delete();
}
return false;
}
}

查看文件

@@ -0,0 +1,32 @@
<?php
namespace addons\wechat\model;
use think\Model;
class WechatConfig extends Model
{
// 表名,不含前缀
public $name = 'wechat_config';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
];
/**
* 读取指定配置名称的值
* @param string $name
* @return string
*/
public static function getValue($name)
{
$item = self::get(['name' => $name]);
return $item ? $item->value : '';
}
}

查看文件

@@ -0,0 +1,16 @@
<?php
namespace addons\wechat\model;
use think\Model;
class WechatContext extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}

查看文件

@@ -0,0 +1,16 @@
<?php
namespace addons\wechat\model;
use think\Model;
class WechatResponse extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}