Commit b6928345 authored by clone's avatar clone

去掉些没用的冗余

parent db76a4a3
......@@ -6,7 +6,8 @@ namespace app\index\controller\member;
* Date: 17-12-3
* Time: 下午1:03
*/
use app\index\behavior\Basic;
use app\index\extend\Basic;
class Index extends Basic {
public function member(){
return view('member/member',['title'=>'thinkphp']);
......
<?php
namespace app\index\behavior;
namespace app\index\extend;
/**
* Created by PhpStorm.
* User: zw
......
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Db;
use think\Request;
/**
* 基础数据服务
* Class DataService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2017/03/22 15:32
*/
class DataService
{
/**
* 数据签名
* @param array $data
* @param string $apikey
* @param string $prefix
* @return string
*/
public static function sign(&$data, $apikey = '', $prefix = '')
{
$data['_SIGNSTR_'] = strtoupper(isset($data['_SIGNSTR_']) ? $data['_SIGNSTR_'] : substr(md5(uniqid()), 22));
ksort($data);
foreach (array_values($data) as $string) {
is_array($string) || ($prefix .= "{$string}");
}
return strtoupper(md5($prefix . $apikey . $data['_SIGNSTR_']));
}
/**
* 删除指定序号
* @param string $sequence
* @param string $type
* @return bool
*/
public static function deleteSequence($sequence, $type = 'SYSTEM')
{
$data = ['sequence' => $sequence, 'type' => strtoupper($type)];
return Db::name('SystemSequence')->where($data)->delete();
}
/**
* 生成唯一序号 (失败返回 NULL )
* @param int $length 序号长度
* @param string $type 序号顾类型
* @return string
*/
public static function createSequence($length = 10, $type = 'SYSTEM')
{
$times = 0;
while ($times++ < 10) {
list($i, $sequence) = [0, ''];
while ($i++ < $length) {
$sequence .= ($i <= 1 ? rand(1, 9) : rand(0, 9));
}
$data = ['sequence' => $sequence, 'type' => strtoupper($type)];
if (Db::name('SystemSequence')->where($data)->count() < 1) {
if (Db::name('SystemSequence')->insert($data) !== false) {
return $sequence;
}
}
}
return null;
}
/**
* 数据增量保存
* @param \think\db\Query|string $dbQuery 数据查询对象
* @param array $data 需要保存或更新的数据
* @param string $key 条件主键限制
* @param array $where 其它的where条件
* @return bool
*/
public static function save($dbQuery, $data, $key = 'id', $where = [])
{
$db = is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery;
$where[$key] = isset($data[$key]) ? $data[$key] : '';
if ($db->where($where)->count() > 0) {
return $db->where($where)->update($data) !== false;
}
return $db->insert($data) !== false;
}
/**
* 更新数据表内容
* @param \think\db\Query|string $dbQuery 数据查询对象
* @param array $where 额外查询条件
* @return bool|null
*/
public static function update(&$dbQuery, $where = [])
{
$request = Request::instance();
$db = is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery;
$ids = explode(',', $request->post('id', ''));
$field = $request->post('field', '');
$value = $request->post('value', '');
$pk = $db->getPk(['table' => $db->getTable()]);
$where[empty($pk) ? 'id' : $pk] = ['in', $ids];
// 删除模式,如果存在 is_deleted 字段使用软删除
if ($field === 'delete') {
if (method_exists($db, 'getTableFields')) {
if (in_array('is_deleted', $db->getTableFields($db->getTable()))) {
return false !== $db->where($where)->update(['is_deleted' => 1]);
}
}
return false !== $db->where($where)->delete();
}
// 更新模式,更新指定字段内容
return false !== $db->where($where)->update([$field => $value]);
}
}
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Db;
use think\Request;
/**
* 扩展服务
* Class ExtendService
* @package service
*/
class ExtendService
{
/**
* 发送短信验证码
* @param string $phone 手机号
* @param string $content 短信内容
* @param string $productid 短信通道ID
* @return bool
*/
public static function sendSms($phone, $content, $productid = '676767')
{
$tkey = date("YmdHis");
$data = [
'username' => sysconf('sms_username'), 'tkey' => $tkey,
'content' => $content, 'mobile' => $phone, 'productid' => $productid,
'password' => md5(md5(sysconf('sms_password')) . $tkey),
];
$result = HttpService::post('http://www.ztsms.cn/sendNSms.do', $data);
list($code, $msg) = explode(',', $result . ',');
$insert = ['phone' => $phone, 'content' => $content, 'result' => $result];
Db::name('MemberSmsHistory')->insert($insert);
return intval($code) === 1;
}
/**
* 查询短信余额
* @return array
*/
public static function querySmsBalance()
{
$tkey = date("YmdHis");
$data = [
'username' => sysconf('sms_username'), 'tkey' => $tkey,
'password' => md5(md5(sysconf('sms_password')) . $tkey),
];
$result = HttpService::post('http://www.ztsms.cn/balanceN.do', $data);
if ($result > -1) {
return ['code' => 1, 'num' => $result, 'msg' => '获取短信剩余条数成功!'];
} elseif ($result > -2) {
return ['code' => 0, 'num' => '0', 'msg' => '用户名或者密码不正确!'];
} elseif ($result > -3) {
return ['code' => 0, 'num' => '0', 'msg' => 'tkey不正确!'];
} elseif ($result > -4) {
return ['code' => 0, 'num' => '0', 'msg' => '用户不存在或用户停用!'];
}
}
/**
* 通用物流单查询
* @param string $code 快递物流编号
* @return array
*/
public static function expressByAuto($code)
{
list($result, $client_ip) = [[], Request::instance()->ip()];
$header = ['Host' => 'www.kuaidi100.com', 'CLIENT-IP' => $client_ip, 'X-FORWARDED-FOR' => $client_ip];
$autoResult = HttpService::get("http://www.kuaidi100.com/autonumber/autoComNum?text={$code}", [], 30, $header);
foreach (json_decode($autoResult)->auto as $vo) {
$result[$vo->comCode] = self::express($vo->comCode, $code);
}
return $result;
}
/**
* 查询物流信息
* @param string $express_code 快递公司编辑
* @param string $express_no 快递物流编号
* @return array
*/
public static function express($express_code, $express_no)
{
list($microtime, $client_ip) = [microtime(true), Request::instance()->ip()];
$header = ['Host' => 'www.kuaidi100.com', 'CLIENT-IP' => $client_ip, 'X-FORWARDED-FOR' => $client_ip];
$location = "http://www.kuaidi100.com/query?type={$express_code}&postid={$express_no}&id=1&valicode=&temp={$microtime}";
return json_decode(HttpService::get($location, [], 30, $header), true);
}
}
\ No newline at end of file
This diff is collapsed.
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use CURLFile;
/**
* HTTP请求服务
* Class HttpService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2017/03/22 15:32
*/
class HttpService
{
/**
* HTTP GET 请求
* @param string $url 请求的URL地址
* @param array $data GET参数
* @param int $second 设置超时时间(默认30秒)
* @param array $header 请求Header信息
* @return bool|string
*/
public static function get($url, $data = [], $second = 30, $header = [])
{
if (!empty($data)) {
$url .= (stripos($url, '?') === false ? '?' : '&');
$url .= (is_array($data) ? http_build_query($data) : $data);
}
$curl = curl_init();
self::applyHttp($curl, $url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, $second);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if (!empty($header)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
}
list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
return (intval($status["http_code"]) === 200) ? $content : false;
}
/**
* POST 请求(支持文件上传)
* @param string $url HTTP请求URL地址
* @param array|string $data POST提交的数据
* @param int $second 请求超时时间
* @param array $header 请求Header信息
* @return bool|string
*/
static public function post($url, $data = [], $second = 30, $header = [])
{
$curl = curl_init();
self::applyData($data);
self::applyHttp($curl, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, $second);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
if (!empty($header)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
}
list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
return (intval($status["http_code"]) === 200) ? $content : false;
}
/**
* 设置SSL参数
* @param $curl
* @param string $url
*/
private static function applyHttp(&$curl, $url)
{
if (stripos($url, "https") === 0) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSLVERSION, 1);
}
}
/**
* Post 数据过滤处理
* @param array $data
* @param bool $isBuild
* @return string
*/
private static function applyData(&$data, $isBuild = true)
{
if (!is_array($data)) {
return null;
}
foreach ($data as &$value) {
is_array($value) && $isBuild = true;
if (!(is_string($value) && strlen($value) > 0 && $value[0] === '@')) {
continue;
}
if (!file_exists(($file = realpath(trim($value, '@'))))) {
continue;
}
list($isBuild, $mime) = [false, FileService::getFileMine(pathinfo($file, 4))];
if (class_exists('CURLFile', false)) {
$value = new CURLFile($file, $mime);
} else {
$value = "{$value};type={$mime}";
}
}
$isBuild && $data = http_build_query($data);
}
}
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Db;
use think\Request;
/**
* 操作日志服务
* Class LogService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2017/03/24 13:25
*/
class LogService
{
/**
* 获取数据操作对象
* @return \think\db\Query
*/
protected static function db()
{
return Db::name('SystemLog');
}
/**
* 写入操作日志
* @param string $action
* @param string $content
* @return bool
*/
public static function write($action = '行为', $content = "内容描述")
{
$request = Request::instance();
$node = strtolower(join('/', [$request->module(), $request->controller(), $request->action()]));
$data = ['ip' => $request->ip(), 'node' => $node, 'username' => session('user.username') . '', 'action' => $action, 'content' => $content];
return self::db()->insert($data) !== false;
}
}
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Db;
/**
* 系统权限节点读取器
* Class NodeService
* @package extend
* @author Anyon <zoujingli@qq.com>
* @date 2017/05/08 11:28
*/
class NodeService
{
/**
* 应用用户权限节点
* @return bool
*/
public static function applyAuthNode()
{
cache('need_access_node', null);
if (($userid = session('user.id'))) {
session('user', Db::name('SystemUser')->where('id', $userid)->find());
}
if (($authorize = session('user.authorize'))) {
$where = ['id' => ['in', explode(',', $authorize)], 'status' => '1'];
$authorizeids = Db::name('SystemAuth')->where($where)->column('id');
if (empty($authorizeids)) {
return session('user.nodes', []);
}
$nodes = Db::name('SystemAuthNode')->whereIn('auth', $authorizeids)->column('node');
return session('user.nodes', $nodes);
}
return false;
}
/**
* 获取授权节点
* @return array
*/
public static function getAuthNode()
{
$nodes = cache('need_access_node');
if (empty($nodes)) {
$nodes = Db::name('SystemNode')->where(['is_auth' => '1'])->column('node');
cache('need_access_node', $nodes);
}
return $nodes;
}
/**
* 检查用户节点权限
* @param string $node 节点
* @return bool
*/
public static function checkAuthNode($node)
{
list($module, $controller, $action) = explode('/', str_replace(['?', '=', '&'], '/', $node . '///'));
$auth_node = strtolower(trim("{$module}/{$controller}/{$action}", '/'));
if (session('user.username') === 'admin' || stripos($node, 'admin/index') === 0) {
return true;
}
if (!in_array($auth_node, self::getAuthNode())) {
return true;
}
return in_array($auth_node, (array)session('user.nodes'));
}
/**
* 获取系统代码节点
* @param array $nodes
* @return array
*/
public static function get($nodes = [])
{
$alias = Db::name('SystemNode')->column('node,is_menu,is_auth,is_login,title');
$ignore = ['index', 'wechat/api', 'wechat/notify', 'wechat/review', 'admin/plugs', 'admin/login', 'admin/index'];
foreach (self::getNodeTree(APP_PATH) as $thr) {
foreach ($ignore as $str) {
if (stripos($thr, $str) === 0) {
continue 2;
}
}
$tmp = explode('/', $thr);
list($one, $two) = ["{$tmp[0]}", "{$tmp[0]}/{$tmp[1]}"];
$nodes[$one] = array_merge(isset($alias[$one]) ? $alias[$one] : ['node' => $one, 'title' => '', 'is_menu' => 0, 'is_auth' => 0, 'is_login' => 0], ['pnode' => '']);
$nodes[$two] = array_merge(isset($alias[$two]) ? $alias[$two] : ['node' => $two, 'title' => '', 'is_menu' => 0, 'is_auth' => 0, 'is_login' => 0], ['pnode' => $one]);
$nodes[$thr] = array_merge(isset($alias[$thr]) ? $alias[$thr] : ['node' => $thr, 'title' => '', 'is_menu' => 0, 'is_auth' => 0, 'is_login' => 0], ['pnode' => $two]);
}
foreach ($nodes as &$node) {
list($node['is_auth'], $node['is_menu'], $node['is_login']) = [
intval($node['is_auth']), intval($node['is_menu']),
empty($node['is_auth']) ? intval($node['is_login']) : 1
];
}
return $nodes;
}
/**
* 获取节点列表
* @param string $path 路径
* @param array $nodes 额外数据
* @return array
*/
public static function getNodeTree($path, $nodes = [])
{
foreach (self::_getFilePaths($path) as $vo) {
if (!preg_match('|/(\w+)/controller/(\w+)|', str_replace(DS, '/', $vo), $matches) || count($matches) !== 3) {
continue;
}
$className = config('app_namespace') . str_replace('/', '\\', $matches[0]);
if (!class_exists($className)) {
continue;
}
foreach (get_class_methods($className) as $actionName) {
if ($actionName[0] !== '_') {
$nodes[] = strtolower("{$matches[1]}/{$matches[2]}/{$actionName}");
}
}
}
return $nodes;
}
/**
* 获取所有PHP文件
* @param string $path 目录
* @param array $data 额外数据
* @param string $ext 文件后缀
* @return array
*/
private static function _getFilePaths($path, $data = [], $ext = 'php')
{
foreach (scandir($path) as $dir) {
if ($dir[0] === '.') {
continue;
}
if (($tmp = realpath($path . DS . $dir)) && (is_dir($tmp) || pathinfo($tmp, 4) === $ext)) {
is_dir($tmp) ? $data = array_merge($data, self::_getFilePaths($tmp)) : $data[] = $tmp;
}
}
return $data;
}
}
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use Endroid\QrCode\QrCode;
use Wechat\WechatPay;
use think\Log;
use think\Db;
/**
* 支付数据服务
* Class PayService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2016/10/25 14:49
*/
class PayService
{
/**
* 查询订单是否已经支付
* @param string $order_no
* @return bool
*/
public static function isPay($order_no)
{
$map = ['order_no' => $order_no, 'is_pay' => '1'];
return Db::name('WechatPayPrepayid')->where($map)->count() > 0;
}
/**
* 创建微信二维码支付(扫码支付模式二)
* @param WechatPay $pay 支付SDK
* @param string $order_no 系统订单号
* @param int $fee 支付金额
* @param string $title 订单标题
* @param string $from 订单来源
* @return false|string
*/
public static function createWechatPayQrc(WechatPay $pay, $order_no, $fee, $title, $from = 'wechat')
{
$prepayid = self::createWechatPrepayid($pay, null, $order_no, $fee, $title, 'NATIVE', $from);
if ($prepayid === false) {
return false;
}
$filename = FileService::getFileName($prepayid, 'png', 'qrc/');
if (!FileService::hasFile($filename, 'local')) {
$qrCode = new QrCode($prepayid);
if (null === FileService::save($filename, $qrCode->get(), 'local')) {
return false;
}
}
return FileService::getFileUrl($filename, 'local');
}
/**
* 创建微信JSAPI支付签名包
* @param WechatPay $pay 支付SDK
* @param string $openid 微信用户openid
* @param string $order_no 系统订单号
* @param int $fee 支付金额
* @param string $title 订单标题
* @return bool|array
*/
public static function createWechatPayJsPicker(WechatPay $pay, $openid, $order_no, $fee, $title)
{
if (($prepayid = self::createWechatPrepayid($pay, $openid, $order_no, $fee, $title, 'JSAPI')) === false) {
return false;
}
return $pay->createMchPay($prepayid);
}
/**
* 微信退款操作
* @param WechatPay $pay 支付SDK
* @param string $order_no 系统订单号
* @param int $fee 退款金额
* @param string|null $refund_no 退款订单号
* @param string $refund_account
* @return bool
*/
public static function putWechatRefund(WechatPay $pay, $order_no, $fee = 0, $refund_no = null, $refund_account = '')
{
$map = ['order_no' => $order_no, 'is_pay' => '1', 'appid' => $pay->appid];
$notify = Db::name('WechatPayPrepayid')->where($map)->find();
if (empty($notify)) {
Log::error("内部订单号{$order_no}验证退款失败");
return false;
}
if (false !== $pay->refund($notify['out_trade_no'], $notify['transaction_id'], is_null($refund_no) ? "T{$order_no}" : $refund_no, $notify['fee'], empty($fee) ? $notify['fee'] : $fee, '', $refund_account)) {
$data = ['out_trade_no' => $notify['out_trade_no'], 'is_refund' => "1", 'refund_at' => date('Y-m-d H:i:s'), 'expires_in' => time() + 7000];
if (DataService::save('wechat_pay_prepayid', $data, 'out_trade_no')) {
return true;
}
Log::error("内部订单号{$order_no}退款成功,系统更新异常");
return false;
}
Log::error("内部订单号{$order_no}退款失败,{$pay->errMsg}");
return false;
}
/**
* 创建微信预支付码
* @param WechatPay $pay 支付SDK
* @param string $openid 支付者Openid
* @param string $order_no 实际订单号
* @param int $fee 实际订单支付费用
* @param string $title 订单标题
* @param string $trade_type 付款方式
* @param string $from 订单来源
* @return bool|string
*/
public static function createWechatPrepayid(WechatPay $pay, $openid, $order_no, $fee, $title, $trade_type = 'JSAPI', $from = 'wechat')
{
$map = ['order_no' => $order_no, 'is_pay' => '1', 'expires_in' => time(), 'appid' => $pay->appid, 'trade_type' => $trade_type];
$where = 'appid=:appid and order_no=:order_no and (is_pay=:is_pay or expires_in>:expires_in) and trade_type=:trade_type';
$prepayinfo = Db::name('WechatPayPrepayid')->where($where, $map)->find();
if (empty($prepayinfo) || empty($prepayinfo['prepayid'])) {
$out_trade_no = DataService::createSequence(18, 'WXPAY-OUTER-NO');
if (!($prepayid = $pay->getPrepayId($openid, $title, $out_trade_no, $fee, url("@wechat/notify", '', true, true), $trade_type))) {
Log::error("内部订单号{$order_no}生成预支付失败,{$pay->errMsg}");
return false;
}
$data = ['prepayid' => $prepayid, 'order_no' => $order_no, 'out_trade_no' => $out_trade_no, 'fee' => $fee, 'trade_type' => $trade_type];
list($data['from'], $data['appid'], $data['expires_in']) = [$from, $pay->getAppid(), time() + 5400];
if (Db::name('WechatPayPrepayid')->insert($data) > 0) {
Log::notice("内部订单号{$order_no}生成预支付成功,{$prepayid}");
return $prepayid;
}
}
return $prepayinfo['prepayid'];
}
}
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Log;
/**
* Soap服务对象
* Class SoapService
* @package service
*/
class SoapService
{
/**
* SOAP实例对象
* @var \SoapClient
*/
protected $soap;
/**
* 错误消息
* @var string
*/
protected $error;
/**
* SoapService constructor.
* @param string|null $wsdl WSDL连接参数
* @param array $params Params连接参数
* @throws \Exception
*/
public function __construct($wsdl, $params)
{
set_time_limit(3600);
if (!extension_loaded('soap')) {
throw new \Exception('Not support soap.');
}
$this->soap = new \SoapClient($wsdl, $params);
}
/**
* 属性获取转换
* @param $name
* @return string
*/
public function __get($name)
{
switch (strtolower($name)) {
case 'errmsg':
return $this->getError();
case 'errcode':
return $this->getErrorCode();
case 'appid':
return $this->getAppid();
}
return '';
}
/**
* @param string $name SOAP调用方法名
* @param array|string $arguments SOAP调用参数
* @return array|string|bool
* @throws \Exception
*/
public function __call($name, $arguments)
{
try {
return $this->soap->__call($name, $arguments);
} catch (\Exception $e) {
Log::error("Soap Error. Call {$name} Method --- " . $e->getMessage());
}
return false;
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Request;
/**
* 系统工具服务
* Class ToolsService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2016/10/25 14:49
*/
class ToolsService
{
/**
* Cors Options 授权处理
*/
public static function corsOptionsHandler()
{
if (request()->isOptions()) {
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
header('Access-Control-Allow-Credentials:true');
header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
header('Access-Control-Max-Age:1728000');
header('Content-Type:text/plain charset=UTF-8');
header('Content-Length: 0', true);
header('status: 204');
header('HTTP/1.0 204 No Content');
exit;
}
}
/**
* Cors Request Header信息
* @return array
*/
public static function corsRequestHander()
{
return [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Credentials' => true,
'Access-Control-Allow-Methods' => 'GET,POST,OPTIONS',
'Access-Defined-X-Support' => 'service@cuci.cc',
'Access-Defined-X-Servers' => 'Guangzhou Cuci Technology Co. Ltd',
];
}
/**
* Emoji原形转换为String
* @param string $content
* @return string
*/
public static function emojiEncode($content)
{
return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($str) {
return addslashes($str[0]);
}, json_encode($content)));
}
/**
* Emoji字符串转换为原形
* @param string $content
* @return string
*/
public static function emojiDecode($content)
{
return json_decode(preg_replace_callback('/\\\\\\\\/i', function () {
return '\\';
}, json_encode($content)));
}
/**
* 一维数据数组生成数据树
* @param array $list 数据列表
* @param string $id 父ID Key
* @param string $pid ID Key
* @param string $son 定义子数据Key
* @return array
*/
public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
{
list($tree, $map) = [[], []];
foreach ($list as $item) {
$map[$item[$id]] = $item;
}
foreach ($list as $item) {
if (isset($item[$pid]) && isset($map[$item[$pid]])) {
$map[$item[$pid]][$son][] = &$map[$item[$id]];
} else {
$tree[] = &$map[$item[$id]];
}
}
unset($map);
return $tree;
}
/**
* 一维数据数组生成数据树
* @param array $list 数据列表
* @param string $id ID Key
* @param string $pid 父ID Key
* @param string $path
* @param string $ppath
* @return array
*/
public static function arr2table(array $list, $id = 'id', $pid = 'pid', $path = 'path', $ppath = '')
{
$tree = [];
foreach (self::arr2tree($list, $id, $pid) as $attr) {
$attr[$path] = "{$ppath}-{$attr[$id]}";
$attr['sub'] = isset($attr['sub']) ? $attr['sub'] : [];
$attr['spl'] = str_repeat("&nbsp;&nbsp;&nbsp;├&nbsp;&nbsp;", substr_count($ppath, '-'));
$sub = $attr['sub'];
unset($attr['sub']);
$tree[] = $attr;
if (!empty($sub)) {
$tree = array_merge($tree, (array)self::arr2table($sub, $id, $pid, $path, $attr[$path]));
}
}
return $tree;
}
/**
* 获取数据树子ID
* @param array $list 数据列表
* @param int $id 起始ID
* @param string $key 子Key
* @param string $pkey 父Key
* @return array
*/
public static function getArrSubIds($list, $id = 0, $key = 'id', $pkey = 'pid')
{
$ids = [intval($id)];
foreach ($list as $vo) {
if (intval($vo[$pkey]) > 0 && intval($vo[$pkey]) === intval($id)) {
$ids = array_merge($ids, self::getArrSubIds($list, intval($vo[$key]), $key, $pkey));
}
}
return $ids;
}
/**
* 物流单查询
* @param $code
* @return array
*/
public static function express($code)
{
list($result, $client_ip) = [[], Request::instance()->ip()];
$header = ['Host' => 'www.kuaidi100.com', 'CLIENT-IP' => $client_ip, 'X-FORWARDED-FOR' => $client_ip];
$autoResult = HttpService::get("http://www.kuaidi100.com/autonumber/autoComNum?text={$code}", [], 30, $header);
foreach (json_decode($autoResult)->auto as $vo) {
$microtime = microtime(true);
$location = "http://www.kuaidi100.com/query?type={$vo->comCode}&postid={$code}&id=1&valicode=&temp={$microtime}";
$result[$vo->comCode] = json_decode(HttpService::get($location, [], 30, $header), true);
}
return $result;
}
}
<?php
// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------
namespace service;
use think\Db;
use think\Log;
/**
* 微信数据服务
* Class WechatService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2017/03/22 15:32
*/
class WechatService
{
/**
* 通过图文ID读取图文信息
* @param int $id 本地图文ID
* @param array $where 额外的查询条件
* @return array
*/
public static function getNewsById($id, $where = [])
{
$data = Db::name('WechatNews')->where(['id' => $id])->where($where)->find();
$article_ids = explode(',', $data['article_id']);
$articles = Db::name('WechatNewsArticle')->whereIn('id', $article_ids)->select();
$data['articles'] = [];
foreach ($article_ids as $article_id) {
foreach ($articles as $article) {
if (intval($article['id']) === intval($article_id)) {
unset($article['create_by'], $article['create_at']);
$article['content'] = htmlspecialchars_decode($article['content']);
$data['articles'][] = $article;
}
}
}
unset($articles);
return $data;
}
/**
* 上传图片到微信服务器
* @param string $local_url
* @return string|null
*/
public static function uploadImage($local_url)
{
# 检测文件上否已经上传过了
$md5 = md5($local_url);
if (($img = Db::name('WechatNewsImage')->where(['md5' => $md5])->find()) && !empty($img['media_url'])) {
return $img['media_url'];
}
# 下载临时文件到本地
$content = file_get_contents($local_url);
$filename = 'wechat/image/' . join('/', str_split($md5, 16)) . '.' . strtolower(pathinfo($local_url, 4));
# 上传图片到微信服务器
if (($result = FileService::local($filename, $content)) && isset($result['file'])) {
$wechat = load_wechat('media');
$info = $wechat->uploadImg(['media' => base64_encode($content)]);
if (!empty($info)) {
$data = ['local_url' => $local_url, 'media_url' => $info['url'], 'md5' => $md5];
Db::name('WechatNewsImage')->insert($data);
return $info['url'];
}
Log::error("图片上传失败,请稍后再试!{$wechat->errMsg}[{$wechat->errCode}]");
}
return null;
}
/**
* 上传图片永久素材
* @param string $local_url 文件URL地址
* @param string $type 文件类型
* @param bool $is_video 是否为视频文件
* @param array $video_info 视频信息
* @return string|null
*/
public static function uploadForeverMedia($local_url = '', $type = 'image', $is_video = false, $video_info = [])
{
# 检测文件上否已经上传过了
$wechat = load_wechat('media');
$map = ['md5' => md5($local_url), 'appid' => $wechat->getAppid()];
if (($img = Db::name('WechatNewsMedia')->where($map)->find()) && !empty($img['media_id'])) {
return $img['media_id'];
}
# 下载临时文件到本地
$content = file_get_contents($local_url);
$filename = 'wechat/image/' . join('/', str_split(md5($local_url), 16)) . '.' . strtolower(pathinfo($local_url, 4));
if (($upload = FileService::local($filename, $content)) && isset($upload['file']) && file_exists($upload['file'])) {
# 上传图片到微信服务器
if (false !== ($result = $wechat->uploadForeverMedia(['media' => base64_encode($content)], $type, $is_video, $video_info))) {
$data = ['md5' => $map['md5'], 'type' => $type, 'appid' => $wechat->getAppid(), 'media_id' => $result['media_id'], 'local_url' => $local_url];
isset($result['url']) && $data['media_url'] = $result['url'];
Db::name('WechatNewsMedia')->insert($data);
return $data['media_id'];
}
}
Log::error("素材上传失败, 请稍后再试! {$wechat->errMsg}[{$wechat->errCode}]");
return null;
}
/**
* 从微信服务器获取所有标签
* @return bool
*/
public static function syncFansTags()
{
$wechat = load_wechat("User");
if (($result = $wechat->getTags()) !== false) {
Db::name('WechatFansTags')->where('appid', $wechat->getAppid())->delete();
foreach (array_chunk($result['tags'], 100) as $list) {
Db::name('WechatFansTags')->insertAll($list);
}
}
return true;
}
/**
* 同步粉丝的标签
* @param string $openid
* @return bool
*/
public static function syncFansTagsByOpenid($openid)
{
$wechat = load_wechat('User');
$tagsid = $wechat->getUserTags($openid);
if ($tagsid === false || !is_array($tagsid)) {
return false;
}
$data = ['openid' => $openid, 'tagid_list' => join(',', $tagsid)];
return DataService::save('wechat_fans', $data, 'openid', ['appid' => $wechat->getAppid()]);
}
/**
* 保存/更新粉丝信息
* @param array $user
* @param string $appid
* @return bool
*/
public static function setFansInfo($user, $appid = '')
{
if (!empty($user['subscribe_time'])) {
$user['subscribe_at'] = date('Y-m-d H:i:s', $user['subscribe_time']);
}
if (!empty($user['tagid_list']) && is_array($user['tagid_list'])) {
$user['tagid_list'] = join(',', $user['tagid_list']);
}
foreach (['country', 'province', 'city', 'nickname', 'remark'] as $k) {
isset($user[$k]) && $user[$k] = ToolsService::emojiEncode($user[$k]);
}
$user['appid'] = $appid;
return DataService::save('WechatFans', $user, 'openid');
}
/**
* 读取粉丝信息
* @param string $openid 微信用户openid
* @param string $appid 公众号appid
* @return array|false
*/
public static function getFansInfo($openid, $appid = null)
{
$map = ['openid' => $openid];
is_string($appid) && $map['appid'] = $appid;
$user = Db::name('WechatFans')->where($map)->find();
foreach (['country', 'province', 'city', 'nickname', 'remark'] as $k) {
isset($user[$k]) && $user[$k] = ToolsService::emojiDecode($user[$k]);
}
return $user;
}
/**
* 同步获取粉丝列表
* @param string $next_openid
* @return bool
*/
public static function syncAllFans($next_openid = '')
{
$wechat = load_wechat('User');
$appid = $wechat->getAppid();
if (false === ($result = $wechat->getUserList($next_openid)) || empty($result['data']['openid'])) {
Log::error("获取粉丝列表失败, {$wechat->errMsg} [{$wechat->errCode}]");
return false;
}
foreach (array_chunk($result['data']['openid'], 100) as $openids) {
if (false === ($info = $wechat->getUserBatchInfo($openids)) || !is_array($info)) {
Log::error("获取用户信息失败, {$wechat->errMsg} [{$wechat->errCode}]");
return false;
}
foreach ($info as $user) {
if (false === self::setFansInfo($user, $appid)) {
Log::error('更新粉丝信息更新失败!');
return false;
}
if ($result['next_openid'] === $user['openid']) {
unset($result['next_openid']);
}
}
}
return empty($result['next_openid']) ? true : self::syncAllFans($result['next_openid']);
}
/**
* 同步获取黑名单信息
* @param string $next_openid
* @return bool
*/
public static function syncBlackFans($next_openid = '')
{
$wechat = load_wechat('User');
$result = $wechat->getBacklist($next_openid);
if ($result === false || empty($result['data']['openid'])) {
if (empty($result['total'])) {
return true;
}
Log::error("获取粉丝黑名单列表失败,{$wechat->errMsg} [{$wechat->errCode}]");
return false;
}
foreach ($result['data']['openid'] as $openid) {
if (false === ($user = $wechat->getUserInfo($openid))) {
Log::error("获取用户[{$openid}]信息失败,$wechat->errMsg");
return false;
}
$user['is_back'] = '1';
if (false === self::setFansInfo($user)) {
Log::error('更新粉丝信息更新失败!');
return false;
}
if ($result['next_openid'] === $openid) {
unset($result['next_openid']);
}
}
return empty($result['next_openid']) ? true : self::syncBlackFans($result['next_openid']);
}
}
......@@ -8,14 +8,34 @@
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Route;
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
];
// 注册路由到index模块的News控制器的read操作
/*Route::get(['/', '/:d'], 'index/index');
Route::get(['/well', '/w'], 'index/wellCome');
Route::get('/s', 'index/wellCome');*/
//推荐这种风格 注明控制器
/*IndexController*/
/*Route::rule([
'/' => 'index/index',
'/well' => 'index/wellCome',
'/re' => 'index/read'
], '', 'GET|POST');
// 检测路由规则仅GET请求有效
Route::any('new/:id','News/read',['method'=>'get']);
// 检测路由规则仅GET和POST请求有效
Route::any('new/:id','News/read',['method'=>'get|post']);
Route::get('/he/:id', 'index/hello');
/*StoreController
Route::rule([
'/saveStore' => 'store/save'
], '', 'GET');
/*Error
Route::rule(['/city/:name' => 'error/index'] , '' ,'GET');*/
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment