订单查询
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_2
423154
public function orderQuery($params,$timeOut=6){

         $url='https://api.mch.weixin.qq.com/pay/orderquery';

         $inputObj=new WxPayParam();
         $inputObj->setValues($params); //置入参数
         if(!$inputObj->isKeySet("transaction_id")&&!$inputObj->isKeySet("out_trade_no")){
             throw new \Exception("订单查询接口中，out_trade_no、transaction_id至少填一个！");
         }
         $inputObj->setValueByKey("appid",Config::getAppId());
         $inputObj->setValueByKey("mch_id",Config::getMchid());
         $inputObj->setValueByKey("nonce_str",static::getNonceStr()); //随机字符串

         //签名
         $inputObj->SetSign();
         $xml = $inputObj->ToXml();

         $startTimeStamp = self::getMillisecond();//请求开始时间
         $response=static::postXmlCurl($xml,$url,false,$timeOut);
         $result=WxPayResult::Init($response);

         //上报数据
         $this->reportCostTime($url,$startTimeStamp,$result);

         return $result;


     }
306755
@Override
    public WxResp card_code_get(String code, String cardId, Boolean checkConsume) {
    	NutMap body = NutMap.NEW().addv("code", code);
    	if (cardId != null) {
    		body.addv("card_id", cardId);
    	}
    	if (checkConsume != null) {
    		body.addv("check_consume", checkConsume);
    	}

    	// 由于查询Code API中没有“/cgi-bin”，所以uri不能只写“/card/code/get”
    	return postJson("https://api.weixin.qq.com/card/code/get", body);
    }
1011097
function analyUrl(ctx, path) {
    // 如果是标准的url，则以http或者https开头
    // 则直接发送请求不做处理
    let isUrl = /^(http:\/\/|https:\/\/)/;
    if (isUrl.test(path)) {
      return {
        url: path,
        method: ctx.method
      }
    }

    // 否则，用"?"切分URL："?"前部用以解析真实的URL
    let urlQueryArr = path.split('?');
    let urlPrefix = urlQueryArr[0] || '';

    // url前部只能包含1个或2个":"，否则报错
    let urlReg = urlPrefix.split(':');
    if (urlReg.length < 2 || urlReg.length > 3) {
      throw `Illegal proxy path：${path} !`;
    }

    let [apiName, urlMethod, urlPath] = urlReg;
    let urlOrigin = getOriginApi(api, apiName);

    if (!urlPath) {
      urlPath = urlMethod;
      urlMethod = ctx.method;
    }

    // 拼接URL
    let urlHref = url_opera.resolve(urlOrigin, urlPath)
    return {
      url: path.replace(urlPrefix, urlHref),
      method: urlMethod.toUpperCase()
    }
  }
281389
function getAudioCard(){
        $listTemplate = new ListTemplate1();
        //设置模板token
        $tokenArr = array(
            'page' => 'audio',
        );
        $listTemplate->setToken($this->genToken($tokenArr));
        //设置模板标题
        $listTemplate->setTitle('音频示例');
        //getaudioCard
        $audioList = $this->getPlayList(self::TYPE_AUDIO);
        if(is_array($audioList)&&$audioList){
            foreach($audioList as $audio){
                $id = isset($audio['id']) && $audio['id']?$audio['id']:'';
                $title = isset($audio['title']) && $audio['title']?$audio['title']:'';
                $introduction = isset($audio['intro']) && $audio['intro']?$audio['intro']:'';
                $picUrl = isset($audio['picurl']) && $audio['picurl']?$audio['picurl']:'';
            
                $token = array(
                    'page' => 'audio',
                    'item' => strval($id)
                );   
                //设置模版列表数组listItems其中一项，即列表的一个元素
                $listTemplateItem = new ListTemplateItem();
                $listTemplateItem->setToken($this->genToken($token));
                $listTemplateItem->setImage($picUrl);
                $listTemplateItem->setPlainPrimaryText($title);
                $listTemplateItem->setPlainSecondaryText($introduction);
                
                //把listTemplateItem添加到模版listItems
                $listTemplate->addItem($listTemplateItem);
            }
        }
        //定义RenderTemplate指令
        $template = new RenderTemplate($listTemplate);
        return $template;
    }
