has('product_id') ? $request->get('product_id') : '';
        $uid = $request->has('uid') ? $request->get('uid') : '';
        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->get('distribution_channel_id') : '';
        $p_channel_id = $request->has('p_channel_id') ? $request->get('p_channel_id') : 0;
        $pay_redirect_url = $request->has('pay_redirect_url') ? $request->get('pay_redirect_url') : '';
        $send_order_id = $request->has('send_order_id') ? $request->get('send_order_id') : 0;
        $activity_id = $request->has('activity_id') ? $request->get('activity_id') : 0;
        $ip = $request->has('ip') ? $request->get('ip') : '';
        $n = $request->has('n') ? $request->get('n') : 0;
        $crm = $request->has('crm') ? $request->get('crm') : 0;
        if ($send_order_id && strlen($send_order_id) > 50) {
            try {
                $send_order_id = decrypt($send_order_id);
            } catch (\Exception $e) {
                $send_order_id = 0;
            }
        }
        if ($send_order_id && strlen($send_order_id) > 50) {
            $send_order_id = 0;
        }
        //活动判断
        if ($activity_id) {
            $limit = $request->get('limit', 0);
            if ($limit && $limit == 1) {
                $order = OrderService::userIsParticipateActivity($uid, $activity_id);
                if ($order) {
                    $activity = ActivityService::getById($activity_id);
                    if ($activity) {
                        $url = env('PROTOCOL', 'https') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST', 'leyuee') . '.com' . $activity->activity_page;
                        return redirect()->to($url);
                    }
                    return '';
                }
            }
        }
        $suid = $request->get('suid', 0);
        if ($suid) {
            $user_info = UserService::getById($uid);
            $distribution_channel_id = $user_info->distribution_channel_id;
            $pay_redirect_url = 1;
        }
        if (empty($product_id) || empty($uid) || empty($distribution_channel_id) || empty($pay_redirect_url)) {
            return response()->error('WAP_PARAM_ERROR');
        }
        if ($suid && $suid == $uid) {
            return back();
        }
        $openid = $request->has('openid') ? $request->get('openid') : '';
        $bid = $request->has('bid') ? $request->get('bid') : 0;
        $hash_bid = $bid;
        $fromtype = $request->has('fromtype') ? $request->get('fromtype') : $request->get('from');
        if ($fromtype && strlen($fromtype) > 50) {
            try {
                $fromtype = decrypt($fromtype);
            } catch (\Exception $e) {
                $fromtype = 'main';
            }
        }
        if ($fromtype && strlen($fromtype) > 50) {
            $fromtype = 'main';
        }
        if (!$openid && !$p_channel_id && !$suid) {
            $transfer_channel_id = $this->transfer($distribution_channel_id);
            if ($transfer_channel_id) {
                $p_channel_id = $distribution_channel_id;
                $distribution_channel_id = $transfer_channel_id;
            }
        }
        //根据分校id获取支付配置id
        Log::info($request->all());
        $channel = ChannelService::getById($distribution_channel_id);
        if (!$channel || !$channel->pay_merchant_id) {
            return response()->error('WAP_PARAM_ERROR');
        }
        //获取支付类型
        $pay_merchant = DB::table('pay_merchants')->select('id', 'appid', 'source', 'config_info')->where('id', $channel->pay_merchant_id)->where('is_enabled', 1)->first();
        if (!$pay_merchant || !$pay_merchant->appid || !$pay_merchant->source) return response()->error('WAP_PARAM_ERROR');
        if ($pay_merchant->source == 'PALMPAYV2') {
            return redirect()->to($this->paympay($request, $pay_merchant));
        }
        //重定向 获取用户信息的次数
        $n++;
        if ($n >= 5) {
            //重定向次数过多,则授权公众号出问题
            $this->payAlert($channel->pay_merchant_id, '', '', $n);
            $back_url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com' . '/pay';
            return redirect()->to($back_url);
        }
        if (empty($openid)) {
            $trade_no = date("YmdHis") . str_shuffle(hexdec(uniqid()));
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } else {
                $ip = get_client_ip();
            }
            $params = compact('uid', 'product_id', 'distribution_channel_id', 'send_order_id', 'bid', 'trade_no', 'pay_redirect_url', 'fromtype', 'activity_id', 'n', 'suid', 'ip', 'p_channel_id','crm');
            $redirect_url = env('CREATE_PAY_URL') . '?' . http_build_query($params);
            //$redirect_url  = env('CREATE_PAY_URL').'?uid='.$uid.'&product_id='.$product_id.'&distribution_channel_id='
            // .$distribution_channel_id.'&send_order_id='.$send_order_id.'&bid='.$bid.'&pay_redirect_url='.urlencode($pay_redirect_url)
            $auth_url = env('AUTH_URL') . '?gzh_app_id=' . $pay_merchant->appid . '&redirect_url=' . urlencode($redirect_url);
            Log::info('redirect_auth_url:' . $auth_url);
            header("Location:" . $auth_url);
            exit();
        }
        $trade_no = $request->input('trade_no');
        $order_info = OrderService::getByTradeNo($trade_no);
        if ($order_info) return response()->error('WAP_SYS_ERROR');
        $cid = $request->has('cid') ? $request->get('cid') : '';
        $product_info = ProductService::getProductSingle($product_id, false);
        //新用户只能冲一次
        //Log::info('新用户只能冲一次:' .$product_info->type);
        if ($this->isNewUserSecondCharge($product_info->type, $product_id, $uid)) {
            $url = env('PROTOCOL', 'https') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST', 'leyuee') . '.com/pay';
            return redirect()->to($url);
        }
        $price = $product_info->price * 100;
        if ($uid < 32) {
            $price = 1;
        }
        try {
            $send_order_id = (int)Redis::hget('book_read:' . $uid, 'send_order_id');
        } catch (\Exception $e) {
        }
        $this->updateUserSendOrderId($uid, $send_order_id);
        if (in_array($uid, explode(',', env('TEST_UID')))) {
            $price = 1;
        }
        if ($bid) {
            try {
                $bid = Hashids::decode($bid)[0];
            } catch (\Exception $e) {
                $bid = 0;
            }
        }
        try {
            $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:' . $distribution_channel_id;
            Redis::hset($key, $uid, time());
            $date = date('Y-m-d');
            Redis::hincrby('order_stat:' . $distribution_channel_id, 'order_num_' . $date, 1);
            if ($send_order_id) {
                Redis::hincrby('order_promotion_stat:' . $send_order_id, 'order_num_' . $date, 1);
                Redis::hincrby('order_promotion_stat:' . $send_order_id, 'total', 1);
            }
        } catch (\Exception  $e) {
        }
        $data = [];
        $data['price'] = $price;
        $data['create_ip'] = $ip;
        $data['openid'] = $openid;//
        $data['body'] = 'novel read';
        $official_name = $this->getSubscribeOfficialName($uid, $distribution_channel_id);
        if ($official_name) {
            $data['body'] = '搜索公众号' . $official_name . ',请继续阅读';
        }
        $data['detail'] = 'novel read';
        $data['trade_no'] = $trade_no;
        $data['remark'] = json_encode(
            [
                'uid' => $uid,
                'dcd' => $distribution_channel_id,
                'bid' => $bid,
                'cp' => $ip,
                'pms' => $pay_merchant->source,
                'pmi' => $channel->pay_merchant_id,
                'pd' => $product_id,
                'soi' => $send_order_id,
            ]
        );
        if ($product_info->type == 'YEAR_ORDER') {
            $order_type = 'YEAR';
        } elseif ($product_info->type == 'BOOK_ORDER') {
            $order_type = 'BOOK';
        } elseif ($product_info->type == 'TICKET_RECHARGE') {
            $order_type = 'RECHARGE';
        } elseif ($product_info->type == 'NEW_USER') {
            $order_type = 'RECHARGE';
        } else {
            $order_type = 'UNKNOWN';
        }
        /*
        $this->createOrderTotal([
            'distribution_channel_id'=>$distribution_channel_id,
            'uid'=>$uid,
            'product_id'=>$product_id,
            'price'=>$price/100,
            'pay_type'=>1,
            'trade_no'=>$data['trade_no'],
            'pay_merchant_source'=>$pay_merchant->source,
            'pay_merchant_id'=>$channel->pay_merchant_id,
            'create_ip'=>$request->getClientIp(),
            'send_order_id'=>$send_order_id,
            'order_type'=>$order_type,
            'from_bid'=>$bid
        ]);*/
        $send_order_name = '';
        if ($send_order_id) {
            $send_order_info = SendOrderService::getById($send_order_id);
            if ($send_order_info && isset($send_order_info->name) && !empty($send_order_info->name)) {
                $send_order_name = $send_order_info->name;
            }
            if(redisEnv('MIWAN_TRANSFER_TO_CHANNEL_ID', 0) == $distribution_channel_id){
                $send_order_id = -$send_order_id;
            }
        }
        if ($suid) {
            $user_info = UserService::getById($uid);
            $distribution_channel_id = $user_info->distribution_channel_id;
        }
        $from_bid = ReadRecordService::getSimpleFirstReadRecord($uid);
        $inner_send_order_id = ReadRecordService::getInnerSendOrderId($uid);
        $init_order = [
            'distribution_channel_id' => $distribution_channel_id,
            'uid' => $uid,
            'product_id' => $product_id,
            'price' => $price / 100,
            'pay_type' => 1,
            'trade_no' => $data['trade_no'],
            'pay_merchant_source' => $pay_merchant->source,
            'pay_merchant_id' => $channel->pay_merchant_id,
            'create_ip' => $ip,
            'send_order_id' => $send_order_id,
            'send_order_name' => $send_order_name,
            'order_type' => $order_type,
            'from_bid' => $from_bid,
            'from_type' => $fromtype,
            'activity_id' => $activity_id,
            'inner_send_order_id' => $inner_send_order_id
        ];
        $result = $this->createUnPayOrder($init_order);
        //订单创建成功后增加统计
        if ($result) {
            $this->orderCreated($init_order);
            $this->recordOtherParam($result->id, $uid);
            if($p_channel_id){
                //miwa 转换
                OrderParamService::createByParam([
                    'order_id'=>$result->id,'gxhp'=>'mw_transfer','appid'=>'','bid'=>$bid,'data_hour_key'=>'','times'=>'','distribution_channel_id'=>$p_channel_id
                ]);
            }
            if($crm){
                OrderParamService::createByParam([
                    'order_id'=>$result->id,'gxhp'=>'crm','appid'=>'','bid'=>$bid,'data_hour_key'=>$crm,'times'=>'','distribution_channel_id'=>$distribution_channel_id
                ]);
            }
        }
        if ($request->get('suid')) {
            $this->createSubstituteOrder($result->id, $uid, $request->get('suid'));
        }
        Log::info($data);
        $config = [];
        if ($pay_merchant->config_info) {
            $config = json_decode($pay_merchant->config_info, true);
        }
        $wechatPay = WechatPay::instance($pay_merchant->source, $config);
        if (!$wechatPay) return response()->error('WAP_PARAM_ERROR');
        $pay_info = $wechatPay->send($data);
        if (!$pay_info) {
            $pay_info = $wechatPay->send($data);
        }
        if (!isset($pay_info['appId']) || !isset($pay_info['package'])) {
            //支付异常
            myLog('order')->info('pay error start---------------------------------');
            myLog('order')->info($pay_info);
            myLog('order')->info($request->all());
            myLog('order')->info('order info  is');
            myLog('order')->info($init_order);
            myLog('order')->info('pay error end-----------------------------------');
            $this->payAlert($channel->pay_merchant_id, $trade_no, $pay_info);
        }
        $pay_info['pay_redirect_url'] = urldecode($pay_redirect_url);
        if ($request->has('cid')) {
            $pay_info['pay_redirect_url'] = $pay_info['pay_redirect_url'] . '&cid=' . $request->input('cid');
        }
//        if ($hash_bid) {
//            $pay_info['pay_redirect_url'] = $pay_info['pay_redirect_url'] . '&bid=' . $hash_bid;
//        }
        if ($suid) {
            $prize_fee = (int)(($product_info->price * 100) * 0.1);
            $help_pay_page_channel_id = env('HELP_PAY_PAGE_CHANNEL_ID', 123);
            $help_pay_page_channel_id = $distribution_channel_id;
            $url_format = '%s://site%s.%s.com/helppay?back=%s&su=%s';
            $pay_info['pay_redirect_url'] = $pay_redirect_url = sprintf(
                $url_format,
                env('PROTOCOL'),
                encodeDistributionChannelId($help_pay_page_channel_id),
                env('CUSTOM_HOST'),
                $prize_fee,
                $uid
            );
        }
        $pay_url_info = parse_url($pay_redirect_url);
        $pay_info['pay_wait_url'] = $pay_url_info['scheme'] . '://' . $pay_url_info['host'] . '/pay/wait?order=' . $data['trade_no'] . '&redirect=' . urlencode($pay_info['pay_redirect_url']);
        //$h5_scheme = env('H5_SCHEME','https');
        //$jsSdkSign = $this->jsSdkSign($pay_info,str_replace('http',$h5_scheme,url()->current()));
        Log::info('$pay_info is');
        $jsSdkSign = 0;
        Log::info($pay_info);
        Log::info('jsSdkSign---- :' . $jsSdkSign);
        $pay_order = $trade_no;
        // 注册动作-》创建订单
        $action_type = 'CreateOrder';
        $param = [
            'openid' => isset($openid) ? $openid : '0',
            'uid' => isset($uid) ? $uid : '0',
            'order_sn' => isset($trade_no) ? $trade_no : '0',
            'amount' => isset($price) ? $price : '0',
        ];
        UserService::PushUserActionToQueue($action_type, $distribution_channel_id, $param);
        return view('pay.order.index', compact('pay_info', 'referer', 'jsSdkSign', 'pay_order'));
    }
    private function paympay(Request $request, $pay_merchant)
    {
        $product_id = $request->get('product_id');
        $uid = $request->get('uid');
        $distribution_channel_id = $request->get('distribution_channel_id');
        $pay_redirect_url = $request->get('pay_redirect_url');
        $send_order_id = $request->get('send_order_id', 0);
        $activity_id = $request->get('activity_id', 0);
        $suid = $request->get('suid', 0);
        $bid = $request->has('bid') ? $request->get('bid') : 0;
        $crm = $request->has('crm') ? $request->get('crm') : '';
        $hash_bid = $bid;
        $fromtype = $request->has('fromtype') ? $request->get('fromtype') : $request->get('from', 'main');
        //根据分校id获取支付配置id
        Log::info($request->all());
        $trade_no = $trade_no = date("YmdHis") . str_shuffle(hexdec(uniqid()));
        $order_info = OrderService::getByTradeNo($trade_no);
        if ($order_info) return response()->error('WAP_SYS_ERROR');
        $cid = $request->has('cid') ? $request->get('cid') : '';
        $product_info = ProductService::getProductSingle($product_id, false);
        //新用户只能冲一次
        //Log::info('新用户只能冲一次:' .$product_info->type);
        if ($this->isNewUserSecondCharge($product_info->type, $product_id, $uid)) {
            $url = env('PROTOCOL', 'https') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST', 'leyuee') . '.com/pay';
            return redirect()->to($url);
        }
        $price = $product_info->price * 100;
        if ($uid < 32) {
            $price = 1;
        }
        if (!$send_order_id) {
            try {
                $send_order_id = (int)Redis::hget('book_read:' . $uid, 'send_order_id');
            } catch (\Exception $e) {
            }
        }
        $this->updateUserSendOrderId($uid, $send_order_id);
        if (in_array($uid, explode(',', env('TEST_UID')))) {
            $price = 1;
        }
        try {
            $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:' . $distribution_channel_id;
            Redis::hset($key, $uid, time());
            $date = date('Y-m-d');
            Redis::hincrby('order_stat:' . $distribution_channel_id, 'order_num_' . $date, 1);
            if ($send_order_id) {
                Redis::hincrby('order_promotion_stat:' . $send_order_id, 'order_num_' . $date, 1);
                Redis::hincrby('order_promotion_stat:' . $send_order_id, 'total', 1);
            }
        } catch (\Exception  $e) {
        }
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = get_client_ip();
        }
        $data = [];
        $data['price'] = $price;
        $data['create_ip'] = $ip;
        $data['body'] = 'novel read';
        $official_name = $this->getSubscribeOfficialName($uid, $distribution_channel_id);
        if ($official_name) {
            $data['body'] = '搜索公众号' . $official_name . ',请继续阅读';
        }
        $data['detail'] = 'novel read';
        $data['trade_no'] = $trade_no;
        if ($product_info->type == 'YEAR_ORDER') {
            $order_type = 'YEAR';
        } elseif ($product_info->type == 'BOOK_ORDER') {
            $order_type = 'BOOK';
        } elseif ($product_info->type == 'TICKET_RECHARGE') {
            $order_type = 'RECHARGE';
        } elseif ($product_info->type == 'NEW_USER') {
            $order_type = 'RECHARGE';
        } else {
            $order_type = 'UNKNOWN';
        }
        $send_order_name = '';
        if ($send_order_id) {
            $send_order_info = SendOrderService::getById($send_order_id);
            if ($send_order_info && isset($send_order_info->name) && !empty($send_order_info->name)) {
                $send_order_name = $send_order_info->name;
            }
        }
        if ($suid) {
            $user_info = UserService::getById($uid);
            $distribution_channel_id = $user_info->distribution_channel_id;
        }
        $from_bid = ReadRecordService::getSimpleFirstReadRecord($uid);
        $inner_send_order_id = ReadRecordService::getInnerSendOrderId($uid);
        $init_order = [
            'distribution_channel_id' => $distribution_channel_id,
            'uid' => $uid,
            'product_id' => $product_id,
            'price' => $price / 100,
            'pay_type' => 1,
            'trade_no' => $data['trade_no'],
            'pay_merchant_source' => 'PALMPAY',
            'pay_merchant_id' => $pay_merchant->id,
            'create_ip' => $ip,
            'send_order_id' => $send_order_id,
            'send_order_name' => $send_order_name,
            'order_type' => $order_type,
            'from_bid' => $from_bid,
            'from_type' => $fromtype,
            'activity_id' => $activity_id,
            'inner_send_order_id' => $inner_send_order_id
        ];
        $result = $this->createUnPayOrder($init_order);
        //订单创建成功后增加统计
        if ($result) {
            $this->orderCreated($init_order);
            $this->recordOtherParam($result->id, $uid);
            if($crm){
                OrderParamService::createByParam([
                    'order_id'=>$result->id,'gxhp'=>'crm','appid'=>'','bid'=>$bid,'data_hour_key'=>$crm,'times'=>'','distribution_channel_id'=>$distribution_channel_id
                ]);
            }
        }
        if ($suid) {
            $this->createSubstituteOrder($result->id, $uid, $suid);
        }
        if ($suid) {
            $prize_fee = (int)(($product_info->price * 100) * 0.1);
            //$help_pay_page_channel_id = env('HELP_PAY_PAGE_CHANNEL_ID', 123);
            $help_pay_page_channel_id = $distribution_channel_id;
            $url_format = '%s://site%s.%s.com/helppay?back=%s&su=%s';
            $pay_redirect_url = sprintf(
                $url_format,
                env('PROTOCOL'),
                encodeDistributionChannelId($help_pay_page_channel_id),
                env('CUSTOM_HOST'),
                $prize_fee,
                $uid
            );
        }
        $de_pay_redirect_url = urldecode($pay_redirect_url);
        /*if ($request->has('cid')) {
            $de_pay_redirect_url = $de_pay_redirect_url . '&cid=' . $request->get('cid');
        }*/
        $pay_url_info = parse_url($de_pay_redirect_url);
        $data['pay_wait_url'] = $pay_url_info['scheme'] . '://' . $pay_url_info['host'] . '/pay/waitv2?order=' . $data['trade_no'] . '&redirect=' . urlencode($de_pay_redirect_url);
        Log::info($data);
        $config = [];
        if ($pay_merchant->config_info) {
            $config = json_decode($pay_merchant->config_info, true);
        }
        $wechatPay = WechatPay::instance($pay_merchant->source, $config);
        \Log::info('$wechatPay is');
        //\Log::info($wechatPay);
        if (!$wechatPay) return response()->error('WAP_PARAM_ERROR');
        \Log::info('$wechatPay ok-------------------');
        $pay_info = $wechatPay->send($data);
        \Log::info('send ok-------------------');
        // 注册动作-》创建订单
        $action_type = 'CreateOrder';
        $param = [
            'openid' => isset($openid) ? $openid : '0',
            'uid' => isset($uid) ? $uid : '0',
            'order_sn' => isset($trade_no) ? $trade_no : '0',
            'amount' => isset($price) ? $price : '0',
        ];
        \Log::info('FUCK_PALMPAYV2');
        UserService::PushUserActionToQueue($action_type, $distribution_channel_id, $param);
        return $pay_info;
    }
    public function waitPageV2(Request $request)
    {
        $order = $request->get('order');
        $order = (string)$order;
        $url = urldecode($request->get('redirect'));
        if (substr_count($url, '?') > 1) {
            $url = str_replace_last('?', '&', $url);
        }
        $url_info = parse_url($url);
        if (isset($url_info['query']) && !empty($url_info['query'])) {
            parse_str($url_info['query'], $path);
            if (isset($path['success']) && $path['success'] == 0) {
                if (isset($url_info['path']) && str_contains($url_info['path'], 'reader') && isset($path['cid']) && !empty($path['cid'])) {
                    $chapter_info = ChapterService::getChapterNameByIdNoCheck($path['cid']);
                    $path['cid'] = $chapter_info->prev_cid;
                    $url = sprintf('%s://%s/reader?%s', $url_info['scheme'], $url_info['host'], http_build_query($path));
                }
                return redirect($url);
            }
        }
        if (isset($url_info['path']) && str_contains($url_info['path'], 'pay')) {
            $url = sprintf('%s://%s/recent', $url_info['scheme'], $url_info['host']);
            return redirect($url);
        }
        return view('pay.order.wait', compact('order', 'url'));
    }
    private function isNewUserSecondCharge($charge_type, $product_id, $uid)
    {
        //Log::info('新用户只能冲一次:' .$charge_type);
        if ($charge_type == 'NEW_USER') {
            $result = OrderService::getUserOrderByProductId($uid, $product_id);
            //Log::info('isNewUserSecondCharge-------------------------');
            //Log::info($result);
            if ($result) {
                return true;
            }
        }
        return false;
    }
    //订单创建后统计
    private function orderCreated($init_order)
    {
        try {
            if (isset($init_order['pay_merchant_id'])) {
                $key = 'pay_merchant:' . $init_order['pay_merchant_id'];
                Redis::hincrby($key, 'unpaid_num', 1);
                Redis::hset($key, 'last_create_time', time());
            }
        } catch (\Exception $e) {
        }
    }
    //订单回调后统计
    private function orderPaid($init_order)
    {
        try {
            if (isset($init_order['pay_merchant_id'])) {
                $key = 'pay_merchant:' . $init_order['pay_merchant_id'];
                Redis::hset($key, 'unpaid_num', 0);
            }
        } catch (\Exception $e) {
        }
    }
    public function reportError(Request $request)
    {
        $data = $request->post('data');
        DB::table('pay_page_error')->insert([
            'msg' => $data,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        return response()->success();
    }
    private function jsSdkSign($pay_info, $url)
    {
        if (!isset($pay_info['appId']) || !isset($pay_info['package'])) {
            return 0;
        }
        $appid = $pay_info['appId'];
        $jsapi_ticket = Redis::hget($appid, 'jsapi_ticket');
        //如果能获取到jsapi_ticket 则直接签名
        if ($jsapi_ticket) {
            $sign_arr = [
                'noncestr' => $pay_info['nonceStr'],
                'jsapi_ticket' => $jsapi_ticket,
                'timestamp' => $pay_info['timeStamp'],
                'url' => $url
            ];
            return sha1($this->arr_to_url($sign_arr));
        }
        //获取不到jsapi_ticket
        $app_secret_info = DB::table('official_setting')->select('secret')->first();
        if ($app_secret_info && !empty($app_secret_info->secret)) {
            $client = new Client(['timeout' => 5]);
            try {
                //获取access_token
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $app_secret_info->secret;
                $res = $client->request('get', $url)->getBody()->getContents();
                if (!$res) {
                    return 0;
                }
                $res = json_decode($res, 1);
                if (!isset($res['access_token']) || empty($res['access_token'])) {
                    return 0;
                }
                Redis::hset($appid, 'access_token', $res['access_token']);
                //获取jsapi_ticket
                $res = null;
                $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $res['access_token'] . '&type=jsapi';
                $res = $client->request('get', $url)->getBody()->getContents();
                if (!$res) {
                    return 0;
                }
                $res = json_decode($res, 1);
                if (!isset($res['ticket']) || empty($res['ticket'])) {
                    return 0;
                }
                Redis::hset($appid, 'jsapi_ticket', $res['ticket']);
                Redis::EXPIRE($appid, 7000);
                $sign_arr = [
                    'noncestr' => $pay_info['nonceStr'],
                    'jsapi_ticket' => $res['ticket'],
                    'timestamp' => $pay_info['timeStamp'],
                    'url' => $url
                ];
                return sha1($this->arr_to_url($sign_arr));
            } catch (\Exception $e) {
                return 0;
            }
        }
        return 0;
    }
    public function waitPage(Request $request)
    {
        $order = $request->input('order');
        //$order = "201712081711401585932843356442";
        $order = (string)$order;
        $url = urldecode($request->input('redirect'));
        return view('pay.order.wait', compact('order', 'url'));
        //return view('pay.order.wait');
    }
    /**
     * 官方微信回调
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    function wcback_official(Request $request)
    {
        libxml_disable_entity_loader(true);
        $xml = XML::parse(strval($request->getContent()));
        Log::info('xml is');
        Log::info($xml);
        if (!$xml || !is_array($xml)) return 'fail';
        $remarks = json_decode($xml['attach'], true);
        $pay_merchant_id = $remarks['pmi'];
        $pay_merchant = DB::table('pay_merchants')->select('appid', 'source', 'config_info')->where('id', $pay_merchant_id)->where('is_enabled', 1)->first();
        $application = WechatPay::instance('OFFICIALPAY', json_decode($pay_merchant->config_info, true));
        //$app = new Application($options);
        $app = $application->app;
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            if (!$successful) return 'fail';
            $trade_no = $notify->out_trade_no;
            $order = OrderService::getByTradeNo($trade_no);
            if (isset($order->status) && $order->status == 'PAID') {
                Log::info('has_pay:' . $trade_no);
                return true;
            }
            DB::beginTransaction();
            try {
                $transaction_id = $notify->transaction_id;
                $remarks = json_decode($notify->attach, true);
                $uid = $remarks['uid'];
                $distribution_channel_id = $remarks['dcd'];
                $product_id = $remarks['pd'];
                $product = ProductService::getProductSingle($product_id);
                $pay_merchant_source = $remarks['pms'];
                $pay_merchant_id = $remarks['pmi'];
                $send_order_id = $remarks['soi'];
                $create_ip = $remarks['cp'];
                $price = $product->price;
                $bid = $remarks['bid'];
                //$this->updateOrderTotal($trade_no,$transaction_id);
                $prize_fee = (int)(($product->price * 100) * 0.1);
                $this->substituteOrderPrice($order->id, $prize_fee);
                $this->smartPushTestBookPaidUv($order->from_bid, $order->uid, $order->price);
                //获取用户充值次数
                $order->pay_type = $this->getChargeTimes($order->uid);
                // 更新其他定制Order表
                if ($product->type == 'YEAR_ORDER') {
                    Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
                    $order_type = 'YEAR';
                    $this->yearOrder($uid, $distribution_channel_id, $price, $send_order_id);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                    //$price = $price/100;
                    /*
                    $this->createOrder(
                        compact(
                            'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
                            'pay_merchant_id','create_ip','bid','transaction_id'
                        )
                    );*/
                } elseif ($product->type == 'BOOK_ORDER') {
                    Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
                    $order_type = 'BOOK';
                    $this->bookOrder($product_id, $uid, $send_order_id, $price, $distribution_channel_id);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                    //$price = $price/100;
                    /*
                    $this->createOrder(
                        compact(
                            'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
                            'pay_merchant_id','create_ip','bid','transaction_id'
                        )
                    );*/
                } elseif ($product->type == 'TICKET_RECHARGE') {
                    Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
                    $order_type = 'RECHARGE';
                    $this->userCharge($product, $uid);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                    //$price = $price/100;
                    /*
                    $this->createOrder(
                        compact(
                            'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
                            'pay_merchant_id','create_ip','bid','transaction_id'
                        ));*/
                } elseif ($product->type == 'FOREVER') {
                    Log::info('FOREVER------------------------FOREVER');
                    $order_type = 'FOREVER';
                    $this->foreverFreeOrder($uid, $distribution_channel_id, $price, $send_order_id);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                } else {
                    DB::rollback();
                    return 'Order not exist.';
                }
                $this->successPayPushMsg($uid, $product, $order->id);
                $this->orderStatistical($order);
                $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:' . $distribution_channel_id;
                Redis::hdel($key, $uid);
                DB::commit();
                $this->huaweiActivity($order->activity_id,$uid,$product_id);
                // 注册动作-》回调订单
                $action_type = 'CallBackOrder';
                $param = [
                    'order_sn' => isset($trade_no) ? $trade_no : '0',
                    'openid' => isset($uid) ? $uid : '0',// 没有openid,用uid写log
                ];
                UserService::PushUserActionToQueue($action_type, $distribution_channel_id, $param);
                //用户属性
                $this->userProperty($uid);
                return true;
            } catch (\Exception $e) {
                DB::rollback();
                return 'fail';
            }
        });
        return $response;
    }
    /**
     * 通联支付回调
     * @param Request $request
     */
    function wcback_allinpay(Request $request)
    {
        Log::info('wcback_allinpay_request');
        try {
            $data = $request->all();
            Log::info($request->all());
            if (!$data['trxreserved']) return 'fail';
            $pay_merchant_id = json_decode($data['trxreserved'], true)['pmi'];
            $pay_merchant = DB::table('pay_merchants')->select('appid', 'source', 'config_info')->where('id', $pay_merchant_id)->where('is_enabled', 1)->first();
            unset($data['_url']);
            if (!$pay_merchant->config_info) return 'fail';
            $wechatPay = WechatPay::instance('ALLINPAY', json_decode($pay_merchant->config_info, true));
            if ($wechatPay->NotifyValidSign($data, $wechatPay->appkey)) {
                Log::info('allinpay_notify_sign_success');
                /**
                 * 只有0000表示交易成功或下单成功,其他为失败
                 * 0000:交易成功
                 * 3045,3088:交易超时
                 * 3008:余额不足
                 * 3999:交易失败
                 * 2008:交易处理中
                 * 3050:交易已撤销
                 */
                if ($data['trxstatus'] == '0000') {
                    // 修改表比较多,开启事务
                    DB::beginTransaction();
                    $trade_no = $data['cusorderid'];
                    $transaction_id = $data['chnltrxid'];
                    //$openid = $data['acct'];
                    $remarks = $data['trxreserved'];
//     				$remarks = '{"openid":"oEteU1VNvYozhXuu8TXhByPBtSl4","distribution_channel_id":2,"product_id":1,"uid":1,"price":"1","trade_no":"201711301937151585490779316114","create_ip":"::1","servicer":"AllinPay"}';
                    $remarks = json_decode($remarks, true);
                    Log::info('$remarks');
                    Log::info($remarks);
                    // 更新Order
                    $order = OrderService::getByTradeNo($trade_no);
                    // 防止重复推送
                    if (isset($order->status) && $order->status == 'PAID') {
                        Log::info('has_pay:' . $trade_no);
                        echo 'success';
                        exit();
                    }
                    $uid = $remarks['uid'];
                    $distribution_channel_id = $remarks['dcd'];
                    $product_id = $remarks['pd'];
                    $product = ProductService::getProductSingle($product_id);
                    $pay_merchant_source = $remarks['pms'];
                    $pay_merchant_id = $remarks['pmi'];
                    $send_order_id = $remarks['soi'];
                    $create_ip = $remarks['cp'];
                    $price = $product->price;
                    $bid = $remarks['bid'];
                    Log::info('save_order_end');
                    //$this->updateOrderTotal($trade_no,$transaction_id);
                    Log::info($product);
                    Log::info('product_type:' . $product->type);
                    $prize_fee = (int)(($product->price * 100) * 0.1);
                    $this->substituteOrderPrice($order->id, $prize_fee);
                    $this->smartPushTestBookPaidUv($order->from_bid, $order->uid, $order->price);
                    //获取用户充值次数
                    $order->pay_type = $this->getChargeTimes($order->uid);
                    // 更新其他定制Order表
                    if ($product->type == 'YEAR_ORDER') {
                        Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
                        $order_type = 'YEAR';
                        $this->yearOrder($uid, $distribution_channel_id, $price, $send_order_id);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                        //$price = $price/100;
                        /*
                        $this->createOrder(
                            compact(
                                'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
                                'pay_merchant_id','create_ip','bid','transaction_id'
                            )
                        );*/
                    } elseif ($product->type == 'BOOK_ORDER') {
                        Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
                        $order_type = 'BOOK';
                        $this->bookOrder($product_id, $uid, $send_order_id, $price, $distribution_channel_id);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                        //$price = $price/100;
                        /*
                        $this->createOrder(
                            compact(
                                'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
                                'pay_merchant_id','create_ip','bid','transaction_id'
                            )
                        );*/
                    } elseif ($product->type == 'TICKET_RECHARGE' || $product->type == 'NEW_USER') {
                        Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
                        $order_type = 'RECHARGE';
                        $this->userCharge($product, $uid);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                        //$price = $price/100;
                        /*
                        $this->createOrder(
                            compact(
                                'uid','distribution_channel_id','product_id','price','trade_no','send_order_id','order_type','pay_merchant_source',
                                'pay_merchant_id','create_ip','bid','transaction_id'
                            ));*/
                    } elseif ($product->type == 'FOREVER') {
                        Log::info('FOREVER------------------------FOREVER');
                        $order_type = 'FOREVER';
                        $this->foreverFreeOrder($uid, $distribution_channel_id, $price, $send_order_id);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                    }
                    $this->successPayPushMsg($uid, $product, $order->id);
                    $this->orderStatistical($order);
                    DB::commit();
                    $this->userProperty($uid);
                    $this->huaweiActivity($order->activity_id,$uid,$product_id);
                    //redis 删除未支付的uid
                    try {
                        $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:' . $distribution_channel_id;
                        Redis::hdel($key, $uid);
                        //Redis::srem($key,$uid);
                    } catch (\Exception $e) {
                        Log::info('redis remote error-----------------------');
                        Log::info($e);
                    }
                }
            } else {
                Log::info('allinpay_notify_sign_fail');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('receive_allinpay_ept:' . $e->getMessage());
            Log::info('pay_callback_end fail');
            echo 'fail';
            return;
        }
        Log::info('pay_callback_end');
        echo "success";
    }
    public function wcback_lianlianpay(Request $request)
    {
        $data = $request->getContent();
        Log::info('wcback_lianlianpay call back enter');
        Log::info($request->getContent());
        $data = json_decode($data, true);
        if ($data['result_pay'] == 'SUCCESS') {
            $trade_no = $data['no_order'];
            $order = OrderService::getByTradeNo($trade_no);
            if (!$order) return response()->json(['ret_code' => '-1']);
            $pay_merchant_id = $order->pay_merchant_id;
            $pay_merchant = DB::table('pay_merchants')->select('appid', 'source', 'config_info')->where('id', $pay_merchant_id)->where('is_enabled', 1)->first();
            unset($data['_url']);
            if (!$pay_merchant->config_info) response()->json(['ret_code' => '-1']);
            $wechatPay = WechatPay::instance('LIANLIANPAY', json_decode($pay_merchant->config_info, true));
            $uid = $order->uid;
            $distribution_channel_id = $order->distribution_channel_id;
            $price = $order->price;
            $send_order_id = $order->send_order_id;
            $product_id = $order->product_id;
            if (!$wechatPay->rsaCheck($data)) {
                Log::info('sign check error');
                //return response()->json(['ret_code'=>'-1']);
            }
            // 防止重复推送
            if (isset($order->status) && $order->status == 'PAID') {
                Log::info('has_pay:' . $trade_no);
                return response()->json(['ret_code' => '0000', 'ret_msg' => '交易成功']);
            }
            DB::beginTransaction();
            try {
                $product = ProductService::getProductSingle($order->product_id);
                $transaction_id = $data['oid_paybill'];
                $prize_fee = (int)(($product->price * 100));
                $this->substituteOrderPrice($order->id, $prize_fee);
                $this->smartPushTestBookPaidUv($order->from_bid, $order->uid, $order->price);
                //获取用户充值次数
                $order->pay_type = $this->getChargeTimes($order->uid);
                // 更新其他定制Order表
                if ($product->type == 'YEAR_ORDER') {
                    Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
                    $order_type = 'YEAR';
                    $this->yearOrder($uid, $distribution_channel_id, $price, $send_order_id);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                } elseif ($product->type == 'BOOK_ORDER') {
                    Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
                    $order_type = 'BOOK';
                    $this->bookOrder($product_id, $uid, $send_order_id, $price, $distribution_channel_id);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                } elseif ($product->type == 'TICKET_RECHARGE' || $product->type == 'NEW_USER') {
                    Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
                    $order_type = 'RECHARGE';
                    $this->userCharge($product, $uid);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                } elseif ($product->type == 'FOREVER') {
                    Log::info('FOREVER------------------------FOREVER');
                    $order_type = 'FOREVER';
                    $this->foreverFreeOrder($uid, $distribution_channel_id, $price, $send_order_id);
                    $order->order_type = $order_type;
                    $order->status = 'PAID';
                    $order->pay_end_at = date('Y-m-d H:i:s');
                    $order->transaction_id = $transaction_id;
                    $order->save();
                }
                $this->successPayPushMsg($uid, $product, $order->id);
                $this->orderStatistical($order);
                DB::commit();
                $this->userProperty($uid);
                $this->huaweiActivity($order->activity_id,$uid,$product_id);
                //redis 删除未支付的uid
                $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id' . $distribution_channel_id;
                Redis::hdel($key, $uid);
                return response()->json(['ret_code' => '0000', 'ret_msg' => '交易成功']);
            } catch (\Exception $e) {
                DB::rollBack();
                Log::info('lianlian:' . $e->getMessage());
                echo 'fail';
                return;
            }
        }
        echo 'success';
    }
    /**
     * 微众支付回调
     * @param Request $request
     */
    function wcback_palmpay(Request $request)
    {
        Log::info('wcback_palmpay_request');
        try {
            $data = $request->except('_url');
            Log::info($request->all());
            //订单
            $trade_no = $data['outTradeNo'];
            $order = OrderService::getByTradeNo($trade_no);
            if (!$order) die('failed');
            // 防止重复推送
            if (isset($order->status) && $order->status == 'PAID') {
                if($data['chorderid'] != $order->transaction_id){
                    Log::info('palmpay order repeat');
                    $this->palmpaySpecial($data['chorderid'],$trade_no);
                }
                Log::info('has_pay:' . $trade_no);
                echo 'success';
                exit();
            }
            $pay_merchant = DB::table('pay_merchants')->select('appid', 'source', 'config_info')->where('id', $order->pay_merchant_id)->where('is_enabled', 1)->first();
            //校验签名
            $sign = _sign($data, json_decode($pay_merchant->config_info, 1)['appKey']);
            if ($sign != $data['sign']) die('failed');
            $transaction_id = $data['chorderid'];
            if ($data['status'] == 'success') {
                Log::info('wcback_palmpay_notify_sign_success');
                if ($data['status'] == 'success') {
                    // 修改表比较多,开启事务
                    DB::beginTransaction();
                    // 更新Order
                    $order = OrderService::getByTradeNo($trade_no);
                    $uid = $order->uid;
                    $distribution_channel_id = $order->distribution_channel_id;
                    $product_id = $order->product_id;
                    $product = ProductService::getProductSingle($product_id);
                    $send_order_id = $order->send_order_id;
                    $price = $product->price;
                    Log::info('save_order_end');
                    Log::info($product);
                    Log::info('product_type:' . $product->type);
                    $prize_fee = (int)(($product->price * 100) * 0.1);
                    $this->substituteOrderPrice($order->id, $prize_fee);
                    $this->smartPushTestBookPaidUv($order->from_bid, $order->uid, $order->price);
                    //获取用户充值次数
                    $order->pay_type = $this->getChargeTimes($order->uid);
                    // 更新其他定制Order表
                    if ($product->type == 'YEAR_ORDER') {
                        Log::info('YEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDERYEAR_ORDER');
                        $order_type = 'YEAR';
                        $this->yearOrder($uid, $distribution_channel_id, $price, $send_order_id);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                    } elseif ($product->type == 'BOOK_ORDER') {
                        Log::info('BOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDERBOOK_ORDER');
                        $order_type = 'BOOK';
                        $this->bookOrder($product_id, $uid, $send_order_id, $price, $distribution_channel_id);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                    } elseif ($product->type == 'TICKET_RECHARGE' || $product->type == 'NEW_USER') {
                        Log::info('TICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGETICKET_RECHARGE');
                        $order_type = 'RECHARGE';
                        $this->userCharge($product, $uid);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                    } elseif ($product->type == 'FOREVER') {
                        Log::info('FOREVER------------------------FOREVER');
                        $order_type = 'FOREVER';
                        $this->foreverFreeOrder($uid, $distribution_channel_id, $price, $send_order_id);
                        $order->order_type = $order_type;
                        $order->status = 'PAID';
                        $order->pay_end_at = date('Y-m-d H:i:s');
                        $order->transaction_id = $transaction_id;
                        $order->save();
                    }
                    $this->successPayPushMsg($uid, $product, $order->id);
                    $this->orderStatistical($order);
                    DB::commit();
                    //redis 删除未支付的uid
                    try {
                        $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:' . $distribution_channel_id;
                        Redis::hdel($key, $uid);
                    } catch (\Exception $e) {
                        Log::info('redis remote error-----------------------');
                        Log::info($e);
                    }
                    // 注册动作-》回调订单
                    $action_type = 'CallBackOrder';
                    $param = [
                        'order_sn' => isset($trade_no) ? $trade_no : '0',
                        'openid' => isset($uid) ? $uid : '0',// 没有openid,用uid写log
                    ];
                    UserService::PushUserActionToQueue($action_type, $distribution_channel_id, $param);
                    $this->userProperty($uid);
                    $this->huaweiActivity($order->activity_id,$uid,$product_id);
                }
            } else {
                Log::info('wcback_palmpay_notify_sign_fail');
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            DB::rollBack();
            Log::info('receive_wcback_palmpay_ept:' . $e->getMessage());
            echo 'fail';
            Log::info('pay_callback_end error');
            return;
        }
        Log::info('pay_callback_end');
        echo "success";
    }
    /**
     * 公众号签名@华灯初上
     * @param $params
     * @return string
     */
    protected function getSign($params, $key)
    {
        $url = $this->arr_to_url($params, false);
        $url = $url . '&key=' . $key;
        $sign = md5($url);
        return $sign;
    }
    /**
     * 公众号签名@华灯初上
     * @param $array
     * @param bool $has_sign
     * @return string
     */
    protected function arr_to_url($array, $has_sign = false)
    {
        ksort($array);
        reset($array);
        $arg = "";
        while (list ($name, $val) = each($array)) {
            if ($name == 'sign' && !$has_sign) continue;
            if (strpos($name, "_") === 0)
                continue;
            if (is_array($val))
                $val = join(',', $val);
            if ($val === "")
                continue;
            $arg .= $name . "=" . $val . "&";
        }
        $arg = substr($arg, 0, count($arg) - 2);
        return $arg;
    }
    /**
     * 单本充值会掉
     * @param $product_id
     * @param $uid
     * @param $send_order_id
     * @param $fee
     */
    protected function bookOrder($product_id, $uid, $send_order_id, $fee, $distribution_channel_id)
    {
        $book_conf = BookConfigService::getBookByProduct($product_id);
        $insert_data['bid'] = isset($book_conf->bid) ? $book_conf->bid : '';
        $insert_data['book_name'] = isset($book_conf->book_name) ? $book_conf->book_name : '';
        $insert_data['uid'] = $uid;
        $insert_data['distribution_channel_id'] = $distribution_channel_id;
        $insert_data['fee'] = $fee;
        $insert_data['send_order_id'] = $send_order_id;
        $insert_data['charge_balance'] = 0;
        $insert_data['reward_balance'] = 0;
        Log::info('start_save_book_order');
        Log::info($insert_data);
        return BookOrderService::save_book_order($insert_data);
    }
    /**
     * 包年
     * @param $uid
     * @param $distribution_channel_id
     * @param $fee
     * @param $send_order_id
     * @return mixed
     */
    protected function yearOrder($uid, $distribution_channel_id, $fee, $send_order_id)
    {
        Log::info('start_save_year_order');
        $insert_data['uid'] = $uid;
        $insert_data['distribution_channel_id'] = $distribution_channel_id;
        $insert_data['fee'] = $fee;
        $insert_data['send_order_id'] = $send_order_id;
        Log::info($insert_data);
        return YearOrderService::save_year_order($insert_data);
    }
    private function foreverFreeOrder($uid, $distribution_channel_id, $fee, $send_order_id)
    {
        Log::info('start_save_year_order');
        ('start_forever_Free_Order');
        $insert_data['uid'] = $uid;
        $insert_data['distribution_channel_id'] = $distribution_channel_id;
        $insert_data['fee'] = $fee;
        $insert_data['send_order_id'] = $send_order_id;
        Log::info($insert_data);
        return YearOrderService::foreverFree($insert_data);
    }
    /**
     * 用户充值
     * @param $product
     * @param $uid\
     */
    protected function userCharge($product, $uid)
    {
        $total = $product->price * 100 + $product->given;
        UserService::addBalance($uid, $total, $product->price * 100, $product->given);
        Log::info('update_user_balance_end:' . $uid . ' balance_add:' . $total);
    }
    /**
     * 添加订单
     * @param array $data
     * @return mixed
     */
    protected function createOrder(array $data)
    {
        $insert_data = array();
        $insert_data['uid'] = $data['uid'];
        $insert_data['distribution_channel_id'] = $data['distribution_channel_id'];
        $insert_data['product_id'] = $data['product_id'];
        $insert_data['price'] = $data['price'];
        $insert_data['status'] = 'PAID';
        $insert_data['pay_type'] = 1;
        $insert_data['trade_no'] = $data['trade_no'];
        $insert_data['send_order_id'] = $data['send_order_id'];
        $insert_data['order_type'] = $data['order_type'];
        $insert_data['pay_merchant_source'] = $data['pay_merchant_source'];
        $insert_data['pay_merchant_id'] = $data['pay_merchant_id'];
        $insert_data['transaction_id'] = $data['transaction_id'];
        $insert_data['pay_end_at'] = date('Y-m-d H:i:s');
        $insert_data['create_ip'] = $data['create_ip'];
        $insert_data['from_bid'] = $data['bid'];
        Log::info('createOrder');
        Log::info($insert_data);
        return OrderService::save_order($insert_data);
    }
    /**
     * 添加位置付订单
     * @param $data
     * @return mixed
     */
    protected function createUnPayOrder($data)
    {
        $data['status'] = 'UNPAID';
        $data['transaction_id'] = '';
        $data['pay_end_at'] = '0000-00-00 00:00:00';
        return OrderService::save_order($data);
    }
    /**
     * order total
     * @param $data
     *
     */
    protected function createOrderTotal($data)
    {
        $data['status'] = 'UNPAID';
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        DB::table('orders_total')->insert($data);
    }
    protected function updateOrderTotal($trade_no, $transaction_id)
    {
        $data['status'] = 'PAID';
        $data['transaction_id'] = $transaction_id;
        $data['pay_end_at'] = date('Y-m-d H:i:s');
        //DB::table('orders_total')->where('trade_no',$trade_no)->update($data);
    }
    protected function successPayPushMsg($uid, $product_info, $order_id)
    {
        try {
            $force_sub_info = $this->getSubscribeV2($uid);
            $data = UserService::getById($uid);
            if (!in_array($data->distribution_channel_id, [5, 123])) {
                //return false;
            }
            if ($force_sub_info) {
                //$content_format = "您好,你已经成功充值\r\n\r\n会员:%s\r\n会员ID:%s\r\n充值金额:%s\r\n充值状态:充值成功\r\n如有疑问,请点击用户中心-联系客服\r\n\r\n>点击继续阅读上次阅读";
                if (SubstituteOrderService::getByOrderId($order_id)) {
                    $content_format = "代充值客服消息:\r\n\r\n你好,您的好友为你代付成功\r\n会员:%s\r\n会员ID:%s\r\n代付金额:%s\r\n充值状态:充值成功\r\n如有疑问,请点击用户中心-联系客服\r\n\r\n>点击继续阅读上次阅读";
                } else {
                    $content_format = "您好,你已经成功充值\r\n\r\n会员:%s\r\n会员ID:%s\r\n充值金额:%s\r\n充值状态:充值成功\r\n如有疑问,请点击用户中心-联系客服\r\n\r\n>点击继续阅读上次阅读";
                }
                if ($product_info->type == 'YEAR_ORDER') {
                    $money_text = $product_info->price . '元(尊贵的年费VIP会员)';
                } elseif ($product_info->type == 'TICKET_RECHARGE') {
                    if ($product_info->given) {
                        $money_text = $product_info->price . '元(' . ($product_info->price * 100) . '书币+赠送' . $product_info->given . '书币)';
                    } else {
                        $money_text = $product_info->price . '元(' . ($product_info->price * 100) . '书币)';
                    }
                } else {
                    $money_text = '未知';
                }
                $delay = 0;
                $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($data->distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/continue';;
                $content = sprintf($content_format, $data->nickname ? $data->nickname : '匿名', $uid, $money_text, $url);
                foreach ($force_sub_info as $item) {
                    $res['openid'] = $item->openid;
                    $res['appid'] = $item->appid;
                    $res['content'] = $content;
                    $res['type'] = 'one_task';
                    $res['send_time'] = date("Y-m-d H:i:s");
                    $res['task_id'] = md5('pay_success_push');
                    $send_data = array(
                        'send_time' => date("Y-m-d H:i:s"),
                        'data' => $res
                    );
                    dispatch((new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list'));
                }
            }
        } catch (\Exception $e) {
            Log::info('pay_success_push error');
            Log::info($e);
        }
        return true;
    }
    private function orderStatistical($order)
    {
        try {
            $send_data = array(
                'type' => 'order_info',
                'data' => $order->toArray()
            );
            $send = new SendStatisticsList($send_data);
            $job = ($send)->onConnection('rabbitmq')->delay(0)->onQueue('send_statistics_list');
            dispatch($job);
        } catch (\Exception $e) {
            Log::info($e);
        }
        //灵界的推送统计\App\Modules\Statistic\Services\WapVisitStatService::customerAllStats
        try {
            if ($order->from_type) {
                $pv = Redis::hget('push:distribution_channel_id:allpv', $order->from_type);
                if ($pv) {
                    Redis::sadd('push:all:paidnum:from:' . $order->from_type, $order->uid);
                    $old = Redis::hget('push:all:paidamount', $order->from_type);
                    if ($old) {
                        Redis::hset('push:all:paidamount', $order->from_type, $old + $order->price);
                    } else {
                        Redis::hset('push:all:paidamount', $order->from_type, $order->price);
                    }
                }
            }
            if (isset($order->pay_merchant_id) && $order->pay_merchant_id)//临时统计队列清0 用于报警
            {
                $key = 'pay_merchant:' . $order->pay_merchant_id;
                Redis::hset($key, 'unpaid_num', 0);
            }
        } catch (\Exception $e) {
        }
    }
    private function getSubscribe($uid)
    {
        return ForceSubscribeService::forceSubscribeUsersByUid(['uid' => $uid]);
    }
    private function getSubscribeV2($uid)
    {
        return DB::table('force_subscribe_users')->where('uid', $uid)->where('is_subscribed', 1)->get();
    }
    public function getSubscribeOfficialName($uid, $distribution_channel_id)
    {
        $subscribe = $this->getSubscribe($uid);
        if ($subscribe && isset($subscribe->appid)) {
            $official = DB::table('official_accounts')->where('appid', $subscribe->appid)->select('nickname')->first();
            if ($official && isset($official->nickname)) {
                return $official->nickname;
            }
        }
        $res = OfficialAccountService::canUseOfficialAccountByChannelId(compact('distribution_channel_id'));
        if (isset($res->nickname) && !empty($res->nickname)) {
            return $res->nickname;
        }
        try {
            $official = DB::table('official_accounts')
                ->where('distribution_channel_id', $distribution_channel_id)
                ->where('is_auth', 1)
                ->orderBy('id', 'desc')
                ->select('nickname')->first();
            if ($official && isset($official->nickname)) {
                return $official->nickname;
            }
        } catch (\Exception $e) {
        }
        return '';
    }
    private function payAlert($pay_merchant_id, $trade_no = '', $pay_info = '', $n = 0)
    {
        $change_pay_id = 40;
        if ($pay_merchant_id == 40) {
            $change_pay_id = 9;
        }
        try {
            $time = (int)date('G');
            $change = false;
            if ($time <= 8 || $time >= 23) {
                if (!$pay_info && $pay_merchant_id != $change_pay_id) {
                    DB::table('distribution_channels')->where('pay_merchant_id', $pay_merchant_id)->update(['pay_merchant_id' => $change_pay_id]);
                    $change = true;
                }
            }
            //$number,$template_type,$param=array()
            $phone_arr = ['15868100210',  '15088790066', '13858057394', '18668029091', '18668420256'];
            //$phone_arr = ['18668029091'];
            $param = ['pay_id' => $pay_merchant_id];
            if ($n) {
                $template_type = 'pay_channel_remind';
                //$content = '支付通道:' . $pay_merchant_id . ',获取授权信息失败';
            } else {
                $template_type = 'pay_channel_remind';
                //$content = '支付通道:' . $pay_merchant_id . ',订单号为' . $trade_no . '支付异常,异常信息:' . json_encode($pay_info);
            }
            if ($change) {
                $template_type = 'pay_channel_change';
                $param = ['pay_id' => $pay_merchant_id, 'new_pay_id' => $change_pay_id];
            }
            $last_alert_time = Redis::hget('autopayalert',$pay_merchant_id);
            if($last_alert_time && (time() -$last_alert_time) <= 3600 ){
                return ;
            }
            Redis::hset('autopayalert',$pay_merchant_id,time());
            foreach ($phone_arr as $phone) {
                AliSMS::send($phone, $template_type, $param);
            }
        } catch (\Exception $e) {
        }
    }
    private function createSubstituteOrder($order_id, $uid, $pay_uid)
    {
        SubstituteOrderService::createOrder($order_id, $uid, $pay_uid);
    }
    private function recordOtherParam($order_id, $uid)
    {
        $gxhp = ReadRecordService::getByField($uid, 'gxhp');
        if ($gxhp) {
            OrderParamService::create($order_id, $gxhp);
        }
    }
    private function substituteOrderPrice($order_id, $prize_fee = 500)
    {
        SubstituteOrderService::SubstituteOrderPrize($order_id, $prize_fee);
    }
    private function updateUserSendOrderId(int $uid, $send_order_id)
    {
        if ($send_order_id && $uid) {
            $user = UserService::getById($uid);
            if ($user && !$user->send_order_id) {
                UserService::updateInfo($uid, compact('send_order_id'));
            }
        }
    }
    /**
     * 测书智能推送统计 付费用户数、充值金额
     * @param $bid
     * @param $uid
     * @param $price
     */
    private function smartPushTestBookPaidUv($bid, $uid, $price)
    {
        $smart_bid = ReadRecordService::getSmartPush($uid);
        if ($smart_bid && in_array($bid, $smart_bid)) {
            try {
                $key = 'smartPushTestBookPaidUv:bid:%s';
                Redis::sadd(sprintf($key, $bid), $uid);
                $now_amount = Redis::hget('smartPushTestBookPaidAmount', $bid);
                if (!$now_amount) {
                    $now_amount = 0;
                }
                Redis::hset('smartPushTestBookPaidAmount', $bid, $now_amount + $price);
            } catch (\Exception $e) {
            }
        }
    }
    /**
     * 获取用户第几次充值
     * @param $uid
     * @return int
     */
    private function getChargeTimes($uid)
    {
        $count = OrderService::getUserChargeTimes($uid);
        return $count + 1;
    }
    //米玩 订单转移
    private function transfer($distribution_channel_id)
    {
        if (in_array($distribution_channel_id, explode(',', redisEnv('MIWAN_TRANSFER_CHANNEL_ID', 1)))) {
            $random = random_int(1, 100);
            $miwan_transfer_probability = redisEnv('MIWAN_TRANSFER_PROBABILITY', 0);
            $miwan_transfer_to_channel_id = redisEnv('MIWAN_TRANSFER_TO_CHANNEL_ID', 0);
            if ($miwan_transfer_to_channel_id && $random <= $miwan_transfer_probability) {
                return $miwan_transfer_to_channel_id;
            }
        }
        return 0;
    }
    private function userProperty($uid){
        try{
            $userproperty = UserDivisionCpcPropertyService::getUserSubscribeAndChargeInfoByUid($uid);
            if(!$userproperty) return ;
            UserDivisionCpcPropertyService::createorUpdate($userproperty);
        }catch (\Exception $e){}
    }
    private function huaweiActivity($activity_id,$uid,$product_id){
        $huawei_activity_id = redisEnv('HUAWEI_ACTIVITY_ID');
        if($huawei_activity_id &&  $activity_id && $activity_id == $huawei_activity_id){
            $product_id_relate_lottery_count = ['6117'=>1,'6118'=>2,'6119'=>4,'6120'=>8];
            if(isset($product_id_relate_lottery_count[$product_id])){
                $info = DB::table('huaweilottery_user_counts')->where('uid',$uid)->select('count')->first();
                if($info){
                    DB::table('huaweilottery_user_counts')->where('uid',$uid)->update([
                        'uid'=>$uid,
                        'count'=>$info->count+$product_id_relate_lottery_count[$product_id],
                        'updated_at'=>date('Y-m-d H:i:s')
                    ]);
                }else{
                    DB::table('huaweilottery_user_counts')->insert([
                        'uid'=>$uid,
                        'count'=>$product_id_relate_lottery_count[$product_id],
                        'updated_at'=>date('Y-m-d H:i:s'),
                        'created_at'=>date('Y-m-d H:i:s')
                    ]);
                }
            }
        }
    }
    private function palmpaySpecial($transaction_id,$trade_no)
    {
        try{
            $order = OrderService::getByTradeNo($trade_no);
            $product_id = $order->product_id;
            $product = ProductService::getProductSingle($product_id);
            $init_order = [
                'distribution_channel_id' => $order->distribution_channel_id,
                'uid' => $order->uid,
                'product_id' => $product_id,
                'price' => $order->price,
                'pay_type' => 1,
                'trade_no' => $order->uid.'-'.$order->id,
                'pay_merchant_source' => $order->pay_merchant_source,
                'pay_merchant_id' => $order->pay_merchant_id,
                'create_ip' => $order->create_ip,
                'send_order_id' => $order->send_order_id,
                'send_order_name' => $order->send_order_name,
                'order_type' => $order->order_type,
                'from_bid' => $order->from_bid,
                'from_type' => $order->from_type,
                'activity_id' => $order->activity_id,
                'inner_send_order_id' => $order->inner_send_order_id,
                'status'=>'PAID',
                'transaction_id'=>$transaction_id,
                'pay_end_at'=>date('Y-m-d H:i:s')
            ];
            OrderService::save_order($init_order);
            if ($product->type == 'YEAR_ORDER') {
                Log::info('palmpaySpecial YEAR_ORDER');
                $this->yearOrder($order->uid, $order->distribution_channel_id, $order->price, $order->send_order_id);
            } elseif ($product->type == 'BOOK_ORDER') {
                Log::info('palmpaySpecial BOOK_ORDER');
                $this->bookOrder($product_id, $order->ui, $order->send_order_id,  $order->price, $order->distribution_channel_id);
            } elseif ($product->type == 'TICKET_RECHARGE' || $product->type == 'NEW_USER') {
                Log::info('palmpaySpecial TICKET_RECHARGE');
                $this->userCharge($product, $order->uid);
            } elseif ($product->type == 'FOREVER') {
                Log::info('palmpaySpecial-------FOREVER');
                $this->foreverFreeOrder($order->uid, $order->distribution_channel_id, $order->price, $order->send_order_id);
            }
        }catch (\Exception $e){
            Log::info($e);
        }
    }
}