338 lines
12 KiB
PHP
338 lines
12 KiB
PHP
<?php
|
|
/**
|
|
* SAAS应用系统 --- 十年开发经验汇集巨献!
|
|
* ==========================================================
|
|
* Copy right 2020-2050 成都众联思索科技有限公司,保留所有权利。
|
|
* ----------------------------------------------------------
|
|
* 官方网址: https://www.zoomtk.com
|
|
* 这不是自由软件!未经允许不得用于商业目或程序代码摘取及修改。
|
|
* 任何企业和个人不允许对程序代码以任何形式任何目的再发布传播。
|
|
* 唯一发布渠道www.zoomtk.com;非官方渠道统一视为侵权行为。
|
|
* ==========================================================
|
|
*/
|
|
|
|
namespace addon\wxoplatform\model;
|
|
|
|
use addon\weapp\model\Weapp;
|
|
use addon\wechat\model\Wechat;
|
|
use addon\wechat\model\Wechat as WechatModel;
|
|
use addon\wechat\model\WechatRequest;
|
|
use app\model\system\Servicer as ServicerModel;
|
|
use EasyWeChat\Factory;
|
|
use app\model\BaseModel;
|
|
use EasyWeChat\Kernel\Messages\Text;
|
|
use EasyWeChat\Kernel\Messages\Transfer;
|
|
use EasyWeChat\OpenPlatform\Server\Guard;
|
|
use EasyWeChat\OpenPlatform\Auth\VerifyTicket;
|
|
use think\Exception;
|
|
use think\facade\Cache;
|
|
|
|
/**
|
|
* 微信开放平台
|
|
*/
|
|
class Oplatform extends BaseModel
|
|
{
|
|
|
|
|
|
public $app;//微信公众对象
|
|
public $appConfig = [];//微信公众对象
|
|
public $openConfig = [];//微信公众对象
|
|
|
|
public function __construct($site_id = 0, $appid = '')
|
|
{
|
|
//微信配置
|
|
$config_model = new Config();
|
|
$config_result = $config_model->getOplatformConfig($site_id);
|
|
$config = $config_result["data"];
|
|
if (!empty($config)) {
|
|
$config_info = $config["value"];
|
|
$this->openConfig = $config_info;
|
|
}
|
|
$config = [
|
|
'app_id' => $config_info["appid"] ?? '',
|
|
'secret' => $config_info["secret"] ?? '',
|
|
'token' => $config_info["token"] ?? '',
|
|
'aes_key' => $config_info["aes_key"] ?? '',
|
|
'log' => [
|
|
'level' => 'debug',
|
|
'permission' => 0777,
|
|
'file' => 'runtime/log/wechat/oplatform.logs',
|
|
],
|
|
'http' => [
|
|
'max_retries' => 1,
|
|
'retry_delay' => 500,
|
|
'timeout' => 30,
|
|
],
|
|
];
|
|
$this->app = Factory::openPlatform($config);
|
|
$this->app->rebind('request', request());
|
|
$this->app->rebind('cache', Cache::store('redis_public'));
|
|
$this->SetVerifyTicket();
|
|
}
|
|
|
|
use MiniCode;
|
|
|
|
/**
|
|
* 开放平台获取授权
|
|
* @param $param
|
|
* @return \EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Account\Client|\EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Account\Client
|
|
*/
|
|
public function app($param)
|
|
{
|
|
if ($param["type"] == "wechat") {
|
|
// 代公众号实现业务
|
|
$officialAccount = $this->app->officialAccount($param["authorizer_appid"], $param["authorizer_refresh_token"] ?? null);
|
|
$account = $officialAccount;
|
|
} else {
|
|
// 代小程序实现业务
|
|
$miniProgram = $this->app->miniProgram($param["authorizer_appid"], $param["authorizer_refresh_token"] ?? null);
|
|
$account = $miniProgram;
|
|
}
|
|
return $account;
|
|
}
|
|
|
|
/**
|
|
* 获取用户授权页 URL
|
|
* @param $param
|
|
* @return array
|
|
*/
|
|
public function getPreAuthorizationUrl($param = [], $optional = [])
|
|
{
|
|
try {
|
|
$result = $this->app->getPreAuthorizationUrl($param['callback'], $optional);
|
|
return $this->success($result);
|
|
} catch (\Exception $e) {
|
|
return $this->error([], $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 使用授权码换取接口调用凭据和授权信息
|
|
* @param $param
|
|
* @return array
|
|
*/
|
|
public function handleAuthorize($param = [])
|
|
{
|
|
try {
|
|
$code = $param["code"] ?? null;
|
|
$result = $this->app->handleAuthorize($code);
|
|
if (isset($result['errcode']) && $result['errcode'] != 0) {
|
|
return $this->error($result, $result["errmsg"]);
|
|
}
|
|
return $this->success($result);
|
|
} catch (\Exception $e) {
|
|
return $this->error([], $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取授权方的帐号基本信息
|
|
* @param array $param
|
|
*/
|
|
public function getAuthorizer($param = [])
|
|
{
|
|
try {
|
|
$result = $this->app->getAuthorizer($param["authorizer_appid"]);
|
|
if (isset($result['errcode']) && $result['errcode'] != 0) {
|
|
return $this->error($result, $result["errmsg"]);
|
|
}
|
|
return $this->success($result);
|
|
} catch (\Exception $e) {
|
|
return $this->error([], $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 授权回调事件响应 https://www.easywechat.com
|
|
*/
|
|
public function server()
|
|
{
|
|
$server = $this->app->server;
|
|
|
|
$server->push(function ($message) {
|
|
$component_verify_ticket = $message['ComponentVerifyTicket'];
|
|
// file_put_contents(root_path() . 'runtime/log/' . date('YmdHis', time()) . 'ComponentVerifyTicket.TXT', $component_verify_ticket);
|
|
Cache::set('ComponentVerifyTicket', $component_verify_ticket);
|
|
$verify_ticket = new VerifyTicket($this->app);
|
|
$verify_ticket->setTicket(Cache::get('ComponentVerifyTicket'));
|
|
$config_model = new Config();
|
|
$config_result = $config_model->getOplatformConfig();
|
|
$data = $config_result['data']["value"];
|
|
$data['ComponentVerifyTicket'] = $component_verify_ticket;
|
|
$data['VerifyTicketTime'] = time();
|
|
$config_model->setOplatformConfig($data, 1);
|
|
}, Guard::EVENT_COMPONENT_VERIFY_TICKET);
|
|
|
|
$server->push(function ($message) { //完成小程序注册授权
|
|
if (isset($message['InfoType']) && $message['InfoType'] == 'notify_third_fasteregister') {
|
|
event('WeappRegister', $message);
|
|
}
|
|
}, Guard::EVENT_THIRD_FAST_REGISTERED);
|
|
|
|
// 授权成功事件
|
|
$server->push(function ($message) {
|
|
|
|
}, Guard::EVENT_AUTHORIZED);
|
|
|
|
// 小程序认证事件
|
|
$server->push(function ($message) {
|
|
|
|
file_put_contents(root_path() . 'runtime/log/' . date('YmdHis', time()) . 'notify_3rd_wxa_auth.txt', json_encode($message, JSON_UNESCAPED_UNICODE));
|
|
|
|
}, 'notify_3rd_wxa_auth');
|
|
|
|
/***
|
|
* 授权更新
|
|
*/
|
|
$server->push(function ($message) {
|
|
|
|
|
|
}, Guard::EVENT_UPDATE_AUTHORIZED);
|
|
// 授权取消事件
|
|
$server->push(function ($message) {
|
|
$appid = $message['AuthorizerAppid'];
|
|
model('config')->update(['value' => ''], [['app_module', '=', 'shop'], ['config_key', 'in', ['WECHAT_CONFIG', 'WEAPP_CONFIG']], ['value', 'like', '%' . $appid . '%'], ['value', 'like', '%is_authopen%']]);
|
|
Cache::tag("config")->clear();
|
|
}, Guard::EVENT_UNAUTHORIZED);
|
|
|
|
return $server->serve();
|
|
}
|
|
|
|
/***
|
|
* 设置验证
|
|
* @param $ComponentVerifyTicket
|
|
* @return void
|
|
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
|
|
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException
|
|
*/
|
|
public function SetVerifyTicket()
|
|
{
|
|
$verify_ticket = new VerifyTicket($this->app);
|
|
try {
|
|
$verify_ticket->getTicket();
|
|
} catch (\Exception $e) {
|
|
|
|
|
|
$where = [['site_id', '=', 0], ['app_module', '=', 'admin'], ['config_key', '=', 'OPLATFORM_CONFIG']];
|
|
$info = model('config')->getValue($where, 'value');
|
|
if ($info) {
|
|
$v = json_decode($info, true);
|
|
$verify_ticket->setTicket($v['ComponentVerifyTicket'] ?? '');
|
|
}
|
|
}
|
|
}
|
|
|
|
/***
|
|
* 全网验证
|
|
*/
|
|
public function openCheck($appid)
|
|
{
|
|
$openPlatform = $this->app;
|
|
$server = $openPlatform->server;
|
|
$message = $server->getMessage();
|
|
if (isset($message['MsgType']) && $message['MsgType'] == 'text') {
|
|
if (strpos($message['Content'], 'QUERY_AUTH_CODE') !== false) {
|
|
$query_auth_code = str_replace('QUERY_AUTH_CODE:', '', $message['Content']);
|
|
$authorizerInfo = $openPlatform->handleAuthorize($query_auth_code)['authorization_info'];
|
|
cache($appid, $authorizerInfo);
|
|
$content = "{$query_auth_code}_from_api";
|
|
$curOfficialAccount = $openPlatform->officialAccount(
|
|
$authorizerInfo['authorizer_appid'],
|
|
$authorizerInfo['authorizer_refresh_token']
|
|
);
|
|
$curOfficialAccount->customer_service->message($content)
|
|
->from($message['ToUserName'])->to($message['FromUserName'])->send();
|
|
}
|
|
if ($message['Content'] == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
|
|
$authorizerInfo = cache($appid);
|
|
$curOfficialAccount = $openPlatform->officialAccount($appid, $authorizerInfo['authorizer_refresh_token']);
|
|
$curOfficialAccount->server->push(function () use ($message) {
|
|
return new Text('TESTCOMPONENT_MSG_TYPE_TEXT_callback');
|
|
});
|
|
$curOfficialAccount->server->serve()->send();
|
|
}
|
|
} else {
|
|
$server->serve()->send();
|
|
}
|
|
}
|
|
|
|
/***
|
|
* 微信消息事件处理
|
|
* @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
|
|
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
|
|
* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
|
|
* @throws \GuzzleHttp\Exception\GuzzleException
|
|
* @throws \think\db\exception\DataNotFoundException
|
|
* @throws \think\db\exception\DbException
|
|
* @throws \think\db\exception\ModelNotFoundException
|
|
*/
|
|
public function MsgEvent()
|
|
{
|
|
$openPlatform = $this->app;
|
|
$server = $openPlatform->server;
|
|
$message = $server->getMessage();
|
|
if ($message && isset($message['Event'])) {
|
|
switch ($message['Event']) {
|
|
case 'weapp_audit_fail':
|
|
case 'weapp_audit_success'://小程序审核
|
|
event('WeappAuditEvent', $message);
|
|
$server->serve()->send();
|
|
break;
|
|
case 'weapp_audit_delay':
|
|
case 'wxa_nickname_audit':
|
|
$server->serve()->send();
|
|
case 'wxa_privacy_apply':
|
|
default:
|
|
if ($this->appConfig['app_type'] == 'wechat') {
|
|
$wechat = new WechatModel($this->appConfig['site_id']);
|
|
$wechat->relateWeixin();
|
|
}
|
|
}
|
|
} else {
|
|
if ($this->appConfig['config_key'] == 'WEAPP_CONFIG') { //转发客服消息
|
|
$servicer_model = new ServicerModel();
|
|
$config = $servicer_model->getServicerConfig($this->appConfig['site_id'], 'shop')['data']['value'];
|
|
if (isset($config['system']) && !$config['system']) {
|
|
// 转发收到的消息给客服
|
|
$app = $this->app->miniProgram($this->appConfig['value']['appid'], $this->appConfig['value']['authorizer_refresh_token']);
|
|
$server = $app->server;
|
|
$server->push(function () {
|
|
return new Transfer();
|
|
});
|
|
$server->serve()->send();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 消息通知
|
|
* @param $appid
|
|
*/
|
|
public function message($appid)
|
|
{
|
|
try {
|
|
$where = [
|
|
['config_key', 'in', ['WECHAT_CONFIG', 'WEAPP_CONFIG']],
|
|
['value', 'like', '%' . $appid . '%'],
|
|
['value', 'like', '%is_authopen%']
|
|
];
|
|
// $site_id=Db::name('config')->where($where)->order('modify_time desc')->value('site_id');
|
|
// $site_id=0;
|
|
//公众号处理
|
|
$officialAccount = $this->app(['authorizer_appid' => $appid, 'type' => 'wechat']);
|
|
$wechat_model = new Wechat(0);
|
|
$wechat_model->app = $officialAccount;
|
|
$wechat_model->relateWeixin();
|
|
//微信处理
|
|
$officialAccount = $this->app(['authorizer_appid' => $appid, 'type' => 'weapp']);
|
|
$weapp_model = new Weapp(0);
|
|
$weapp_model->app = $officialAccount;
|
|
$weapp_model->relateWeixin();
|
|
} catch (\Exception $e) {
|
|
|
|
}
|
|
}
|
|
}
|