141053
def aStockQoutation(self,code):
        '''
        
        '''

        #设置监听-->订阅-->调用接口

        # 分时
        self.quote_ctx.set_handler(RTDataTest())
        self.quote_ctx.subscribe(code, SubType.RT_DATA)
        ret_code_rt_data, ret_data_rt_data = self.quote_ctx.get_rt_data(code)
        # 逐笔
        self.quote_ctx.set_handler(TickerTest())
        self.quote_ctx.subscribe(code, SubType.TICKER)
        ret_code_rt_ticker, ret_data_rt_ticker = self.quote_ctx.get_rt_ticker(code)
        # 报价
        self.quote_ctx.set_handler(StockQuoteTest())
        self.quote_ctx.subscribe(code, SubType.QUOTE)
        ret_code_stock_quote, ret_data_stock_quote = self.quote_ctx.get_stock_quote([code])
        # 实时K线
        self.quote_ctx.set_handler(CurKlineTest())
        kTypes = [SubType.K_1M, SubType.K_5M, SubType.K_15M, SubType.K_30M, SubType.K_60M, SubType.K_DAY,
                  SubType.K_WEEK, SubType.K_MON]
        auTypes = [AuType.NONE, AuType.QFQ, AuType.HFQ]
        num = 10
        ret_code_cur_kline = RET_OK
        for kType in kTypes:
            self.quote_ctx.subscribe(code, kType)
            for auType in auTypes:
                ret_code_cur_kline_temp, ret_data_cur_kline = self.quote_ctx.get_cur_kline(code, num, kType, auType)
                if ret_code_cur_kline_temp is RET_ERROR:
                    ret_code_cur_kline = RET_ERROR
        # 摆盘
        self.quote_ctx.set_handler(OrderBookTest())
        self.quote_ctx.subscribe(code, SubType.ORDER_BOOK)
        ret_code_order_book, ret_data_order_book = self.quote_ctx.get_order_book(code)
        # 经纪队列
        self.quote_ctx.set_handler(BrokerTest())
        self.quote_ctx.subscribe(code, SubType.BROKER)
        ret_code_broker_queue, bid_frame_table, ask_frame_table = self.quote_ctx.get_broker_queue(code)

        return ret_code_rt_data+ret_code_rt_ticker+ret_code_stock_quote+ret_code_cur_kline+ret_code_order_book+ret_code_broker_queue
258574
public function beforeSwooleStart()
    {
        parent::beforeSwooleStart();
        //创建task用的taskid
        $this->task_atomic = new \swoole_atomic(0);
        //创建task用的id->pid共享内存表不至于同时超过1024个任务吧
        $this->tid_pid_table = new \swoole_table(1024);
        $this->tid_pid_table->column('pid', \swoole_table::TYPE_INT, 8);
        $this->tid_pid_table->column('des', \swoole_table::TYPE_STRING, 100);
        $this->tid_pid_table->column('start_time', \swoole_table::TYPE_INT, 8);
        $this->tid_pid_table->create();
        //创建task用的锁
        $this->task_lock = new \swoole_lock(SWOOLE_MUTEX);
        //开启用户进程
        $this->startProcess();
        //开启一个UDP用于发graylog
        GrayLogHelp::init();
        //开启Cluster端口
        ClusterHelp::getInstance()->buildPort();
        //Timer
        Timer::init();
        //init锁
        $this->initLock = new \swoole_lock(SWOOLE_RWLOCK);
        //reload锁
        for ($i = 0; $i < $this->worker_num; ++$i) {
            $lock = new \swoole_lock(SWOOLE_MUTEX);
            $this->reloadLockMap[$i] = $lock;
        }
    }
