Commit ad418f78 authored by shajiaiming's avatar shajiaiming

Merge branch 'master' into feature/optimize

parents 761b431b 7a940eae
<?php
namespace api\base;
class BaseConstant
{
const ERROR = 'error';
const MSG = 'msg';
const MESSAGE = 'message';
const CODE = 'code';
const VAL = 'val';
const DATA = 'data';
const OK = 'ok';
const FINALTAG = 'finaltag';
}
...@@ -37,7 +37,7 @@ class BaseResponse extends Response ...@@ -37,7 +37,7 @@ class BaseResponse extends Response
$return = $data; $return = $data;
} }
if (YII_ENV_DEV) { if (YII_ENV_DEV) {
$return['time'] = \Yii::$app->controller->end - \Yii::$app->controller->start; #$return['time'] = \Yii::$app->controller->end - \Yii::$app->controller->start;
} }
\Yii::$app->response->data = $return; \Yii::$app->response->data = $return;
parent::send(); parent::send();
......
<?php
namespace api\base;
use yii\helpers\Html;
use yii\web\Response;
class ResponseMsg
{
public $is_support_jsonp = false;
public $header_list = [];
private static $default_header_list = [];
public function __construct()
{
// if ('cli' !== php_sapi_name()){
// $this->header_list = self::$default_header_list;
// $this->fzmCrossHeader();
// }
}
public function fzmCrossHeader()
{
$allow_list = \Yii::$app->params['allow_options_domain']['common'];
$origin = \Yii::$app->request->headers->get('Origin');
if (!in_array($origin, $allow_list)) {
$origin = implode(',', $allow_list);
}
$this->header('Access-Control-Allow-Origin', $origin);
$this->header('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
$this->header('Access-Control-Allow-Credentials', 'true');
$this->header('Access-Control-Allow-Headers', 'Authorization,FZM-REQUEST-OS,FZM-USER-IP,FZM-REQUEST-UUID,Content-Type,Content-Length');
}
public static function setDefaultHeader($default_header_list)
{
foreach ($default_header_list as $key => $header) {
self::$default_header_list[$key] = $header;
}
}
public static function getDefaultHeader()
{
return self::$default_header_list;
}
public function arrSuccess($data = BaseConstant::OK, $code = 200)
{
return [BaseConstant::ERROR => false, BaseConstant::MESSAGE => $data, BaseConstant::CODE => $code];
}
public function arrFail($data, $code = -1)
{
return [BaseConstant::ERROR => true, BaseConstant::MESSAGE => $data, BaseConstant::CODE => $code];
}
/**
* 失败返回接口
* @param string $msg
* @param int $code
* @return string
*/
public function jsonError($msg = '', $code = -1)
{
if (empty($msg)) {
$msg = 'unknown error';
}
$view = [
BaseConstant::CODE => $code,
BaseConstant::MSG => $msg,
BaseConstant::DATA => null,
];
$json = json_encode($view);
return $this->dumpJsonData($json);
}
/**
* 成功返回接口
* @param string $msg
* @param int $code
* @return string
*/
public function jsonSuccess($data = '', $code = 200)
{
$view = [
BaseConstant::CODE => $code,
BaseConstant::MESSAGE => BaseConstant::OK,
BaseConstant::DATA => $data
];
$json = json_encode($view);
return $this->dumpJsonData($json);
}
/**
* 直接处理接口数据
* @param $ret
*/
public function dealRet($ret)
{
if (true === $ret[BaseConstant::ERROR]) {
$this->jsonError($ret[BaseConstant::MESSAGE] ? : 'unknown error');
} else {
$this->jsonSuccess($ret[BaseConstant::MESSAGE] ? : BaseConstant::OK);
}
}
/**
* 根据是否为JSONP做特殊处理输出
* @param $json
* @return string
*/
public function dumpJsonData($json)
{
$callback = '';
if (true === $this->is_support_jsonp) {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
$callback_key = 'jsonpcallback';
$callback = $_GET[$callback_key];
if ($callback) {
$callback = Html::encode($callback_key);
$json = $callback . '(' . $json . ')';
}
}
if (!$callback && !$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return $json;
}
/**
* @param $json_str
* @param string $callback_key
* @return string
*/
public function printByJson($json_str, $callback_key = '')
{
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . $json_str . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return $json_str;
}
}
/**
* @param $arr
* @param string $callback_key
* @return string
*/
public function printByArr($arr, $callback_key = '')
{
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
public function printOldFail($code, $code_msg, $detail_code, $detail_msg, $callback_key = '')
{
$this->fzmCrossHeader();
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
$arr = ['code' => $code, 'error' => $code_msg, 'ecode' => $detail_code, 'message' => $detail_msg, 'data' => []];
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
/**
* @param $success_data
* @param string $callback_key
* @return string
*/
public function printOldSuccess($success_data, $callback_key = '')
{
$this->fzmCrossHeader();
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
$arr = ['code' => 200, 'ecode' => 200, 'error' => 'OK', 'message' => 'OK', 'data' => $success_data];
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
/**
* 解决xdebug cookie设置不了的问题
*/
private function isDebug()
{
if (defined('SERVICE_ENV') && (SERVICE_ENV === 'test' || SERVICE_ENV === 'local') && isset($_GET['debug'])) {
return true;
}
return false;
}
public function header($key, $value)
{
$this->header_list[$key] = $value;
}
public function getHeaders()
{
return $this->header_list;
}
public function withHeaders($header_arr)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
foreach ($header_arr as $key => $val) {
\Yii::$app->response->headers->add($key, $val);
}
return $this;
}
public function withContent($content)
{
return $content;
}
}
...@@ -60,6 +60,8 @@ class AppController extends BaseController ...@@ -60,6 +60,8 @@ class AppController extends BaseController
$platform_id = \Yii::$app->request->post('platform_id', 1); $platform_id = \Yii::$app->request->post('platform_id', 1);
$data = CoinAppVersion::getLastStable($type,$platform_id); $data = CoinAppVersion::getLastStable($type,$platform_id);
if ($data) { if ($data) {
$logstr = '';
if(!empty($data['log'])){
$logItems = json_decode($data['log']); $logItems = json_decode($data['log']);
$logstr = ''; $logstr = '';
foreach($logItems as $item){ foreach($logItems as $item){
...@@ -68,7 +70,7 @@ class AppController extends BaseController ...@@ -68,7 +70,7 @@ class AppController extends BaseController
}else{ }else{
$logstr = $item; $logstr = $item;
} }
}
} }
$data['log'] = $logstr; $data['log'] = $logstr;
$data['id']=(integer)$data['id']; $data['id']=(integer)$data['id'];
......
...@@ -11,6 +11,7 @@ namespace api\controllers; ...@@ -11,6 +11,7 @@ namespace api\controllers;
use api\base\BaseController; use api\base\BaseController;
use common\base\Exception; use common\base\Exception;
use common\business\BrowerBusiness; use common\business\BrowerBusiness;
use common\business\Chain33Business;
use common\business\CoinBusiness; use common\business\CoinBusiness;
use common\business\ExchangeBusiness; use common\business\ExchangeBusiness;
use common\models\psources\Coin; use common\models\psources\Coin;
...@@ -139,7 +140,7 @@ class CoinController extends BaseController ...@@ -139,7 +140,7 @@ class CoinController extends BaseController
$coin_ids = array_column($coin_recommends, 'cid'); $coin_ids = array_column($coin_recommends, 'cid');
//获取币种信息 //获取币种信息
$coin_infos = Coin::getCoinInfoByIds($coin_ids, $select, 'id'); $coin_infos = Coin::getCoinInfoByIds($coin_ids, $select, 'id');
foreach ($coin_infos as $key => &$val){ foreach ($coin_infos as $key => &$val) {
$nickname = json_decode($val['nickname'], true); $nickname = json_decode($val['nickname'], true);
$val['nickname'] = $nickname[$this->lang]; $val['nickname'] = $nickname[$this->lang];
} }
...@@ -179,7 +180,7 @@ class CoinController extends BaseController ...@@ -179,7 +180,7 @@ class CoinController extends BaseController
unset($key, $value); unset($key, $value);
} }
} }
if(!$datas['data']){ if (!$datas['data']) {
$datas['data'] = null; $datas['data'] = null;
} }
return $datas; return $datas;
...@@ -198,8 +199,8 @@ class CoinController extends BaseController ...@@ -198,8 +199,8 @@ class CoinController extends BaseController
$coin = Coin::findOne(['name' => $names]); $coin = Coin::findOne(['name' => $names]);
if ($coin) { if ($coin) {
$chain = $coin->chain; $chain = $coin->chain;
$miner_fee = MinerFee::find()->where(['platform' => $chain,'type' => 1])->one(); $miner_fee = MinerFee::find()->where(['platform' => $chain, 'type' => 1])->one();
if(!$miner_fee){ if (!$miner_fee) {
throw new Exception('8', '旷工费未设置'); throw new Exception('8', '旷工费未设置');
} }
} else { } else {
...@@ -207,8 +208,8 @@ class CoinController extends BaseController ...@@ -207,8 +208,8 @@ class CoinController extends BaseController
throw new Exception('8', '币种不存在'); throw new Exception('8', '币种不存在');
} }
$result = (array)$miner_fee->getAttributes(); $result = (array)$miner_fee->getAttributes();
$result['min'] = number_format($result['min'],6); $result['min'] = number_format($result['min'], 6);
$result['max'] = number_format($result['max'],6); $result['max'] = number_format($result['max'], 6);
return $result; return $result;
} }
...@@ -220,20 +221,20 @@ class CoinController extends BaseController ...@@ -220,20 +221,20 @@ class CoinController extends BaseController
$names = Yii::$app->request->post('names'); $names = Yii::$app->request->post('names');
$platforms = []; $platforms = [];
$newNames = []; $newNames = [];
if(!$names){ if (!$names) {
return ['code' => 0,'data' => []]; return ['code' => 0, 'data' => []];
} }
foreach($names as $item){ foreach ($names as $item) {
$item_array = explode(',',$item); $item_array = explode(',', $item);
$newNames [] = $item_array[0]; $newNames [] = $item_array[0];
if(isset($item_array[1])){ if (isset($item_array[1])) {
if(!in_array($item_array[1],$platforms)){ if (!in_array($item_array[1], $platforms)) {
$platforms [] = $item_array[1]; $platforms [] = $item_array[1];
} }
} }
} }
$condition = [['in', 'name', $newNames]]; $condition = [['in', 'name', $newNames]];
if($platforms){ if ($platforms) {
$condition[] = ['in', 'platform', $platforms]; $condition[] = ['in', 'platform', $platforms];
} }
$result = ExchangeBusiness::getApiListForIndex(1, 999, $condition); $result = ExchangeBusiness::getApiListForIndex(1, 999, $condition);
...@@ -267,9 +268,9 @@ class CoinController extends BaseController ...@@ -267,9 +268,9 @@ class CoinController extends BaseController
$limit = $request->post('limit', 10); $limit = $request->post('limit', 10);
$platform_ids = $request->post('platform_id', null); $platform_ids = $request->post('platform_id', null);
$condition = [['in', 'chain', ['ETH','DCR','BTC','BTY']]]; $condition = [['in', 'chain', ['ETH', 'DCR', 'BTC', 'BTY']]];
if (!empty($name)) { if (!empty($name)) {
$condition[] = ['or',['address' => $name],['or', ['like', 'name', $name], ['like', 'nickname', $name]]]; $condition[] = ['or', ['address' => $name], ['or', ['like', 'name', $name], ['like', 'nickname', $name]]];
} }
if ($platform_ids) { if ($platform_ids) {
/* $platform_id_arr = explode(',', $platform_ids); /* $platform_id_arr = explode(',', $platform_ids);
...@@ -330,11 +331,11 @@ class CoinController extends BaseController ...@@ -330,11 +331,11 @@ class CoinController extends BaseController
{ {
$request = Yii::$app->request; $request = Yii::$app->request;
$platform = $request->post('platform', ''); $platform = $request->post('platform', '');
if($platform){ if ($platform) {
$brower_url = Yii::$app->redis->hget('platform_brower_info',$platform); $brower_url = Yii::$app->redis->hget('platform_brower_info', $platform);
return ['code' => 0,'data' => $brower_url]; return ['code' => 0, 'data' => $brower_url];
}else{ } else {
return ['code' => 1,'data' => [],'msg' => '平台参数不能为空']; return ['code' => 1, 'data' => [], 'msg' => '平台参数不能为空'];
} }
} }
...@@ -345,24 +346,33 @@ class CoinController extends BaseController ...@@ -345,24 +346,33 @@ class CoinController extends BaseController
{ {
$request = Yii::$app->request; $request = Yii::$app->request;
$platform = $request->get('platform', ''); $platform = $request->get('platform', '');
if($platform){ $coin_name = $request->get('coinname', '');
if (empty($coin_name)) {
$platform_with_hold = CoinPlatformWithHold::getRecord($platform); $platform_with_hold = CoinPlatformWithHold::getRecord($platform);
if($platform_with_hold){
$des = Yii::$app->des; $des = Yii::$app->des;
$platform_with_hold['private_key'] = $des->encrypt($platform_with_hold['private_key']); $platform_with_hold['private_key'] = $des->encrypt($platform_with_hold['private_key']);
return ['code' => 0,'data' => $platform_with_hold]; return ['code' => 0, 'data' => $platform_with_hold];
}else{ }
$data = [ $platform_with_hold = CoinPlatformWithHold::getRecord($platform);
'id' => 0, $coin_info = Coin::find()->select('treaty')->where(['name' => strtoupper($coin_name)])->asArray()->one();
'platform' => '', $des = Yii::$app->des;
'address' => '', $platform_with_hold['private_key'] = $des->encrypt($platform_with_hold['private_key']);
'private_key' => '', if (1 == $coin_info['treaty']) {
'exer' => '' $platform_with_hold['exer'] = 'user.p.' . $platform . '.token';
]; $platform_with_hold['tokensymbol'] = $coin_name;
return ['code' => 0, 'data' => $data]; $platform_with_hold['fee'] = 0;
} } else {
}else{ $platform_with_hold['exer'] = 'user.p.' . $platform . '.coins';
return ['code' => 1,'data' => [],'msg' => '平台参数不能为空']; $platform_with_hold['tokensymbol'] = $platform . '.coins';
$platform_with_hold['fee'] = (float)sprintf("%0.4f", (double)$platform_with_hold['fee']);
}
$service = new Chain33Business();
$result = $service->getProperFee();
if (0 === $result['code']) {
$platform_with_hold['bty_fee'] = (float)sprintf("%0.4f", $result['result']['properFee'] / 1e8);
} else {
$platform_with_hold['bty_fee'] = (float)sprintf("%0.4f", Yii::$app->params['bty_fee']);
} }
return ['code' => 0, 'data' => $platform_with_hold];
} }
} }
...@@ -5,9 +5,11 @@ ...@@ -5,9 +5,11 @@
* Date: 2018/11/14 * Date: 2018/11/14
* Time: 18:53 * Time: 18:53
*/ */
namespace api\controllers; namespace api\controllers;
use api\base\BaseController; use api\base\BaseController;
use common\models\psources\CoinHashMemo;
use common\models\psources\CoinTokenTransfer; use common\models\psources\CoinTokenTransfer;
use common\service\chain33\Chain33Service; use common\service\chain33\Chain33Service;
use Yii; use Yii;
...@@ -22,13 +24,33 @@ class TradeController extends BaseController ...@@ -22,13 +24,33 @@ class TradeController extends BaseController
{ {
$request = Yii::$app->request; $request = Yii::$app->request;
$hash = $request->post('hash'); $hash = $request->post('hash');
if (empty($hash)) {
return ['code' => 1, 'data' => [], 'msg' => '交易hash值不能为空'];
}
$model = new CoinHashMemo();
$model->setScenario(CoinHashMemo::SCENARIOS_CREATE);
if ($model->load(Yii::$app->request->post(), '') && $model->save()) {
return ['code' => 0, 'data' => [], 'msg' => '本地备注添加成功'];
} else {
return ['code' => 1, 'data' => [], 'msg' => current($model->firstErrors)];
}
}
public function actionUpdateMemo()
{
$request = Yii::$app->request;
$hash = $request->post('hash');
$memo = $request->post('memo'); $memo = $request->post('memo');
if($hash && $memo){ if (empty($hash)) {
Yii::$app->redis->hset('trade_hash_memo',$hash,$memo); return ['code' => 1, 'data' => [], 'msg' => '交易hash值不能为空'];
return ['code' => 0,'data' => [], 'msg' => '本地备注添加成功'];
}else{
return ['code' => 1,'data' => [],'msg' => '交易hash值或者本地备注不能为空'];
} }
$model = CoinHashMemo::find()->where(['hash' => $hash])->one();
if (empty($model)) {
return ['code' => 1, 'data' => [], 'msg' => '记录不存在'];
}
CoinHashMemo::updateAll(['memo' => $memo], 'hash = :hash',[':hash'=>$hash]);
return ['code' => 0, 'data' => [], 'msg' => '本地备注更新成功'];
} }
/** /**
...@@ -38,25 +60,55 @@ class TradeController extends BaseController ...@@ -38,25 +60,55 @@ class TradeController extends BaseController
{ {
$request = Yii::$app->request; $request = Yii::$app->request;
$hash = $request->post('hash'); $hash = $request->post('hash');
if($hash){ $version = $request->post('version', '');
$memo = Yii::$app->redis->hget('trade_hash_memo',$hash); if(empty($hash)) {
return ['code' => 0,'data' => $memo]; return ['code' => 1, 'data' => [], 'msg' => '交易hash值不能为空'];
}else{ }
return ['code' => 1,'data' => [],'msg' => '交易hash值不能为空']; $model = CoinHashMemo::find()->where(['hash' => $hash])->asArray()->one();
if(empty($model)) {
return ['code' => 1, 'data' => [], 'msg' => '记录不存在'];
}
if(empty($version)){
return ['code' => 0, 'data' => $model['memo']];
}
return ['code' => 0, 'data' => [
'memo' => $model['memo'],
'coins_fee' => $model['coins_fee']
]];
} }
public function actionSyncToDb()
{
$data = [];
$result = Yii::$app->redis->HGETALL ('trade_hash_memo');
foreach ($result as $key => $val){
if (($key + 2) % 2 == 0){
$data[] = [
'hash' => $val,
'memo' => $result[$key + 1]
];
}
}
foreach ($data as $val){
if ('0xc080c6a0937f25d1017e5e88bdcff5c3979810c8a6cc1f3a64cf50970da28fc9' == $val['hash']) continue;
$coin_memo_hash = new CoinHashMemo();
$coin_memo_hash->hash = $val['hash'];
$coin_memo_hash->memo = $val['memo'];
$coin_memo_hash->save();
}
exit;
} }
public function actionAddressIsExist() public function actionAddressIsExist()
{ {
$get = Yii::$app->request->get(); $get = Yii::$app->request->get();
$to = $get['coin_address'] ?? ''; $to = $get['coin_address'] ?? '';
if(empty($to)){ if (empty($to)) {
return ['code' => -1, 'msg' => '参数不能为空']; return ['code' => -1, 'msg' => '参数不能为空'];
} }
$coinTokenTransfer = CoinTokenTransfer::find()->where(['coin_address' => $to, 'code' => 1])->one(); $coinTokenTransfer = CoinTokenTransfer::find()->where(['coin_address' => $to, 'code' => 1])->one();
if(!$coinTokenTransfer){ if (!$coinTokenTransfer) {
return ['code' => 0, 'msg' => 'record does not exist']; return ['code' => 0, 'msg' => 'record does not exist'];
} }
...@@ -68,12 +120,12 @@ class TradeController extends BaseController ...@@ -68,12 +120,12 @@ class TradeController extends BaseController
{ {
$get = Yii::$app->request->get(); $get = Yii::$app->request->get();
$to = $get['coin_address'] ?? ''; $to = $get['coin_address'] ?? '';
if(empty($to)){ if (empty($to)) {
return ['code' => -1, 'msg' => '参数不能为空']; return ['code' => -1, 'msg' => '参数不能为空'];
} }
$coinTokenTransfer = CoinTokenTransfer::find()->where(['coin_address' => $to, 'code' => 1])->one(); $coinTokenTransfer = CoinTokenTransfer::find()->where(['coin_address' => $to, 'code' => 1])->one();
if($coinTokenTransfer){ if ($coinTokenTransfer) {
return ['code' => -1, 'msg' => 'record already exists']; return ['code' => -1, 'msg' => 'record already exists'];
} }
...@@ -87,7 +139,7 @@ class TradeController extends BaseController ...@@ -87,7 +139,7 @@ class TradeController extends BaseController
$service = new Chain33Service(); $service = new Chain33Service();
$createRawTransaction = $service->createTokenRawTransaction($to, $amount, $isToken, $tokenSymbol, $fee, $note, $execer); $createRawTransaction = $service->createTokenRawTransaction($to, $amount, $isToken, $tokenSymbol, $fee, $note, $execer);
if(0 != $createRawTransaction['code']){ if (0 != $createRawTransaction['code']) {
$msg = $createRawTransaction['msg']; $msg = $createRawTransaction['msg'];
$code = -1; $code = -1;
goto doEnd; goto doEnd;
...@@ -98,7 +150,7 @@ class TradeController extends BaseController ...@@ -98,7 +150,7 @@ class TradeController extends BaseController
$expire = '1m'; $expire = '1m';
$signRawTx = $service->signRawTx($privkey, $txHex, $expire); $signRawTx = $service->signRawTx($privkey, $txHex, $expire);
if(0 != $signRawTx['code']){ if (0 != $signRawTx['code']) {
$msg = $signRawTx['msg']; $msg = $signRawTx['msg'];
$code = -1; $code = -1;
goto doEnd; goto doEnd;
...@@ -106,7 +158,7 @@ class TradeController extends BaseController ...@@ -106,7 +158,7 @@ class TradeController extends BaseController
$sign_str = $signRawTx['result']; $sign_str = $signRawTx['result'];
$result = $service->sendTransaction($sign_str); $result = $service->sendTransaction($sign_str);
if(0 != $result['code']){ if (0 != $result['code']) {
$msg = $result['msg']; $msg = $result['msg'];
$code = -1; $code = -1;
goto doEnd; goto doEnd;
......
<?php
namespace api\controllers;
use api\base\BaseController;
use common\models\psources\CoinAirDropTrade;
use common\models\psources\CoinPlatform;
use common\service\chain33\Chain33Service;
use Yii;
class WalletController extends BaseController
{
public function actionInfo()
{
$code = 0;
$msg = 'success';
$platform_id = Yii::$app->request->get('platform_id', '');
if(empty($platform_id)){
$msg = '参数不能为空';
$code = -1;
$data = null;
goto doEnd;
}
$data = CoinPlatform::find()->select("name, download_url, introduce")->where(['id' => $platform_id])->asArray()->one();
if(empty($data)){
$msg = '数据不存在';
$data = null;
$code = -1;
goto doEnd;
}
$data['title'] = $data['name'];
unset($data['name']);
doEnd :
return ['code' => $code, 'data' => $data, 'msg' => $msg];
}
public function actionGameTradeUpdate()
{
$coinAirDropTrade = CoinAirDropTrade::find()->where(['attach' => 2 ,'msg' => '0'])->limit(30)->all();
foreach ($coinAirDropTrade as $val){
$fee = 100000;
$amount = 1 * 1e8;
$execer = 'coins';
$note = '';
$service = new Chain33Service();
$createRawTransaction = $service->createRawTransaction($val->coins_address, $amount, $fee, $note, $execer);
if(0 != $createRawTransaction['code']){
continue;
}
$txHex = $createRawTransaction['result'];
$privkey = '72c3879f1f9b523f266a9545b69bd41c0251483a93e21e348e85118afe17a5e2';
$expire = '1m';
$signRawTx = $service->signRawTx($privkey, $txHex, $expire);
if(0 != $signRawTx['code']){
continue;
}
$sign_str = $signRawTx['result'];
$result = $service->sendTransaction($sign_str);
if(0 != $result['code']){
continue;
}
$currentModel = CoinAirDropTrade::findOne($val->id);
$currentModel->attach = 2;
$currentModel->balance = 0;
$currentModel->msg = $result['result'];
$currentModel->save();
}
return ['code' => 1, 'msg' => 'ok'];
}
public function actionGetBalance()
{
$coinAirDropTrade = CoinAirDropTrade::find()->where(['balance' => 0])->limit(60)->all();
$address = [];
foreach ($coinAirDropTrade as $val){
$address[] = $val->coins_address;
}
$service = new Chain33Service();
$execer = 'coins';
$result = $service->getBalance($address, $execer);
if(0 == $result['code']){
$result_balance = $result['result'];
foreach ($result_balance as $val){
$coinAirDropTrade = CoinAirDropTrade::find()->where(['coins_address' => $val['addr']])->one();
if(empty($coinAirDropTrade)) continue;
$coinAirDropTrade->balance = $val['balance'];
$coinAirDropTrade->save();
}
}
return ['code' => 1, 'msg' => 'ok'];
}
}
\ No newline at end of file
<?php
/**
* Created By Sublime Text 3
*
* @authors rlgy <rlgyzhcn@qq.com>
* @date 2018-09-07 17:41:04
*/
namespace backend\assets\wallet;
use yii\web\AssetBundle;
use yii\web\View;
class IndexAsset extends AssetBundle
{
public $sourcePath = '@backend/web/js/wallet';
public $js = [
'index.js',
];
public $jsOptions = [
'position' => View::POS_END,
];
}
\ No newline at end of file
...@@ -5,14 +5,116 @@ ...@@ -5,14 +5,116 @@
* Date: 2018/12/17 * Date: 2018/12/17
* Time: 10:13 * Time: 10:13
*/ */
namespace backend\controllers; namespace backend\controllers;
use common\models\psources\CoinApplicationCategory; use backend\models\coin\CoinPlatformForm;
use common\models\psources\CoinPlatform;
use Yii; use Yii;
class WalletController extends BaseController class WalletController extends BaseController
{ {
public function actionList()
{
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = 'json';
$request = Yii::$app->request;
$page = $request->get('page', 1);
$limit = $request->get('limit', 10);
$name = $request->get('name', '');
$where = [];
if ($name) {
$where[] = ['name' => $name];
}
$data = CoinPlatform::getList($page, $limit, $where);
$data['code'] = 0;
Yii::$app->response->format = 'json';
return $data;
}
return $this->render('index');
}
public function actionAdd()
{
$model = new CoinPlatformForm();
$model->scenario = 'add';
if (Yii::$app->request->isPost) {
$data = Yii::$app->request->post();
if ($model->load($data, '') && $model->validate()) {
$coin = Yii::createObject(CoinPlatform::className());
$result = $coin->addOne($data);
if ($result === true) {
$this->success('添加成功', '/admin/wallet/list');
}
}
//表单验证失败
$errors = $model->errors;
if ($errors) {
foreach ($errors as $key => $item) {
$errors = $item[0];
break;
}
} elseif (isset($result) && $result['code'] != 0) {
$errors = $result['message'];
}
$this->error($errors, Yii::$app->request->getReferrer());
}
return $this->render('add', ['model' => $model]);
}
public function actionEdit()
{
if (Yii::$app->request->isPost) {
$model = new CoinPlatformForm();
$model->scenario = 'update';
$data = Yii::$app->request->post();
Yii::$app->response->format = 'json';
if ($model->load($data, '') && $model->validate()) {
$coin = Yii::createObject(CoinPlatform::className());
$result = $coin->updateOne($data);
if ($result === true) {
return ['code' => 0, 'msg' => 'succeed'];
}
}
$errors = $model->errors;
if ($errors) {
foreach ($errors as $key => $item) {
$errors = $item[0];
break;
}
} elseif (isset($result) && $result['code'] != 0) {
$errors = $result['message'];
}
return ['code' => 1, 'msg' => $errors];
} elseif (Yii::$app->request->isGet) {
$id = Yii::$app->request->get('id', null);
if ($id) {
$coin = CoinPlatform::findOne(['id' => $id]);
$this->layout = false;
return $this->render('edit', ['model' => $coin]);
}
}
}
public function actionDelete()
{
Yii::$app->response->format = 'json';
$id = Yii::$app->request->get('id', 0);
if ($id) {
$model = CoinPlatform::findOne(['id' => $id]);
if ($model) {
try {
$model->delete();
return ['code' => 0, 'msg' => 'succeed'];
} catch (\Throwable $t) {
return ['code' => $t->getCode(), 'msg' => $t->getMessage()];
}
}
}
return ['code' => -1, 'msg' => '删除失败'];
}
/** /**
* @return string * @return string
* 设置钱包密码 * 设置钱包密码
...@@ -24,23 +126,21 @@ class WalletController extends BaseController ...@@ -24,23 +126,21 @@ class WalletController extends BaseController
$new_passwd = Yii::$app->request->post('new_passwd'); $new_passwd = Yii::$app->request->post('new_passwd');
$confirm_passwd = Yii::$app->request->post('confirm_passwd'); $confirm_passwd = Yii::$app->request->post('confirm_passwd');
$passwd = Yii::$app->redis->get('wallet_passwd'); $passwd = Yii::$app->redis->get('wallet_passwd');
if(!$passwd){ if (!$passwd) {
Yii::$app->redis->set('wallet_passwd',$new_passwd); Yii::$app->redis->set('wallet_passwd', $new_passwd);
$this->success('钱包密码设置成功', Yii::$app->request->getReferrer()); $this->success('钱包密码设置成功', Yii::$app->request->getReferrer());
} }
if($passwd != $old_passwd){ if ($passwd != $old_passwd) {
$this->error('原始密码错误', Yii::$app->request->getReferrer()); $this->error('原始密码错误', Yii::$app->request->getReferrer());
} }
if($new_passwd != $confirm_passwd){ if ($new_passwd != $confirm_passwd) {
$this->error('确认密码和设置的密码不一致', Yii::$app->request->getReferrer()); $this->error('确认密码和设置的密码不一致', Yii::$app->request->getReferrer());
} }
Yii::$app->redis->set('wallet_passwd',$new_passwd); Yii::$app->redis->set('wallet_passwd', $new_passwd);
$this->success('钱包密码设置成功', Yii::$app->request->getReferrer()); $this->success('钱包密码设置成功', Yii::$app->request->getReferrer());
} }
return $this->render('set-passwd'); return $this->render('set-passwd');
} }
} }
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-31
* Time: 下午4:05
*/
namespace backend\models\coin;
use yii\base\Model;
class CoinPlatformForm extends Model
{
public $id;
public $name;
public $download_url;
public $introduce;
public function formName()
{
return '';
}
public function rules()
{
return [
[['name'], 'required', 'on' => 'add'],
[['id', 'name'], 'required', 'on' => 'update'],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => '名称',
'download_url' => '下载链接',
'introduce' => '介绍'
];
}
public function scenarios()
{
return [
'add' => [
'id',
'name',
],
'update' => [
'id',
'name',
],
];
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-31
* Time: 下午3:31
*/
?>
<h4>添加钱包</h4>
<style>
.layui-form-label {
width: 100px;
}
</style>
<div class="layui-row" style="padding: 5px;">
<div class="layui-col-md6">
<form class="layui-form" method="post" action="">
<input name="_csrf" type="hidden" value="<?= Yii::$app->request->getCsrfToken() ?>">
<div class="layui-inline">
<label class="layui-form-label">简称</label>
<div class="layui-input-block">
<input class="layui-input" name="name" value="<?= $model->name ?>" lay-verify="required">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">下载地址</label>
<div class="layui-input-block">
<input class="layui-input" name="download_url" value="<?= $model->download_url ?>">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">介绍</label>
<div class="layui-input-block">
<textarea class="layui-textarea" name="introduce"><?= $model->introduce?></textarea>
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn">提交</button>
</div>
</form>
</div>
</div>
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-31
* Time: 下午6:23
*/
?>
<style>
.layui-form-label {
width: 100px;
}
</style>
<div class="layui-row" style="padding: 5px;">
<div class="layui-col-md12">
<form class="layui-form" method="post" action="" id="walletEdit">
<input name="_csrf" type="hidden" value="<?= Yii::$app->request->getCsrfToken() ?>">
<input name="id" type="hidden" value="<?= $model->id ?>">
<div class="layui-inline">
<label class="layui-form-label">简称</label>
<div class="layui-input-block">
<input class="layui-input" name="name" value="<?= $model->name ?>" lay-verify="required">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">下载地址</label>
<div class="layui-input-block">
<input class="layui-input" name="download_url" value="<?= $model->download_url ?>">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">介绍</label>
<div class="layui-input-block">
<textarea class="layui-textarea" name="introduce"><?= $model->introduce?></textarea>
</div>
</div>
</form>
</div>
</div>
<script>
var laydate = layui.laydate;
laydate.render({
elem: "#time1"
});
//图片上传
var uploader = layui.upload;
$_csrf = $("input[name='_csrf']").val();
uploader.render({
elem: "#upload1",
url: '/admin/coin/upload',
data: {_csrf: $_csrf},
done: function (res) {
console.log(res.data.src);
$("input[name='icon']").val(res.data.src);
$("#icon1").attr('src', res.data.src);
},
error: function (res) {
}
});
//form render
var form = layui.form;
form.render();
</script>
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-31
* Time: 上午9:59
*/
use backend\assets\wallet\IndexAsset;
IndexAsset::register($this);
?>
<style>
.layui-table-tips-c {
padding: 0px;
}
</style>
<h4>钱包列表</h4>
<div class="layui-row">
<div class="layui-col-md1">
<a href="/admin/wallet/add">
<button class="layui-btn layui-btn-default" id="add">添加钱包</button>
</a>
</div>
<div class="layui-col-md8">
<form class="layui-form" method="get" action="">
<div class="layui-inline">
<label class="layui-form-label" style="margin-bottom: 0; width: 100px;">钱包名称</label>
<div class="layui-input-inline">
<input class="layui-input" name="name">
</div>
</div>
<div class="layui-inline">
<button class="layui-btn" lay-submit lay-filter="form1">搜索</button>
</div>
</form>
</div>
</div>
<div class="layui-row">
<table class="layui-table" id="table1" lay-filter="table1"></table>
</div>
<script type="text/html" id="operationTpl">
<a lay-event="edit">
<button class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe642;</i></button>
</a>
<a lay-event="delete">
<button class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i></button>
</a>
</script>
/**
* @author rlgyzhcn@qq.com
*/
var table = layui.table;
var form = layui.form;
var layer = layui.layer;
form.render();
var tableIns = table.render({
elem: "#table1",
url: '/admin/wallet/list',
limit: 10,
page: 1,
loading: true,
cols: [[
{field: 'id', title: 'ID'},
{field: 'name', title: '名称'},
{field: 'id', title: '操作', templet: '#operationTpl'}
]],
});
form.on('submit(form1)', function (data) {
table.reload("table1", {
where: data.field,
page: {curr: 1},
});
return false;
});
//监听单元格事件
table.on('tool(table1)', function (obj) {
var data = obj.data;
if (obj.event == 'delete') {
layer.confirm('真的要删除' + data.name + '吗?', {icon: 3, title: '删除'}, function (index) {
layer.close(index);
//向服务端发送删除指令
$.get('/admin/wallet/delete?id=' + obj.data.id, function (data, status) {
if (data.code == 0) {
obj.del(); //删除对应行(tr)的DOM结构
}
layer.msg(data.msg);
});
});
} else if (obj.event == 'edit') {
$.get('/admin/wallet/edit', {id: data.id}, function (str) {
var editIndex = layer.open({
type: 1,
title: '编辑: ' + data.name,
area: '625px',
content: str,
btn: ['保存', '取消'],
btn1: function () {
// console.log();
$.post('/admin/wallet/edit', $("#walletEdit").serialize(), function (rev) {
layer.msg(rev.msg);
if (rev.code == 0) {
table.reload("table1", {
where: data.field,
});
layer.close(editIndex);
}
});
}
});
});
}
});
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: jiaming
* Date: 2019/7/17
* Time: 11:11
*/
namespace common\base;
use yii\web\Request;
class BaseRequest extends Request
{
private $user_id = 0;
private $platform_id = 0;
public function getUserId()
{
return $this->user_id;
}
public function setUserId($value)
{
$this->user_id = $value;
}
public function getPlatformId()
{
return $this->platform_id;
}
public function setPlatformId($value)
{
$this->platform_id = $value;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: jiaming
* Date: 2019/6/20
* Time: 11:11
*/
namespace common\behaviors;
use Yii;
use common\models\Admin;
use api\base\ResponseMsg;
use common\components\Response;
use yii\base\ActionFilter;
class LoginStatusAuthInterceptor extends ActionFilter
{
public function beforeAction($action)
{
$request_class = get_class($action->controller);
$request_action = $action->id;
if('login' == $request_action || 'user-sync' == $request_action){
return true;
}
$token_string = Yii::$app->request->headers->get('Token');
if(false == $token_string){
$msg = 'platform auth error';
$code = '40004';
goto doEnd;
}
$model = new Admin();
$user = $model->loginByAccessToken($token_string,'');
if(false == $user){
$msg = 'user auth error';
$code = '40004';
goto doEnd;
}
$user_id = $user->uid;
$platform_id = $user->platform_id;
Yii::$app->request->setUserId($user_id);
Yii::$app->request->setPlatformId($platform_id);
return true;
doEnd :
// 返回错误
$response_message = new ResponseMsg();
$content = $response_message->jsonError($msg, $code);
$content = $response_message->withHeaders($response_message->getHeaders())->withContent($content);
Yii::$app->response->data = $content;
Yii::$app->response->send();
return false;
}
public function frontAuth()
{
//验证用户token正确性
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: jiaming
* Date: 2019/6/20
* Time: 11:11
*/
namespace common\behaviors;
use api\base\ResponseMsg;
use yii\base\ActionFilter;
use common\models\Admin;
use Yii;
class UserAuthInterceptor extends ActionFilter
{
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
$request_class = get_class($action->controller);
$request_action = $action->id;
if('login' == $request_action || 'user-sync' == $request_action){
return true;
}
$token_string = Yii::$app->request->headers->get('Token');
$model = new Admin();
$user = $model->loginByAccessToken($token_string, '');
if (empty($user)) {
$code = '40001';
$msg = 'user auth error';
goto doEnd;
}
$user_id = $user->uid;
$platform_id = $user->platform_id;
Yii::$app->request->setUserId($user_id);
Yii::$app->request->setPlatformId($platform_id);
$user_auth = Yii::$app->params['user_auth']['user_auth'];
$user_auth_map = $user_auth[$platform_id] ?? null;
if (empty($user_auth_map)) {
$code = '40001';
$msg = 'platform auth error';
goto doEnd;
}
$user_auth_map = $user_auth_map[$user_id] ?? null;
if (empty($user_auth_map)) {
$code = '40001';
$msg = 'user auth error';
goto doEnd;
}
$auth_type_map = Yii::$app->params['user_auth'][$user_auth_map];
$auth_type_map = array_unique($auth_type_map, SORT_REGULAR);
$switch = false;
foreach ($auth_type_map as $key => $auth_type) {
if (empty($auth_type)) continue;
if ($request_class == $auth_type['class']) {
$action_map = $auth_type['actions'];
$switch = true;
break;
}
}
if (false == $switch) {
$code = '40003';
$msg = 'controller auth error';
goto doEnd;
}
if (empty($action_map)) {
return true;
}
if (in_array($request_action, $action_map)) {
return true;
} else {
$code = '40004';
$msg = 'action auth error';
goto doEnd;
}
doEnd :
// 返回错误
$response_message = new ResponseMsg();
$content = $response_message->jsonError($msg, $code);
$content = $response_message->withHeaders($response_message->getHeaders())->withContent($content);
Yii::$app->response->data = $content;
Yii::$app->response->send();
return false;
}
}
\ No newline at end of file
...@@ -131,6 +131,12 @@ class Chain33Business ...@@ -131,6 +131,12 @@ class Chain33Business
return $service->getBlockHashByHeight($height); return $service->getBlockHashByHeight($height);
} }
public static function getProperFee()
{
$service = new Chain33Service();
return $service->getProperFee();
}
/** /**
* 获取coin地址下DAPP交易信息 * 获取coin地址下DAPP交易信息
* @param string $address * @param string $address
......
...@@ -51,17 +51,17 @@ class ExchangeBusiness ...@@ -51,17 +51,17 @@ class ExchangeBusiness
public static function getquatation($tag = 'btc') public static function getquatation($tag = 'btc')
{ {
$coin_quotation_disable_items = Yii::$app->params['coin_quotation_disable_items']; $coin_quotation_disable_items = Yii::$app->params['coin_quotation_disable_items'];
if(strtoupper($tag) == 'CCNY'){ if (strtoupper($tag) == 'CCNY') {
$exchange = ExchangeFactory::createExchange("Bty"); $exchange = ExchangeFactory::createExchange("Bty");
$rate = $exchange->getTicker("BTY", "USDT"); $rate = $exchange->getTicker("BTY", "USDT");
$rate = (float)$rate['rmb'] / $rate['last']; $rate = (float)$rate['rmb'] / $rate['last'];
$quotation['rmb'] = 1.00; $quotation['rmb'] = 1.00;
$quotation['low'] = 1.00; $quotation['low'] = 1.00;
$quotation['high'] = 1.00; $quotation['high'] = 1.00;
$quotation['last'] = (float)sprintf("%0.4f", $quotation['rmb']/$rate); $quotation['last'] = (float)sprintf("%0.4f", $quotation['rmb'] / $rate);
goto doEnd; goto doEnd;
} }
if(strtoupper($tag) == 'BOSS'){ if (strtoupper($tag) == 'BOSS') {
$quotation = [ $quotation = [
'low' => 2000, 'low' => 2000,
'high' => 2000, 'high' => 2000,
...@@ -71,7 +71,7 @@ class ExchangeBusiness ...@@ -71,7 +71,7 @@ class ExchangeBusiness
goto doEnd; goto doEnd;
} }
if(strtoupper($tag) == 'CPF'){ if (strtoupper($tag) == 'CPF') {
$quotation = [ $quotation = [
'low' => 3.4, 'low' => 3.4,
'high' => 3.4, 'high' => 3.4,
...@@ -81,62 +81,72 @@ class ExchangeBusiness ...@@ -81,62 +81,72 @@ class ExchangeBusiness
goto doEnd; goto doEnd;
} }
if(in_array($tag,$coin_quotation_disable_items)){ if (strtoupper($tag) == 'WL' || strtoupper($tag) == 'ETS' || strtoupper($tag) == 'LIMS' || strtoupper($tag) == 'AT' || strtoupper($tag) == 'BTJ') {
$quotation = [
'low' => 0,
'high' => 0,
'last' => 0,
'rmb' => 0,
];
goto doEnd;
}
if (in_array($tag, $coin_quotation_disable_items)) {
return false; return false;
} }
$f = false; $f = false;
$quotation = []; $quotation = [];
if(in_array(strtoupper($tag),['GM', 'BSTC'])){ if (in_array(strtoupper($tag), ['GM', 'BSTC'])) {
$exchange = ExchangeFactory::createExchange("Token7"); $exchange = ExchangeFactory::createExchange("Token7");
$quotation = $exchange->getTicker($tag, 'HA'); $quotation = $exchange->getTicker($tag, 'HA');
$quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']); $quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']);
goto doEnd; goto doEnd;
} }
if(in_array(strtoupper($tag),['BECC'])){ if (in_array(strtoupper($tag), ['BECC'])) {
$exchange = ExchangeFactory::createExchange("S"); $exchange = ExchangeFactory::createExchange("S");
$quotation = $exchange->getTicker($tag, 'ST'); $quotation = $exchange->getTicker($tag, 'ST');
$quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']); $quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']);
goto doEnd; goto doEnd;
} }
if(in_array(strtoupper($tag),['GHP'])){ if (in_array(strtoupper($tag), ['GHP'])) {
$exchange = ExchangeFactory::createExchange("Zg"); $exchange = ExchangeFactory::createExchange("Zg");
$quotation = $exchange->getTicker($tag, 'CNZ'); $quotation = $exchange->getTicker($tag, 'CNZ');
$quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']); $quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']);
goto doEnd; goto doEnd;
} }
if(in_array(strtoupper($tag),['SFT'])){ if (in_array(strtoupper($tag), ['SFT'])) {
$exchange = ExchangeFactory::createExchange("Zhaobi"); $exchange = ExchangeFactory::createExchange("Zhaobi");
$quotation = $exchange->getTicker($tag, 'CNY'); $quotation = $exchange->getTicker($tag, 'CNY');
$quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']); $quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']);
goto doEnd; goto doEnd;
} }
if(in_array(strtoupper($tag),['CTG'])){ if (in_array(strtoupper($tag), ['CTG'])) {
$exchange = ExchangeFactory::createExchange("Gdpro"); $exchange = ExchangeFactory::createExchange("Gdpro");
$quotation = $exchange->getTicker($tag, 'CNY'); $quotation = $exchange->getTicker($tag, 'CNY');
$quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']); $quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']);
goto doEnd; goto doEnd;
} }
if(in_array(strtoupper($tag),['USDT'])){ if (in_array(strtoupper($tag), ['USDT'])) {
$exchange = ExchangeFactory::createExchange("Go"); $exchange = ExchangeFactory::createExchange("Go");
$quotation = $exchange->getTicker('CNY', 'USD'); $quotation = $exchange->getTicker('CNY', 'USD');
$quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']); $quotation['rmb'] = (float)sprintf("%0.2f", $quotation['last']);
goto doEnd; goto doEnd;
} }
if(in_array(strtoupper($tag),['SJPY'])){ if (in_array(strtoupper($tag), ['SJPY'])) {
$exchange = ExchangeFactory::createExchange("Boc"); $exchange = ExchangeFactory::createExchange("Boc");
$quotation = $exchange->getTicker('CNY', 'JPY'); $quotation = $exchange->getTicker('CNY', 'JPY');
$quotation = [ $quotation = [
'low' => (float)sprintf("%0.4f", $quotation['low']/100), 'low' => (float)sprintf("%0.4f", $quotation['low'] / 100),
'high' => (float)sprintf("%0.4f", $quotation['high']/100), 'high' => (float)sprintf("%0.4f", $quotation['high'] / 100),
'last' => (float)sprintf("%0.4f", $quotation['last']/100), 'last' => (float)sprintf("%0.4f", $quotation['last'] / 100),
'rmb' => (float)sprintf("%0.4f", $quotation['last']/100), 'rmb' => (float)sprintf("%0.4f", $quotation['last'] / 100),
]; ];
goto doEnd; goto doEnd;
} }
...@@ -187,7 +197,7 @@ class ExchangeBusiness ...@@ -187,7 +197,7 @@ class ExchangeBusiness
$exchange = ExchangeFactory::createExchange("Go"); $exchange = ExchangeFactory::createExchange("Go");
$rate = $exchange->getTicker("CNY", "USD"); $rate = $exchange->getTicker("CNY", "USD");
$rate = $rate['last'] ?? ''; $rate = $rate['last'] ?? '';
if(empty($rate)) { if (empty($rate)) {
$exchange = ExchangeFactory::createExchange("Bty"); $exchange = ExchangeFactory::createExchange("Bty");
$rate = $exchange->getTicker("BTY", "USDT"); $rate = $exchange->getTicker("BTY", "USDT");
$rate = (float)$rate['rmb'] / $rate['last']; $rate = (float)$rate['rmb'] / $rate['last'];
...@@ -240,12 +250,12 @@ class ExchangeBusiness ...@@ -240,12 +250,12 @@ class ExchangeBusiness
* @param array $condition 需要的币种sid列表 * @param array $condition 需要的币种sid列表
* @return array * @return array
*/ */
public static function getApiListForIndex($page = 1, $limit = 999, $condition = [], $fields=[]) public static function getApiListForIndex($page = 1, $limit = 999, $condition = [], $fields = [])
{ {
if(!$fields) { if (!$fields) {
$fields =['id', 'sid', 'icon', 'name', 'nickname', 'platform', 'chain','address as contract_address', 'treaty']; $fields = ['id', 'sid', 'icon', 'name', 'nickname', 'platform', 'chain', 'address as contract_address', 'treaty'];
} }
$rows = Coin::getSelectList($page, $limit, $fields,$condition); $rows = Coin::getSelectList($page, $limit, $fields, $condition);
$count = 0; $count = 0;
if (!empty($rows) && is_array($rows) && array_key_exists('count', $rows)) { if (!empty($rows) && is_array($rows) && array_key_exists('count', $rows)) {
$count = $rows['count']; $count = $rows['count'];
...@@ -257,7 +267,7 @@ class ExchangeBusiness ...@@ -257,7 +267,7 @@ class ExchangeBusiness
$quotation = self::getquatation($row['name']); $quotation = self::getquatation($row['name']);
if (!$quotation) { if (!$quotation) {
$quotation = []; $quotation = [];
if(in_array($row['name'], ['BTY', 'YCC'])){ if (in_array($row['name'], ['BTY', 'YCC'])) {
$coinServer = CoinFactory::createCoin($row['name'], $row['id'], $row['sid']); $coinServer = CoinFactory::createCoin($row['name'], $row['id'], $row['sid']);
$rows[$key]['sid'] = ucfirst($rows[$key]['sid']); $rows[$key]['sid'] = ucfirst($rows[$key]['sid']);
$rows[$key]['rmb'] = $coinServer->getPrice(); $rows[$key]['rmb'] = $coinServer->getPrice();
...@@ -297,7 +307,7 @@ class ExchangeBusiness ...@@ -297,7 +307,7 @@ class ExchangeBusiness
*/ */
public static function SearchByName($page = 1, $limit = 10, $condition = []) public static function SearchByName($page = 1, $limit = 10, $condition = [])
{ {
$rows = Coin::getSelectList($page, $limit, ['id', 'sid', 'icon', 'name', 'nickname', 'platform', 'chain','address as contract_address', 'treaty'], $rows = Coin::getSelectList($page, $limit, ['id', 'sid', 'icon', 'name', 'nickname', 'platform', 'chain', 'address as contract_address', 'treaty'],
$condition); $condition);
if ($rows['count'] > 0) { if ($rows['count'] > 0) {
$total = $rows['count']; $total = $rows['count'];
...@@ -305,7 +315,7 @@ class ExchangeBusiness ...@@ -305,7 +315,7 @@ class ExchangeBusiness
foreach ($rows as $key => $row) { foreach ($rows as $key => $row) {
$rows[$key]['sid'] = ucfirst($rows[$key]['sid']); $rows[$key]['sid'] = ucfirst($rows[$key]['sid']);
$platform = strtoupper($rows[$key]['platform']); $platform = strtoupper($rows[$key]['platform']);
$platform_icon = Yii::$app->redis->hget('platform_image_info',$platform); $platform_icon = Yii::$app->redis->hget('platform_image_info', $platform);
$rows[$key]['platform_icon'] = $platform_icon ?? ''; $rows[$key]['platform_icon'] = $platform_icon ?? '';
} }
......
...@@ -517,6 +517,7 @@ class Curl ...@@ -517,6 +517,7 @@ class Curl
$curlOptions = $this->getOptions(); $curlOptions = $this->getOptions();
$this->curl = curl_init($this->getUrl()); $this->curl = curl_init($this->getUrl());
curl_setopt_array($this->curl, $curlOptions); curl_setopt_array($this->curl, $curlOptions);
curl_setopt($this->curl, CURLOPT_TIMEOUT,40);
$response = curl_exec($this->curl); $response = curl_exec($this->curl);
//check if curl was successful //check if curl was successful
if ($response === false) { if ($response === false) {
......
...@@ -13,12 +13,14 @@ use yii\web\IdentityInterface; ...@@ -13,12 +13,14 @@ use yii\web\IdentityInterface;
* @property string $uid * @property string $uid
* @property string $username * @property string $username
* @property string $password * @property string $password
* @property string $access_token
* @property string $reg_time * @property string $reg_time
* @property string $reg_ip * @property string $reg_ip
* @property string $last_login_time * @property string $last_login_time
* @property string $last_login_ip * @property string $last_login_ip
* @property string $update_time * @property string $update_time
* @property integer $status * @property integer $status
* @property integer $platform_id
*/ */
class Admin extends \common\modelsgii\Admin implements IdentityInterface class Admin extends \common\modelsgii\Admin implements IdentityInterface
{ {
...@@ -34,14 +36,6 @@ class Admin extends \common\modelsgii\Admin implements IdentityInterface ...@@ -34,14 +36,6 @@ class Admin extends \common\modelsgii\Admin implements IdentityInterface
} }
/** /**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* 根据用户名获取账号信息 * 根据用户名获取账号信息
* *
* @param string $username * @param string $username
...@@ -156,4 +150,43 @@ class Admin extends \common\modelsgii\Admin implements IdentityInterface ...@@ -156,4 +150,43 @@ class Admin extends \common\modelsgii\Admin implements IdentityInterface
$this->password = null; $this->password = null;
} }
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
$user = static::find()->where(['access_token' => $token, 'status' => self::STATUS_ACTIVE])->one();
if (!$user) {
return false;
}
// if ($user->expire_at < time()) {
// throw new UnauthorizedHttpException('the access - token expired ', -1);
// } else {
// return $user;
// }
return $user;
}
public function loginByAccessToken($accessToken, $type) {
return static::findIdentityByAccessToken($accessToken, $type);
}
/**
* Generate accessToken string
* @return string
* @throws \yii\base\Exception
*/
public function generateAccessToken()
{
$this->access_token = Yii::$app->security->generateRandomString();
return $this->access_token;
}
public static function loadArray(array $data)
{
return self::getDb()->createCommand()->batchInsert(self::tableName(),
['bind_uid', 'username', 'salt', 'password', 'reg_time', 'reg_ip', 'last_login_time', 'last_login_ip', 'update_time', 'status', 'platform_id'],
$data)->execute();
}
} }
...@@ -11,10 +11,13 @@ class LoginForm extends Model ...@@ -11,10 +11,13 @@ class LoginForm extends Model
{ {
public $username; public $username;
public $password; public $password;
public $token;
public $rememberMe = true; public $rememberMe = true;
private $_user; private $_user;
//定义场景
const SCENARIOS_LOGIN = 'login';
/** /**
* @inheritdoc * @inheritdoc
...@@ -31,6 +34,13 @@ class LoginForm extends Model ...@@ -31,6 +34,13 @@ class LoginForm extends Model
]; ];
} }
public function scenarios() {
$scenarios = [
self:: SCENARIOS_LOGIN => ['username', 'password'],
];
return array_merge( parent:: scenarios(), $scenarios);
}
/** /**
* Validates the password. * Validates the password.
* This method serves as the inline validation for password. * This method serves as the inline validation for password.
...@@ -56,7 +66,12 @@ class LoginForm extends Model ...@@ -56,7 +66,12 @@ class LoginForm extends Model
public function login() public function login()
{ {
if ($this->validate()) { if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); if ($this->getUser()) {
$access_token = $this->_user->generateAccessToken();
$this->_user->access_token = $access_token ;
$this->_user->save();
return $access_token;
}
} }
return false; return false;
...@@ -70,7 +85,21 @@ class LoginForm extends Model ...@@ -70,7 +85,21 @@ class LoginForm extends Model
protected function getUser() protected function getUser()
{ {
if ($this->_user === null) { if ($this->_user === null) {
$this->_user = User::findByUsername($this->username); $this->_user = Admin::findByUsername($this->username);
}
return $this->_user;
}
/**
* Finds user by [[token]]
*
* @return User|null
*/
protected function getToken()
{
if ($this->_user === null) {
$this->_user = Admin::findIdentityByAccessToken($this->token);
} }
return $this->_user; return $this->_user;
......
...@@ -10,7 +10,7 @@ class CoinAirDropTrade extends BaseActiveRecord ...@@ -10,7 +10,7 @@ class CoinAirDropTrade extends BaseActiveRecord
{ {
const TYPE_GAME = 1; const TYPE_GAME = 1;
const AMOUNT_GAME = 0.5; const AMOUNT_GAME = 0.0001;
public static function getDb() public static function getDb()
{ {
......
<?php
namespace common\models\psources;
use Yii;
use common\core\BaseActiveRecord;
class CoinHashMemo extends BaseActiveRecord
{
public static function getDb()
{
return Yii::$app->get('p_sources');
}
public static function tableName()
{
return '{{%coin_hash_memo}}';
}
//定义场景
const SCENARIOS_CREATE = 'create';
const SCENARIOS_UPDATE = 'update';
public function rules() {
return [
[['hash'], 'required'],
[['coins_fee','memo'],'safe']
];
}
public function scenarios() {
$scenarios = [
self:: SCENARIOS_CREATE => ['hash','memo', 'coins_fee'],
];
return array_merge( parent:: scenarios(), $scenarios);
}
}
\ No newline at end of file
...@@ -14,4 +14,63 @@ class CoinPlatform extends BaseActiveRecord ...@@ -14,4 +14,63 @@ class CoinPlatform extends BaseActiveRecord
{ {
return '{{%coin_platform}}'; return '{{%coin_platform}}';
} }
/**
* 获取钱包信息列表
*
* @param int $page
* @param int $limit
* @param array $condition
* @return array|\yii\db\ActiveRecord[]
*/
public static function getList($page = 1, $limit = 10, $condition = [])
{
$query = self::find();
foreach ($condition as $item) {
$query = $query->andWhere($item);
}
$count = $query->count();
$data = $query->offset(($page - 1) * 10)->limit($limit)->asArray()->all();
return ['count' => $count, 'data' => $data];
}
public function addOne($params)
{
$params = array_filter($params, function ($value) {
if (null == $value) {
return false;
}
return true;
});
$this->setAttributes($params, false);
try {
return (bool)$this->save();
} catch (\Exception $exception) {
return ['code' => $exception->getCode(), 'message' => $exception->getMessage()];
}
}
public function updateOne($params)
{
$params = array_filter($params, function ($value) {
if (null === $value) {
return false;
}
return true;
});
if (isset($params['id']) && !empty($params['id'])) {
$coin = self::findOne(['id' => $params['id']]);
if ($coin === null) {
return ['code' => 1, 'msg' => '币种不存在'];
}
unset($params['id']);
}
$coin->setAttributes($params, false);
try {
return (bool)$coin->save();
} catch (\Exception $exception) {
return ['code' => $exception->getCode(), 'message' => $exception->getMessage()];
}
}
} }
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
* Time: 17:37 * Time: 17:37
*/ */
namespace common\models\psources; namespace common\models\psources;
use Yii;
class CoinPlatformWithHold extends BaseActiveRecord class CoinPlatformWithHold extends BaseActiveRecord
{ {
......
...@@ -10,6 +10,7 @@ use yii\helpers\HtmlPurifier; ...@@ -10,6 +10,7 @@ use yii\helpers\HtmlPurifier;
* @property string $uid * @property string $uid
* @property string $username * @property string $username
* @property string $password * @property string $password
* @property string $access_token
* @property string $salt * @property string $salt
* @property string $reg_time * @property string $reg_time
* @property string $reg_ip * @property string $reg_ip
...@@ -17,6 +18,7 @@ use yii\helpers\HtmlPurifier; ...@@ -17,6 +18,7 @@ use yii\helpers\HtmlPurifier;
* @property string $last_login_ip * @property string $last_login_ip
* @property string $update_time * @property string $update_time
* @property integer $status * @property integer $status
* @property integer $platform_id
*/ */
class Admin extends \common\core\BaseActiveRecord class Admin extends \common\core\BaseActiveRecord
{ {
...@@ -42,10 +44,11 @@ class Admin extends \common\core\BaseActiveRecord ...@@ -42,10 +44,11 @@ class Admin extends \common\core\BaseActiveRecord
return HtmlPurifier::process($str); return HtmlPurifier::process($str);
} }
], ],
[['reg_time', 'reg_ip', 'last_login_time', 'last_login_ip', 'update_time', 'status'], 'integer'], [['reg_time', 'reg_ip', 'last_login_time', 'last_login_ip', 'update_time', 'status', 'platform_id'], 'integer'],
[['username'], 'string', 'max' => 32], [['username'], 'string', 'max' => 32],
[['password'], 'string', 'min' => 6, 'max' => 60], [['password'], 'string', 'min' => 6, 'max' => 60],
[['salt'], 'string', 'max' => 32], [['salt'], 'string', 'max' => 32],
['access_token', 'safe']
]; ];
} }
...@@ -65,6 +68,7 @@ class Admin extends \common\core\BaseActiveRecord ...@@ -65,6 +68,7 @@ class Admin extends \common\core\BaseActiveRecord
'last_login_ip' => 'Last Login Ip', 'last_login_ip' => 'Last Login Ip',
'update_time' => 'Update Time', 'update_time' => 'Update Time',
'status' => 'Status', 'status' => 'Status',
'platform_id' => 'platform_id',
'group' => 'group' 'group' => 'group'
]; ];
} }
......
...@@ -313,6 +313,11 @@ class Chain33Service ...@@ -313,6 +313,11 @@ class Chain33Service
return $this->send(['height' => $height], 'Chain33.GetBlockHash'); return $this->send(['height' => $height], 'Chain33.GetBlockHash');
} }
public function getProperFee($params = [])
{
return $this->send($params, 'Chain33.GetProperFee');
}
public function getTxByAddr($addr, $flag, $count, $direction, $height, $index) public function getTxByAddr($addr, $flag, $count, $direction, $height, $index)
{ {
$params = [ $params = [
......
<?php
namespace common\service\trusteeship;
use Yii;
use common\helpers\Curl;
class TrusteeShipService
{
private $node_params;
public function __construct($parameter = [])
{
$platform_id = Yii::$app->request->getPlatformId();
if (empty($parameter)) {
$this->node_params = Yii::$app->params['trusteeship']['node_' . $platform_id];
} else {
$this->node_params = $parameter;
}
}
public function urlBuild($uri = '')
{
return $this->node_params . '/' . $uri;
}
public function send($method = 'GET', $uri, $params = [])
{
$ch = new Curl();
if (!empty($params)) {
$ch->setGetParams($params);
}
$result = $ch->$method($this->urlBuild($uri), false);
if (!$result) {
return ['code' => -1, 'msg' => $ch->errorText];
}
if (200 == $result['code']) {
return ['code' => $result['code'], 'msg' => $result['data']];
} else {
return ['code' => -1, 'msg' => $result['message']];
}
}
public function getUserList($params = [])
{
$uri = 'backend/user/user-list';
return $this->send("GET", $uri, $params);
}
public function getWalletBalance($params = [])
{
$uri = 'backend/account/wallet-balance';
return $this->send("GET", $uri, $params);
}
public function getUserAsset($params = [])
{
$uri = 'backend/user/asset';
return $this->send("GET", $uri, $params);
}
}
<?php
namespace wallet\base;
class BaseConstant
{
const ERROR = 'error';
const MSG = 'msg';
const MESSAGE = 'message';
const CODE = 'code';
const VAL = 'val';
const DATA = 'data';
const OK = 'ok';
const FINALTAG = 'finaltag';
}
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-31
* Time: 上午10:29
*/
namespace wallet\base;
use Yii;
use yii\helpers\Url;
use yii\web\Response;
use yii\base\Controller;
use yii\base\InlineAction;
use yii\web\BadRequestHttpException;
class BaseController extends Controller
{
public function behaviors()
{
$request_controller = Yii::$app->controller->id;
$request_action = Yii::$app->controller->action->id;
$interceptor_global = array_unique(Yii::$app->params['interceptor']['global']);
$interceptor_default = array_unique(Yii::$app->params['interceptor']['default']);
$interceptor_mapping = isset(Yii::$app->params['interceptor'][$request_controller]) ? array_unique(Yii::$app->params['interceptor'][$request_controller]) : null;
$controller_enable = $interceptor_mapping ?? false;
$behaviors = [];
$final_interceptor = array_keys(array_flip(array_merge($interceptor_global, $interceptor_default)));
if ($controller_enable) {
$interceptor_map = $interceptor_mapping['interceptors'];
if ($interceptor_map) {
$switch = array_shift($interceptor_map);
if (false == $switch) {
$deny_interceptor = $interceptor_map;
$final_interceptor = array_diff($interceptor_default, $deny_interceptor);
} else {
$final_interceptor = array_unique($interceptor_map);
}
}
$action_mapping = $interceptor_mapping['actions'] ?? false;
if ($action_mapping) { //指定方法使用哪些拦截器
foreach ($action_mapping as $val) {
$action_id = array_shift($val); //拦截器配置文件中的action
$interceptor_map = $val[0];
$switch = array_shift($interceptor_map); //拦截器配置文件中action对应的拦截开关
if ($action_id == $request_action) {
if (false == $switch) {
$final_interceptor = array_unique(array_merge($interceptor_map, $interceptor_global));
$final_interceptor = array_diff($interceptor_default, array_diff($final_interceptor, $interceptor_global));
} else {
$final_interceptor = array_unique($interceptor_map);
}
}
}
}
}
foreach ($final_interceptor as $key => $item) {
$behaviors[$key] = [
'class' => $item,
];
}
return $behaviors;
}
/**
* @var bool whether to enable CSRF validation for the actions in this controller.
* CSRF validation is enabled only when both this property and [[\yii\web\Request::enableCsrfValidation]] are true.
*/
public $enableCsrfValidation = true;
/**
* @var array the parameters bound to the current action.
*/
public $actionParams = [];
/**
* Renders a view in response to an AJAX request.
*
* This method is similar to [[renderPartial()]] except that it will inject into
* the rendering result with JS/CSS scripts and files which are registered with the view.
* For this reason, you should use this method instead of [[renderPartial()]] to render
* a view to respond to an AJAX request.
*
* @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
*/
public function renderAjax($view, $params = [])
{
return $this->getView()->renderAjax($view, $params, $this);
}
/**
* Send data formatted as JSON.
*
* This method is a shortcut for sending data formatted as JSON. It will return
* the [[Application::getResponse()|response]] application component after configuring
* the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
* be formatted. A common usage will be:
*
* ```php
* return $this->asJson($data);
* ```
*
* @param mixed $data the data that should be formatted.
* @return Response a response that is configured to send `$data` formatted as JSON.
* @since 2.0.11
* @see Response::$format
* @see Response::FORMAT_JSON
* @see JsonResponseFormatter
*/
public function asJson($data)
{
$response = Yii::$app->getResponse();
$response->format = Response::FORMAT_JSON;
$response->data = $data;
return $response;
}
/**
* Send data formatted as XML.
*
* This method is a shortcut for sending data formatted as XML. It will return
* the [[Application::getResponse()|response]] application component after configuring
* the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
* be formatted. A common usage will be:
*
* ```php
* return $this->asXml($data);
* ```
*
* @param mixed $data the data that should be formatted.
* @return Response a response that is configured to send `$data` formatted as XML.
* @since 2.0.11
* @see Response::$format
* @see Response::FORMAT_XML
* @see XmlResponseFormatter
*/
public function asXml($data)
{
$response = Yii::$app->getResponse();
$response->format = Response::FORMAT_XML;
$response->data = $data;
return $response;
}
/**
* Binds the parameters to the action.
* This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
* This method will check the parameter names that the action requires and return
* the provided parameters according to the requirement. If there is any missing parameter,
* an exception will be thrown.
* @param \yii\base\Action $action the action to be bound with parameters
* @param array $params the parameters to be bound to the action
* @return array the valid parameters that the action can run with.
* @throws BadRequestHttpException if there are missing or invalid parameters.
*/
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$args = [];
$missing = [];
$actionParams = [];
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (array_key_exists($name, $params)) {
if ($param->isArray()) {
$args[] = $actionParams[$name] = (array)$params[$name];
} elseif (!is_array($params[$name])) {
$args[] = $actionParams[$name] = $params[$name];
} else {
throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
'param' => $name,
]));
}
unset($params[$name]);
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $actionParams[$name] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
if (!empty($missing)) {
throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
'params' => implode(', ', $missing),
]));
}
$this->actionParams = $actionParams;
return $args;
}
/**
* {@inheritdoc}
*/
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
}
return true;
}
return false;
}
/**
* Redirects the browser to the specified URL.
* This method is a shortcut to [[Response::redirect()]].
*
* You can use it in an action by returning the [[Response]] directly:
*
* ```php
* // stop executing this action and redirect to login page
* return $this->redirect(['login']);
* ```
*
* @param string|array $url the URL to be redirected to. This can be in one of the following formats:
*
* - a string representing a URL (e.g. "http://example.com")
* - a string representing a URL alias (e.g. "@example.com")
* - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
* [[Url::to()]] will be used to convert the array into a URL.
*
* Any relative URL that starts with a single forward slash "/" will be converted
* into an absolute one by prepending it with the host info of the current request.
*
* @param int $statusCode the HTTP status code. Defaults to 302.
* See <https://tools.ietf.org/html/rfc2616#section-10>
* for details about HTTP status code
* @return Response the current response object
*/
public function redirect($url, $statusCode = 302)
{
return Yii::$app->getResponse()->redirect(Url::to($url), $statusCode);
}
/**
* Redirects the browser to the home page.
*
* You can use this method in an action by returning the [[Response]] directly:
*
* ```php
* // stop executing this action and redirect to home page
* return $this->goHome();
* ```
*
* @return Response the current response object
*/
public function goHome()
{
return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
}
/**
* Redirects the browser to the last visited page.
*
* You can use this method in an action by returning the [[Response]] directly:
*
* ```php
* // stop executing this action and redirect to last visited page
* return $this->goBack();
* ```
*
* For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
*
* @param string|array $defaultUrl the default return URL in case it was not set previously.
* If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
* Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
* @return Response the current response object
* @see User::getReturnUrl()
*/
public function goBack($defaultUrl = null)
{
return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
}
/**
* Refreshes the current page.
* This method is a shortcut to [[Response::refresh()]].
*
* You can use it in an action by returning the [[Response]] directly:
*
* ```php
* // stop executing this action and refresh the current page
* return $this->refresh();
* ```
*
* @param string $anchor the anchor that should be appended to the redirection URL.
* Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
* @return Response the response object itself
*/
public function refresh($anchor = '')
{
return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
}
protected function initParams($p = [], $fields = [], $isFilter = false)
{
$params = [];
if (!empty($fields)) {
foreach ($fields as $key => $value) {
if (isset($p[$value]) && (!empty($p[$value]) || $p[$value] == 0)) {
$params[$value] = $p[$value];
} else {
if (!$isFilter) $params[$value] = null;
}
}
}
return $params;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-31
* Time: 下午1:28
*/
namespace wallet\base;
use yii\web\Response;
class BaseResponse extends Response
{
public function send()
{
//错误处理
$excpetion = \Yii::$app->errorHandler->exception;
if ($excpetion !== null) {
$this->data = [
'code' => $excpetion->getCode(),
'msg' => $excpetion->getMessage(),
'line' => $excpetion->getLine(),
'file' => $excpetion->getFile(),
];
}
//TODO 在这里对数据进行format,这样控制器中可以直接return一个array,保存到数据域data中即可,eg:['code'=>0,'data'=>$data]
$data = \Yii::$app->response->data;
if (empty($data)) {
$return['code'] = 1;
$return['msg'] = '数据为空';
} elseif (is_array($data) && !isset($data['code'])) {
$return['code'] = 0;
$return['count'] = count($data);
$return['data'] = $data;
} else {
$return = $data;
}
if (YII_ENV_DEV) {
#$return['time'] = \Yii::$app->controller->end - \Yii::$app->controller->start;
}
\Yii::$app->response->data = $return;
parent::send();
}
}
\ No newline at end of file
<?php
namespace wallet\base;
use yii\helpers\Html;
use yii\web\Response;
class ResponseMsg
{
public $is_support_jsonp = false;
public $header_list = [];
private static $default_header_list = [];
public function __construct()
{
// if ('cli' !== php_sapi_name()){
// $this->header_list = self::$default_header_list;
// $this->fzmCrossHeader();
// }
}
public function fzmCrossHeader()
{
$allow_list = \Yii::$app->params['allow_options_domain']['common'];
$origin = \Yii::$app->request->headers->get('Origin');
if (!in_array($origin, $allow_list)) {
$origin = implode(',', $allow_list);
}
$this->header('Access-Control-Allow-Origin', $origin);
$this->header('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
$this->header('Access-Control-Allow-Credentials', 'true');
$this->header('Access-Control-Allow-Headers', 'Authorization,FZM-REQUEST-OS,FZM-USER-IP,FZM-REQUEST-UUID,Content-Type,Content-Length');
}
public static function setDefaultHeader($default_header_list)
{
foreach ($default_header_list as $key => $header) {
self::$default_header_list[$key] = $header;
}
}
public static function getDefaultHeader()
{
return self::$default_header_list;
}
public function arrSuccess($data = BaseConstant::OK, $code = 200)
{
return [BaseConstant::ERROR => false, BaseConstant::MESSAGE => $data, BaseConstant::CODE => $code];
}
public function arrFail($data, $code = -1)
{
return [BaseConstant::ERROR => true, BaseConstant::MESSAGE => $data, BaseConstant::CODE => $code];
}
/**
* 失败返回接口
* @param string $msg
* @param int $code
* @return string
*/
public function jsonError($msg = '', $code = -1)
{
if (empty($msg)) {
$msg = 'unknown error';
}
$view = [
BaseConstant::CODE => $code,
BaseConstant::MESSAGE => $msg,
];
$json = json_encode($view);
return $this->dumpJsonData($json);
}
/**
* 成功返回接口
* @param string $msg
* @param int $code
* @return string
*/
public function jsonSuccess($data = '', $code = 200)
{
$view = [
BaseConstant::CODE => $code,
BaseConstant::MESSAGE => BaseConstant::OK,
BaseConstant::DATA => $data
];
$json = json_encode($view);
return $this->dumpJsonData($json);
}
/**
* 直接处理接口数据
* @param $ret
*/
public function dealRet($ret)
{
if (true === $ret[BaseConstant::ERROR]) {
$this->jsonError($ret[BaseConstant::MESSAGE] ? : 'unknown error');
} else {
$this->jsonSuccess($ret[BaseConstant::MESSAGE] ? : BaseConstant::OK);
}
}
/**
* 根据是否为JSONP做特殊处理输出
* @param $json
* @return string
*/
public function dumpJsonData($json)
{
$callback = '';
if (true === $this->is_support_jsonp) {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
$callback_key = 'jsonpcallback';
$callback = $_GET[$callback_key];
if ($callback) {
$callback = Html::encode($callback_key);
$json = $callback . '(' . $json . ')';
}
}
if (!$callback && !$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return $json;
}
/**
* @param $json_str
* @param string $callback_key
* @return string
*/
public function printByJson($json_str, $callback_key = '')
{
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . $json_str . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return $json_str;
}
}
/**
* @param $arr
* @param string $callback_key
* @return string
*/
public function printByArr($arr, $callback_key = '')
{
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
public function printOldFail($code, $code_msg, $detail_code, $detail_msg, $callback_key = '')
{
$this->fzmCrossHeader();
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
$arr = ['code' => $code, 'error' => $code_msg, 'ecode' => $detail_code, 'message' => $detail_msg, 'data' => []];
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
/**
* @param $success_data
* @param string $callback_key
* @return string
*/
public function printOldSuccess($success_data, $callback_key = '')
{
$this->fzmCrossHeader();
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
$arr = ['code' => 200, 'ecode' => 200, 'error' => 'OK', 'message' => 'OK', 'data' => $success_data];
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
/**
* 解决xdebug cookie设置不了的问题
*/
private function isDebug()
{
if (defined('SERVICE_ENV') && (SERVICE_ENV === 'test' || SERVICE_ENV === 'local') && isset($_GET['debug'])) {
return true;
}
return false;
}
public function header($key, $value)
{
$this->header_list[$key] = $value;
}
public function getHeaders()
{
return $this->header_list;
}
public function withHeaders($header_arr)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
foreach ($header_arr as $key => $val) {
\Yii::$app->response->headers->add($key, $val);
}
return $this;
}
public function withContent($content)
{
return $content;
}
}
namespace: backend\tests
actor: Tester
paths:
tests: tests
log: tests/_output
data: tests/_data
helpers: tests/_support
settings:
bootstrap: _bootstrap.php
colors: true
memory_limit: 1024M
modules:
config:
Yii2:
configFile: 'config/test-local.php'
main-local.php
params-local.php
\ No newline at end of file
<?php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'timeZone' => 'Etc/GMT-8',
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'defaultRoute' => 'site/index',
'layout' => 'main',
'modules' => [],
'components' => [
'request' => [
'class' => 'common\core\Request',
'baseUrl' => '/admin',
'cookieValidationKey' => 'Yr4XDePew55tutE3CVZ7vBUqVO3iorN6',
//'csrfParam' => '_csrf-backend',
],
'session' => [
'name' => 'manage-backend',
],
'errorHandler' => [
'errorAction' => 'public/error',
],
'urlManager' => [
'class' => 'common\core\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
]
],
'params' => $params,
];
<?php
return [
'adminEmail' => 'admin@example.com',
/* 后台错误页面模板 */
'action_error' => '@backend/views/public/error.php', // 默认错误跳转对应的模板文件
'action_success' => '@backend/views/public/success.php', // 默认成功跳转对应的模板文件
];
<?php
namespace wallet\controllers;
use common\models\psources\CoinPlatformWithHold;
use common\service\chain33\Chain33Service;
use Yii;
use wallet\base\BaseController;
use yii\data\Pagination;
class MonitorController extends BaseController
{
/**
* landing
* @return array
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function actionList()
{
$msg = 'ok';
$code = 0;
$page = Yii::$app->request->get('page', 1);
$query = CoinPlatformWithHold::find()->select('id, platform, address')->asArray();
$count = $query->count();
if( 0 == $count ) {
$msg = '数据不存在';
$code = -1;
$data = null;
goto doEnd;
}
$models = $query->offset(($page - 1) * 10)->limit(10)->asArray()->all();
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => '10']);
$address = [];
foreach ($models as $model){
$address[] = $model['address'];
}
if(empty($address)){
$data = null;
goto doEnd;
}
$service = new Chain33Service();
$execer = 'coins';
$result = $service->getBalance($address, $execer);
if(0 != $result['code']){
$msg = $result['msg'];
$code = -1;
goto doEnd;
}
$result_balance = $result['result'];
$balance_arr = [];
foreach ($result_balance as $key => $val){
$balance_arr[$val['addr']] = $val;
}
foreach ($models as &$model){
$model['balance'] = $balance_arr[$model['address']]['balance'];
}
$data = [
'list' => $models,
'page' => [
'pageCount' => $pages->pageCount,
'pageSize' => 10,
'currentPage' => $page,
]
];
doEnd :
return ['code' => $code, 'msg' => $msg, 'data' => $data];
}
}
\ No newline at end of file
<?php
namespace wallet\controllers;
use Yii;
use common\models\Admin;
use common\models\LoginForm;
use wallet\base\BaseController;
use common\service\trusteeship\TrusteeShipService;
class UserController extends BaseController
{
/**
* landing
* @return array
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function actionLogin()
{
$msg = 'ok';
$code = 0;
$model = new LoginForm();
$model->setScenario(LoginForm::SCENARIOS_LOGIN);
$model->load(Yii::$app->request->post(), '');
if (!$model->login()) {
$msg = implode(", ", \yii\helpers\ArrayHelper::getColumn($model->errors, 0, false)); // Model's Errors string
$data = null;
$code = -1;
goto doEnd;
}
$data = ['access_token' => $model->login()];
doEnd :
return ['code' => $code, 'msg' => $msg, 'data' => $data];
}
public function actionUserInfo()
{
$msg = 'ok';
$code = 0;
$token_string = Yii::$app->request->headers->get('Token');
$user = Admin::findIdentityByAccessToken($token_string);
$data = [
'username' => $user->username,
'uid' => isset($user->bind_uid) ? $user->bind_uid : $user->uid,
'type' => isset($user->bind_uid) ? 2 : 1,
'platform_id' => $user->platform_id
];
return ['code' => $code, 'msg' => $msg, 'data' => $data];
}
/**
* 用户同步
*/
public function actionUserSync()
{
$items = Yii::$app->request->post();
if (count($items['items']) > 10) {
return ['code' => -1, 'data' => [], 'msg' => '一次最多同步20条数据'];
}
$duplicate = 0;
foreach ($items['items'] as $key => $item) {
$model = Admin::find()->where(['username' => $item['username']])->andWhere(['platform_id' => (int)$item['platform']])->one();
if ($model) {
$duplicate++;
continue;
}
$datas[] = [
$item['bind_uid'],
$item['username'],
Yii::$app->security->generateRandomString(),
Yii::$app->security->generatePasswordHash('123456'),
time(),
ip2long('127.0.0.1'),
0,
ip2long('127.0.0.1'),
0,
1,
$item['platform']
];
}
if (!empty($datas)) {
Admin::loadArray($datas);
}
return ['code' => 1, 'data' => [], 'msg' => '数据更新成功,共有 ' . $duplicate . ' 条重复'];
$header = Yii::$app->request->headers;
$platform_id = $header['platform_id'] ?? 17;
$post = Yii::$app->request->post();
$data = [
'bind_uid' => $post['bind_uid'],
'username' => $post['username'],
'salt' => Yii::$app->security->generateRandomString(),
'password' => Yii::$app->security->generatePasswordHash('123456'),
'reg_time' => time(),
'reg_ip' => ip2long('127.0.0.1'),
'last_login_time' => 0,
'last_login_ip' => ip2long('127.0.0.1'),
'update_time' => 0,
'status' => 1,
'platform_id' => $platform_id
];
$role = Yii::$app->request->post('role', 'GHPwallet');
$model = new Admin();
if ($model->load($data, '') && $model->save()) {
$auth = Yii::$app->authManager;
$role = $auth->getRole($role);
$auth->assign($role, $model->uid);
exit;
} else {
var_dump($model->errors);
exit;
}
}
/**
* 用户列表
*/
public function actionUserList()
{
$current_platform_id = Yii::$app->request->getPlatformId();
if(1 === $current_platform_id) {
$platform_id = Yii::$app->request->get('platform_id', 1);
$platform_id = empty($platform_id) ? 1 : $platform_id;
} else {
$platform_id = Yii::$app->request->getPlatformId();
}
if(!isset(Yii::$app->params['trusteeship']['node_'. $platform_id])){
return ['code' => -1, 'data' => [], 'msg' => '此钱包节点尚未开通'];
}
$node_params = Yii::$app->params['trusteeship']['node_'. $platform_id];
$page = Yii::$app->request->get('page', 1);
$size = Yii::$app->request->get('size', 15);
$real_type = Yii::$app->request->get('real_type', '');
$search_type = Yii::$app->request->get('search_type', 'user');
$search = Yii::$app->request->get('search', '');
$start_time = Yii::$app->request->get('start_time', '');
$end_time = Yii::$app->request->get('end_time', '');
$params = [
'page' => $page,
'size' => $size,
'real_type' => $real_type,
'search_type' => $search_type,
'search' => $search,
'start_time' => $start_time,
'end_time' => $end_time
];
$service = new TrusteeShipService($node_params);
$result = $service->getUserList($params);
if (200 !== $result['code']) {
return ['code' => $result['code'], 'data' => [], 'msg' => $result['msg']];
}
return ['code' => 1, 'data' => $result['msg'], 'msg' => 'success'];
}
}
\ No newline at end of file
<?php
namespace wallet\controllers;
use common\service\trusteeship\TrusteeShipService;
use Yii;
use common\models\Admin;
use wallet\base\BaseController;
use common\models\psources\CoinPlatform;
class WalletController extends BaseController
{
/**
* landing
* @return array
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function actionList()
{
$platform_id = Yii::$app->request->getPlatformId();
if (1 === $platform_id) {
$platforms = CoinPlatform::find()->select('id, name')->asArray()->all();
} else {
$platforms = CoinPlatform::find()->select('id, name')->where(['id' => $platform_id])->asArray()->all();
}
return ['code' => 0, 'msg' => 'ok', 'data' => $platforms];
}
public function actionWalletBallance()
{
$current_platform_id = Yii::$app->request->getPlatformId();
if(1 === $current_platform_id) {
$platform_id = Yii::$app->request->get('platform_id', 1);
$platform_id = empty($platform_id) ? 1 : $platform_id;
} else {
$platform_id = Yii::$app->request->getPlatformId();
}
if(!isset(Yii::$app->params['trusteeship']['node_'. $platform_id])){
return ['code' => -1, 'data' => [], 'msg' => '此钱包节点尚未开通'];
}
$node_params = Yii::$app->params['trusteeship']['node_'. $platform_id];
$type = Yii::$app->request->get('type', 1);
$page = Yii::$app->request->get('page', 1);
$size = Yii::$app->request->get('size', 15);
$currency = Yii::$app->request->get('currency ', '');
$params = [
'type' => $type,
'page' => $page,
'size' => $size,
'currency' => $currency
];
$service = new TrusteeShipService($node_params);
$result = $service->getWalletBalance($params);
if (200 !== $result['code']) {
return ['code' => $result['code'], 'data' => [], 'msg' => $result['msg']];
}
return ['code' => 1, 'data' => $result['msg'], 'msg' => 'success'];
}
public function actionUserAsset()
{
$platform_id = Yii::$app->request->getPlatformId();
$node_params = Yii::$app->params['trusteeship']['node_'. $platform_id];
$uid = Yii::$app->request->get('uid', '');
$params = [
'uid' => $uid
];
$service = new TrusteeShipService($node_params);
$result = $service->getUserAsset($params);
if (200 !== $result['code']) {
return ['code' => $result['code'], 'data' => [], 'msg' => $result['msg']];
}
return ['code' => 1, 'data' => $result['msg'], 'msg' => 'success'];
}
}
\ No newline at end of file
*
!.gitignore
\ No newline at end of file
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', __DIR__.'/../../');
require_once YII_APP_BASE_PATH . '/vendor/autoload.php';
require_once YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php';
require_once YII_APP_BASE_PATH . '/common/config/bootstrap.php';
require_once __DIR__ . '/../config/bootstrap.php';
<?php
return [
[
'username' => 'erau',
'auth_key' => 'tUu1qHcde0diwUol3xeI-18MuHkkprQI',
// password_0
'password_hash' => '$2y$13$nJ1WDlBaGcbCdbNC5.5l4.sgy.OMEKCqtDQOdQ2OWpgiKRWYyzzne',
'password_reset_token' => 'RkD_Jw0_8HEedzLk7MM-ZKEFfYR7VbMr_1392559490',
'created_at' => '1392559490',
'updated_at' => '1392559490',
'email' => 'sfriesen@jenkins.info',
],
];
<?php
namespace backend\tests;
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class FunctionalTester extends \Codeception\Actor
{
use _generated\FunctionalTesterActions;
/**
* Define custom actions here
*/
}
<?php
namespace backend\tests;
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class UnitTester extends \Codeception\Actor
{
use _generated\UnitTesterActions;
/**
* Define custom actions here
*/
}
class_name: FunctionalTester
modules:
enabled:
- Yii2
<?php
namespace backend\tests\functional;
use backend\tests\FunctionalTester;
use common\fixtures\UserFixture;
/**
* Class LoginCest
*/
class LoginCest
{
/**
* Load fixtures before db transaction begin
* Called in _before()
* @see \Codeception\Module\Yii2::_before()
* @see \Codeception\Module\Yii2::loadFixtures()
* @return array
*/
public function _fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => codecept_data_dir() . 'login_data.php'
]
];
}
/**
* @param FunctionalTester $I
*/
public function loginUser(FunctionalTester $I)
{
$I->amOnPage('/site/login');
$I->fillField('Username', 'erau');
$I->fillField('Password', 'password_0');
$I->click('login-button');
$I->see('Logout (erau)', 'form button[type=submit]');
$I->dontSeeLink('Login');
$I->dontSeeLink('Signup');
}
}
<?php
/**
* Here you can initialize variables via \Codeception\Util\Fixtures class
* to store data in global array and use it in Cests.
*
* ```php
* // Here _bootstrap.php
* \Codeception\Util\Fixtures::add('user1', ['name' => 'davert']);
* ```
*
* In Cests
*
* ```php
* \Codeception\Util\Fixtures::get('user1');
* ```
*/
\ No newline at end of file
class_name: UnitTester
<?php
/**
* Here you can initialize variables via \Codeception\Util\Fixtures class
* to store data in global array and use it in Tests.
*
* ```php
* // Here _bootstrap.php
* \Codeception\Util\Fixtures::add('user1', ['name' => 'davert']);
* ```
*
* In Tests
*
* ```php
* \Codeception\Util\Fixtures::get('user1');
* ```
*/
/index-test.php
/robots.txt
/upload
\ No newline at end of file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: rlgyzhcn
* Date: 18-5-3
* Time: 下午12:53
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
$config = yii\helpers\ArrayHelper::merge(
require __DIR__ . '/../../common/config/main.php',
require __DIR__ . '/../../common/config/main-local.php',
require __DIR__ . '/../config/main.php',
require __DIR__ . '/../config/main-local.php'
);
(new yii\web\Application($config))->run();
\ No newline at end of file
/**
* 自定义刷新提示
*/
var whenShowLoading=null;
var showMyLoading=function () {
if (typeof(layer) === 'object' && whenShowLoading === null) {
whenShowLoading = layer.load(2, {shade: false});
}
return true;
};
var hideMyLoading=function () {
if (typeof(layer) === 'object' && whenShowLoading !== null) {
layer.close(whenShowLoading);
whenShowLoading = null;
}
return true;
};
/**
* Bootstrap Table Chinese translation
*/
(function ($) {
'use strict';
$.fn.bootstrapTable.locales['zh-CN'] = {
contentType: "application/x-www-form-urlencoded",
striped: true, //设置为 true 会有隔行变色效果
cache: false, //设置为 false 禁用 AJAX 数据缓存
silent: true, //静默刷新方式 refresh {silent: true}
dataType: "json", //服务器返回的数据类型
queryParamsType:'', //queryParams {pageSize, pageNumber, searchText, sortName, sortOrder}
undefinedText: '', //当数据为 undefined 时显示的字符
sidePagination: "server", //服务器分页
pagination: true, //设置为 true 会在表格底部显示分页条
paginationLoop: false, //设置为 true 启用分页条无限循环的功能
/*fixedColumns: true,
fixedNumber: 2,*/
paginationPreText: '上一页',
paginationNextText: '下一页',
ajaxOptions: function () {
if (typeof(request_token) === 'string') {
return {
headers: {"Authorization": 'Bearer ' + request_token}
};
} else {
return {};
}
},
formatLoadingMessage: function () {
return '';
},
formatRecordsPerPage: function (pageNumber) {
return '';//'每页显示 ' + pageNumber + ' 条记录';
},
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return '<span style="font-size: 11px">第 <b>'+pageFrom+'</b>-<b>'+pageTo+'</b> 条,共 <b>'+totalRows+'</b> 条数据. </span>';
//return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录,总共 ' + totalRows + ' 条记录';
},
formatSearch: function () {
return '搜索';
},
formatNoMatches: function () {
return '<span style="color: #9e9e9e">没有找到匹配的记录</span>';
},
formatPaginationSwitch: function () {
return '隐藏/显示分页';
},
formatRefresh: function () {
return '刷新';
},
formatToggle: function () {
return '切换';
},
formatColumns: function () {
return '列';
},
formatExport: function () {
return '导出';
},
formatClearFilters: function () {
return '清空过滤';
},
onLoadSuccess: function () {
return hideMyLoading();
},
onLoadError: function () {
return hideMyLoading();
},
onRefresh: function () {
return showMyLoading();
},
onPageChange: function () {
return showMyLoading();
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['zh-CN']);
})(jQuery);
\ 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