38960
function nativeRequire( ids, callback, baseId, noRequests ) {
        // 根据 https://github.com/amdjs/amdjs-api/wiki/require
        // It MUST throw an error if the module has not
        // already been loaded and evaluated.
        if ( typeof ids === 'string' ) {
            modTryInvokeFactory( ids );
            if ( !modIs( ids, MODULE_DEFINED ) ) {
                throw new Error( '[MODULE_MISS]"' + ids + '" is not exists!' );
            }

            return modGetModuleExports( ids );
        }

        noRequests = noRequests || {};
        var isCallbackCalled = 0;
        if ( ids instanceof Array ) {
            modAutoInvoke();
            tryFinishRequire();

            if ( !isCallbackCalled ) {
                each( ids, function ( id ) {

                    if ( !(BUILDIN_MODULE[ id ] || modIs( id, MODULE_DEFINED )) ) {
                        modAddDefinedListener( id, tryFinishRequire );

                        if ( !noRequests[ id ] ) {
                            ( id.indexOf( '!' ) > 0
                                ? loadResource
                                : loadModule
                            )( id, baseId );
                        }
                    }

                } );
            }
        }

        /**
         * 尝试完成require，调用callback
         * 在模块与其依赖模块都加载完时调用
         *
         * @inner
         */
        function tryFinishRequire() {
            if ( !isCallbackCalled ) {
                var isAllCompleted = 1;
                each( ids, function ( id ) {
                    if ( !BUILDIN_MODULE[ id ] ) {
                        return ( isAllCompleted = !!modIs( id, MODULE_DEFINED ) );
                    }
                });

                // 检测并调用callback
                if ( isAllCompleted ) {
                    isCallbackCalled = 1;

                    (typeof callback === 'function') && callback.apply(
                        global,
                        modGetModulesExports( ids, BUILDIN_MODULE )
                    );
                }
            }
        }
    }
984863
public function getWxPayAppApiParameters($prepayId)
    {
        // 获取App支付的参数
        $input = [
            // 应用ID
            'appid' => $this->appId,
            // 商户号
            'partnerid' => $this->mchId,
            // 预支付交易会话ID
            'prepayid' => $prepayId,
            // 扩展字段
            'package' => 'Sign=WXPay',
            // 随机字符串
            'noncestr' => SHA1::get_random_str(32),
            // 时间戳
            'timestamp' => (string)time(),
        ];
        // 签名
        $input['paySign'] = SHA1::getSign2($input, 'key='.$this->key);
        return $input;
    }
603938
public function parseURL() {

        $appConfigs = getConfigs(); //获取app配置

        self::$urlMappingRules = $appConfigs['url_mapping_rules'];
        //优先处理短链接映射
        $this->requestUri = self::url2source($this->requestUri);
        $_SERVER['REQUEST_URI'] = $this->requestUri;

        $defaultUrl = $appConfigs['default_url'];
        $urlInfo = parse_url($this->requestUri);

        if ( $urlInfo['path'] && $urlInfo['path'] != '/' ) {
            $filename = str_replace(EXT_URI, '', $urlInfo['path']);
            $filename = rtrim($filename, "/");
            $pathInfo = explode('/', $filename);
            array_shift($pathInfo);
            if ( $pathInfo[0] ) $this->setModule($pathInfo[0]);
            if ( $pathInfo[1] ) $this->setAction($pathInfo[1]);
            if ( $pathInfo[2] ) $this->setMethod($pathInfo[2]);

            //提取pathinfo参数
            if ( count($pathInfo) > 3 ) {
                if ( isset($pathInfo[3]) ) {
                    $params = explode('-', $pathInfo[3]);
                    for ( $i = 0; $i < count($params); $i++ ) {
                        if ( $i % 2 == 0 ) {
                            if ( trim($params[$i]) == '' ) {
                                continue;
                            }
                            $_GET[$params[$i]] = $params[$i+1];
                        }
                    }
                }
            }

            //提取query参数
            if ( isset($urlInfo['query']) ) {
                $params = explode('&', $urlInfo['query']);
                foreach ( $params as $values ) {
                    $__p = explode('=', $values);
                    if ( trim($__p[0]) == '' ) {
                        continue;
                    }
                    $_GET[$__p[0]] = urldecode($__p[1]);
                }
            }

        }

        //如果没有任何参数，则访问默认页面。如http://www.herosphp.my这种格式
        if ( !$this->module ) $this->setModule($defaultUrl['module']);
        if ( !$this->action ) $this->setAction($defaultUrl['action']);
        if ( !$this->method ) $this->setMethod($defaultUrl['method']);

        $this->setParameters($_GET + $_POST);

        //die();
    }
458083
public com.riversoft.weixin.pay.payment.bean.OrderQueryResponse query(com.riversoft.weixin.pay.payment.bean.OrderQueryRequest orderQueryRequest) {
        OrderQueryRequestWrapper wrapper = new OrderQueryRequestWrapper();
        wrapper.setRequest(orderQueryRequest);
        setBaseSettings(wrapper);
        SortedMap<String, Object> queryRequestMap = JsonMapper.nonEmptyMapper().getMapper().convertValue(wrapper, SortedMap.class);
        sign(wrapper, queryRequestMap);

        String url = WxEndpoint.get("url.pay.payment.order.query");
        try {
            String xml = XmlObjectMapper.nonEmptyMapper().toXml(wrapper);
            logger.info("支付 query order request: {}", xml);
            String response = wxSslClient.post(url, xml);
            logger.info("支付 query order response: {}", response);

            OrderQueryResponseWrapper responseWrapper = XmlObjectMapper.defaultMapper().fromXml(response, OrderQueryResponseWrapper.class);
            return responseWrapper.getResponse();
        } catch (Exception e) {
            throw new WxRuntimeException(999, "query order failed:" + e.getMessage());
        }

    }
757129
function nativeRequire( ids, callback, baseId ) {
        // 根据 https://github.com/amdjs/amdjs-api/wiki/require
        // It MUST throw an error if the module has not
        // already been loaded and evaluated.
        if ( typeof ids === 'string' ) {
            if ( !modIsDefined( ids ) ) {
                throw new Error( '[MODULE_MISS]"' + ids + '" is not exists!' );
            }

            return modGetModuleExports( ids );
        }

        var isCallbackCalled = 0;
        if ( isArray( ids ) ) {
            tryFinishRequire();

            !isCallbackCalled && each(
                ids,
                function ( id ) {
                    if ( !BUILDIN_MODULE[ id ] ) {
                        // 以低优先级触发模式挂载监听器
                        // 循环依赖中能先完成依赖其模块的定义
                        modAddDefinedListener( id, tryFinishRequire, 1 );
                        ( id.indexOf( '!' ) > 0
                            ? loadResource
                            : loadModule
                        )( id, baseId );
                    }
                }
            );
        }

        /**
         * 尝试完成require，调用callback
         * 在模块与其依赖模块都加载完时调用
         *
         * @ignore
         */
        function tryFinishRequire() {
            if ( !isCallbackCalled ) {
                var isAllCompleted = 1;
                each( ids, function ( id ) {
                    if ( !BUILDIN_MODULE[ id ] ) {
                        return ( isAllCompleted = modIsCompleted( id ) );
                    }
                });

                // 检测并调用callback
                if ( isAllCompleted ) {
                    isCallbackCalled = 1;

                    (typeof callback === 'function') && callback.apply(
                        global,
                        modGetModulesExports( ids, BUILDIN_MODULE )
                    );
                }
            }
        }
    }
738443
async function removeMulti(ctx) {
  let { Model } = ctx.state;
  let code = Model.api.removeMulti;
  if (code > _alaska.PUBLIC && !ctx.user) {
    //未登录,需要认证
    ctx.status = 401;
    return;
  }
  ctx.body = {};
  let filters = await Model.createFiltersByContext(ctx);

  if (code === _alaska.OWNER) {
    //只允许用户列出自己的资源
    let { userField } = Model.userField;
    // $Flow 这里可以确认ctx.user存在
    filters[userField] = ctx.user._id;
  }

  let res = await Model.deleteMany(filters);

  ctx.body = {
    removed: res.n
  };
}
1225581
function _TPL(ctx)
{
    let method = ctx.method;
    let route = url.parse(ctx.url).pathname.substr(1);
    isDebug && console.log('route',route,ctx.url)
    let data = null;
    let routeName ;//路由名字

    if(((itFace[route] && itFace[route].method == method) || 
        (itFace[`${route}_${method}`] && itFace[`${route}_${method}`].method == method)) 
        && !isDebug){
        if(itFace[route] && itFace[route].method == method){
            routeName = route;
        }
        if(itFace[`${route}_${method}`] && itFace[`${route}_${method}`].method == method){
            routeName = `${route}_${method}`;
        }
        data = itFace[`${routeName}`];
    }else{
        //读取接口文档,并缓存起来
        // console.log('aaaa',`${interFaceRoot}${`${route}_${method}`}.json`)
        if(isExist(path.join(`${interFaceRoot}${route}.json`))){
            data = fs.readFileSync(path.join(`${interFaceRoot}${route}.json`), 'utf-8');
            try {
                data = eval('('+data+')');
            }catch (err){
                return {TPL:"接口文档定义错误!"}
            }
            //如果请求方法对不上,则清空现有数据
            if(!data || data.method != method){//
                data = null;
            }else {
                itFace[route] = data;
                routeName = route;
            }
        }
        //如果本文件不存在,则通过匹配文件名加上请求参数
        if(!data && isExist(path.join(`${interFaceRoot}${`${route}_${method}`}.json`))){
            data = fs.readFileSync(path.join(`${interFaceRoot}${`${route}_${method}`}.json`), 'utf-8');
            try {
                data = eval('('+data+')');
            }catch (err){
                data = null;
            }
            if(!data || data.method != method){//
                data = null;
            }else {
                itFace[route] = data;
                routeName = route;
            }
        }
        if(data){
            //处理数据中,含有的特殊字符
            let map={"{}":"$B","{S}":"$S","{U}":"$U","{X}":"$X"};
            if(data.pretreat)
            {
                if(String==data.pretreat.constructor) data.pretreat=[data.pretreat];
                data.pretreat=data.pretreat.join(";").replace(/{[SUX]?}/g,function($0)
                {
                    return map[$0];
                });
            }
            if(data.grant)
                data.grant=_formatCnd(data.grant,map);
            if(data.check)
                data.check=_formatCnd(data.check,map);
        }
    }
    if(data){
        if(data.params){
            for(let key in data.params){
                if('file'==data.params[key].type) data.hasFile=1;
            }
        }
    }
    return {TPL:data,routeName:routeName}
}
187329
private function parseNetwork()
    {
        // 用户名密码处理
        $username = $this->request->getAttribute('username');
        if(null != $username)
        {
            $userPwd = $username . ':' . $this->request->getAttribute('password', '');
        }
        else
        {
            $userPwd = '';
        }
        curl_setopt_array($this->handler, array(
            // 连接超时
            CURLOPT_CONNECTTIMEOUT_MS       => $this->request->getAttribute('connectTimeout', 30000),
            // 总超时
            CURLOPT_TIMEOUT_MS              => $this->request->getAttribute('timeout', 0),
            // 下载限速
            CURLOPT_MAX_RECV_SPEED_LARGE    => $this->request->getAttribute('downloadSpeed'),
            // 上传限速
            CURLOPT_MAX_SEND_SPEED_LARGE    => $this->request->getAttribute('uploadSpeed'),
            // 连接中用到的用户名和密码
            CURLOPT_USERPWD                 => $userPwd,
        ));
    }
1271972
function entrustGlobalVariables()
    {
        // if don't have request instance, do not anything
        if ($this->requestInstance) {
            $swooleRequest = $this->requestInstance->getSwooleRequest();
            $_GET          = isset($swooleRequest->get) ? $swooleRequest->get : [];
            $_POST         = isset($swooleRequest->post) ? $swooleRequest->post : [];
            $_FILES        = isset($swooleRequest->files) ? $swooleRequest->files : [];
            $_SERVER       = isset($swooleRequest->server) ? array_change_key_case($swooleRequest->server, CASE_UPPER) : [];
            $_REQUEST      = array(); // 暂不支持
            $_COOKIE       = array(); // 暂不支持
            $_ENV          = array(); // 暂不支持
            $_SESSION      = array(); // 暂不支持
            $GLOBALS       = array(); // 暂不支持

            $header = $this->requestInstance->getHeaderLine('x-requested-with');
            if ($header && strtolower($header) == 'xmlhttprequest') {
                $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
            }
        }
    }
35706
public static function detectUri()
    {
        // 如果PATH_INFO读不到，那么就从其他途径读
        if ( ! $uri = Arr::get($_SERVER, 'PATH_INFO'))
        {
            // REQUEST_URI和PHP_SELF会包含当前脚本路径
            if (isset($_SERVER['REQUEST_URI']))
            {
                $uri = $_SERVER['REQUEST_URI'];
                if ($requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))
                {
                    $uri = $requestUri;
                }
                $uri = rawurldecode($uri);
            }
            elseif (isset($_SERVER['PHP_SELF']))
            {
                $uri = $_SERVER['PHP_SELF'];
            }
            elseif (isset($_SERVER['REDIRECT_URL']))
            {
                $uri = $_SERVER['REDIRECT_URL'];
            }
            else
            {
                throw new HelperException('Unable to detect the URI using PATH_INFO, REQUEST_URI, PHP_SELF or REDIRECT_URL');
            }

            $baseUrl = parse_url(Base::$baseUrl, PHP_URL_PATH);
            if (strpos($uri, $baseUrl) === 0)
            {
                $uri = (string) substr($uri, strlen($baseUrl));
            }
            if (Base::$indexFile && strpos($uri, Base::$indexFile) === 0)
            {
                $uri = (string) substr($uri, strlen(Base::$indexFile));
            }
        }

        return $uri;
    }
907665
function(val, index, rule){
    //存在url，并且url不是http方式
    var isHttpUrl = val.indexOf('//') > -1;
    var ret = false;
    if (!isHttpUrl){
      var uri = imageUrlReg.exec(val);
      if (uri){
        var imgurl = url.parse(uri[1], true);
        var params = imgurl.query;
        var id = params['id'] || 0;
        ret = imgurl.pathname.replace(/\\+/g, '/');
        //过滤图片
        if (!(PARAMS['nosprite'] in params)){
          //设置第一个图片为sprite图片位置
          if (!this.get('imgPath')){
            this.set('imgPath', path.dirname(ret));
          }

          var preParam = this.get('preParam');
          var _id = this.get('id');
          if (_id == id){
            this.initSpriteConf(params);
            //依次初始化图片配置
            preParam.forEach(this.initSpriteConf, this);
            preParam = [];
          } else if (_id < id){
            //如果id提前出现，既id为0的图片没有出现之前，id是1的已经出现了，把
            //当前参数存在数组preParam中
            var isNewImg = preParam.every(function(params){
              return params.id < id;
            });
            if (isNewImg) preParam.push(params);
          }
          this.set('preParam', preParam);
        } else {
          var cssImgs = this.get('cssImgs');
          cssImgs.push(ret);
          rule.value[index] = val.replace(imgurl.pathname, ret);
          ret = false;
        }
      }
    }

    return ret;
  }