<?php
namespace app\controller\api\merchant\sxy;

use alipay\aop\AopClient;
use alipay\aop\request\AlipaySystemOauthTokenRequest;
use app\common\dao\movie\order\MovieOrderDao;
use app\common\model\store\order\StoreOrder;
use app\common\model\user\UserCertification;
use app\common\repositories\merchant\order\OrderGzcRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\movie\MovieRepository;
use app\common\repositories\store\order\StoreGroupOrderRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\controller\Aes;
use app\model\sxy\DeclareLog;
use app\traits\HuiPay;
use app\traits\ShouxinyiApiRequest;
use crmeb\exceptions\AuthException;
use think\Exception;
use think\facade\Db;
use think\facade\Request;
use think\facade\Log;
class Access
{
    use HuiPay;
    //入网查询
    public function queryMer($m_id){
        try {
            if($m_id == '')
                return app('json')->fail('参数错误');
            return app('json')->success('入网完成');
        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail('查询失败');
        }
    }

    //发起支付(微信小程序、公众号预下单返回oid)
    public function onlinePay(){

        try {

            $return = array(
                'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
                'status' => $res['status'],
                'scanCode' => $res['scanCode'] ?? '',//Base64二维码
                'appParams' => $res['appParams'] ?? '',//App调用码
                'jsString' => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
                'wechatId' => $res['wechatId'] ?? '',//微信原始ID串
                'tradeNo' => $res['tradeNo'] ?? '',//支付宝生活号调用id
                'token' => $res['token'] ?? '',    //微包支付调用token
            );
            return app('json')->success($return);
        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail('发起支付失败');
        }
    }

    //回调
    public function notify($type){

        try {
            $data = Request::param('data');
            Db::name("log")->insert(array('data'=>"首信易回调data:".json_encode($data)));//日志记录
            $header = Request::header();
            switch ($type){
                case 'createMerchant_5upay':
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"入网回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"入网回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"入网回调res:".json_encode($res)));//日志记录
                    //入网记录
                    $log = new DeclareLog();
                    $log -> updateLog(array(
                        'status' => $res['subMerchantReviewStatus'],
                        'message' => $res['subMerchantReviewRemarks']??'',
                        'requestId'=>$res['requestId']
                    ));
                    $mid = $log -> getMidLog($res['requestId']);
                    if($res['subMerchantReviewStatus'] == 'SUCCESS' || $res['subMerchantReviewStatus'] == 'ESIGN_SUCCESS'){
                        $mer_id = Db::name('merchant_intention') -> where('mer_intention_id',$mid) -> find();
                        if($mer_id['hf_status']==2){
                            Db::name('merchant_intention')->where('mer_intention_id',$mid)->update(['status'=>1]);
                        }
                        Db::name('merchant') -> where('mer_id',$mer_id['mer_id']??0) -> update(['sxy_submerchant_id'=>$res['subMerchantId']]);
                    }else{
                        Db::name('merchant_intention')->where('mer_intention_id',$mid)->update(['status'=>3]);
                    }

                    break;
                case 'pay_5upay':
                    Db::name("log")->insert(array('data'=>"支付回调data:".json_encode($data)));//日志记录
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"支付回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付回调res:".json_encode($res)));//日志记录
                    $requestId = [];
                    if(strpos($res['requestId'],'_') !== false){
                        $requestId = explode("_",$res['requestId']);
                    }
                    if($res['status'] == 'SUCCESS'){
                        Db::name('store_group_order') -> where('group_order_sn',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber']]);
                        $pay_type = $res['paymentModeAlias'] == 'MINIAPPS_WEIXIN_PAY' ? 1 : 4;
                        event('pay_success_order', ['order_sn' => $requestId[0],'pay_type'=>$pay_type]);
                    }
                    break;
                case "pay_split_5upay":
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"分账回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"分账回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"分账回调res:".json_encode($res)));//日志记录
                    if($res['status'] == 'SUCCESS'){
                        $status = ['status'=>1];
                    }else{
                        $status = ['status'=>2];
                    }
                    Db::name('store_split_order') -> where("requestId",$res['requestId']) -> update($status);
                    break;
                case "pay_refund_5upay":
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"退款回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"退款回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"退款回调res:".json_encode($res)));//日志记录
                    break;
                case "pay_annual":
                    Db::name("log")->insert(array('data'=>"支付年费回调data:".json_encode($data)));//日志记录  1
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"支付年费回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付年费回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付年费回调res:".json_encode($res)));//日志记录
                    $requestId = [];
                    if(strpos($res['requestId'],'_') !== false){
                        $requestId = explode("_",$res['requestId']);
                    }
                    if($res['status'] == 'SUCCESS'){
                        $annual_cost_order=Db::name('merchant_annual_cost_order')-> where('order_no',$requestId[0])->find();
                        if($annual_cost_order['status'] == 0) {


//                        Db::name('merchant_annual_cost_order') -> where('order_no',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber']]);
                            Db::name('merchant_annual_cost_order')->where('order_no', $requestId[0])->update(['rand' => $requestId[1], 'serialNumber' => $res['serialNumber'], 'status' => 1]);
                            //如果有商户id就是续费
                            $mer_id = Db::name('merchant_annual_cost_order')->where('order_no', $requestId[0])->value('mer_id');
                            if ($mer_id !== 0) {
                                $expire_time = strtotime(date('Y-m-d')) + 86400 * 365 + 86400 - 1;
                                Db::name('merchant')->where('mer_id', $mer_id)->update(['expire_time' => $expire_time, 'status' => 1]);
                            }
                            $mer = Db::name('user_mer') -> where('uid',$annual_cost_order['uid']) -> find();
                            if(!$mer){
                                Db::name('user_mer') -> insert(['uid'=>$annual_cost_order['uid'],'mer'=>2]);
                            }else{
                                Db::name('user_mer') -> where('uid',$annual_cost_order['uid'])->inc('mer', 2) ->update();;
                            }
//                        $mer_data=Db::name('merchant_annual_cost_order') -> where('order_no',$requestId[0]) ->field('tz_integral,tz_money,mer_id')->find();
//                        $integral=bcadd(bcdiv(500, '5',2),$mer_data['tz_integral'],2);
//                        $moneys=bcadd(500,$mer_data['tz_money'],2);
//                        $updateData=[
//                            'tz_integral'=>$integral,
//                            'tz_money'=>$moneys,
//                            'status'=>1
//                        ];
//                        Db::name('merchant')->where('mer_id',$mer_data['mer_id'])->update($updateData);
                            //佣金跟养老金商户或者用户邀请一个用户成功注册成为平台商家会员（6000元）；获得2000元返佣+1000元养老金；商户自己获得1000元养老金；

                            $this->nianfei_yj($annual_cost_order['id']);
                        }
                    }

                    break;
                case "pay_activation":
                    Db::name("log")->insert(array('data'=>"支付激活码回调data:".json_encode($data)));//日志记录  1
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"支付激活码回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付激活码回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付激活码回调res:".json_encode($res)));//日志记录
                    $requestId = [];
                    if(strpos($res['requestId'],'_') !== false){
                        $requestId = explode("_",$res['requestId']);
                    }
                    if($res['status'] == 'SUCCESS'){
                        try{


//                        Db::name('merchant_annual_cost_order') -> where('order_no',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber']]);
                            $order_data=Db::name('activation_code_order') -> where('order_no',$requestId[0]) -> find();
                            Db::name('channel_user')->where('uid',$order_data['uid'])->update(['status'=>1]);
                            if($order_data['status']==1){
                                return false;
                            }
                            $id=Db::name('activation_code')->insertGetId([
                                'uid'=>$order_data['uid'],
                                'code'=>$this->randomFromDev(20),
                                'ctime'=>time(),
                                'status'=>1,
                                'utime'=>time(),
                                'use_uid'=>0,
                                'type'=>1
                            ]);
//                        $code_data=Db::name('activation_code')->where('status',0)->where('uid',0)->select();
//                        if(!$code_data->isEmpty()){
//                            $data=$code_data->toArray();
//                            Db::name('activation_code')->where('id',$data[0]['id'])->update(['uid'=>$order_data['uid'],'status'=>1,'utime'=>time()]);
                            Db::name('activation_code_order') -> where('order_no',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber'],'status'=>1,'code_id'=>$id]);
//                        }
                        }catch (\Exception $e) {
                            Db::name('log')->insert(['data'=>'支付激活码错误：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
                        }
                    }
                    //处理佣金
                    $num=$this->activation_yj($requestId[0]);
                    //分账
                    $this->activation_spilet($requestId[0],$num);
                    break;
                case "pay_channel":
                    Db::name("log")->insert(array('data'=>"支付渠道商回调data:".json_encode($data)));//日志记录  1
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"支付渠道商回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付渠道商回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"支付渠道商回调res:".json_encode($res)));//日志记录
                    $requestId = [];
                    if(strpos($res['requestId'],'_') !== false){
                        $requestId = explode("_",$res['requestId']);
                    }
                    if($res['status'] == 'SUCCESS'){
                        try{
                            $order_data=Db::name('channel_order') -> where('order_no',$requestId[0]) -> find();
                            if($order_data['status']==1){
                                return false;
                            }
                            Db::name('channel_user')->where('uid',$order_data['uid'])->update(['status'=>1]);
                            Db::name('channel_order') -> where('order_no',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber'],'status'=>1]);

                        }catch (\Exception $e) {
                            Db::name('log')->insert(['data'=>'支付渠道商错误：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
                        }
                        try{


                            //分账
                            $this->channel_spilet($requestId[0]);
                            //分佣
                            $this->channel_fenyong($requestId[0]);
//                            //给7个激活码
//                            for($i=0;$i<=6;$i++){
//                                Db::name('activation_code')->insertGetId([
//                                    'uid'=>$order_data['uid'],
//                                    'code'=>$this->randomFromDev(20),
//                                    'ctime'=>time(),
//                                    'status'=>1,
//                                    'utime'=>time(),
//                                    'use_uid'=>0,
//                                    'type'=>2
//                                ]);
//                            }
                            //赠送返本商户
                            $mer = Db::name('user_mer') -> where('uid',$order_data['uid']) -> find();
                            if(!$mer){
                                Db::name('user_mer') -> insert(['uid'=>$order_data['uid'],'mer'=>10]);
                            }else{
                                Db::name('user_mer') -> where('uid',$order_data['uid'])->inc('mer', 10) ->update();;
                            }
                            //赠送商户
                            $merchant=Db::name('merchant')->where('uid',$order_data['uid'])->find();
                            if(!$merchant)
                                Db::name('merchant_intention')->insert(['uid'=>$order_data['uid'],'activation_code'=>rand('000000000','999999999')]);
                            //赠送大仓会员资格
                            $dacang_user = Db::name('da_cang_user')->where('uid', $order_data['uid'])->find();
                            $time = date('Y-m-d', time());
                            $time = strtotime($time);
                            $end_time = $time + 31536000 - 1;
                            $dc_id = 1;
                            //如果不是金卡会员,赠送金卡会员一年
                            if (!$dacang_user) {
                                Db::name('da_cang_user')->insert(['uid' => $order_data['uid'], 'ctime' => time(), 'end_time' => $end_time, 'dc_id' => $dc_id,'status'=>1,'type'=>1]);
                            }else{
                                //如果是银卡会员,变成金卡，一年 || 是否已过期,如果已过期,赠送金卡会员一年
                                if($dacang_user['type'] == 2 || $dacang_user['end_time'] < $time){
                                    Db::name('da_cang_user')->where('uid', $order_data['uid'])->where('dc_id', $dc_id)->update(['end_time' => $end_time,'status'=>1,'type'=>1]);
                                }

                            }
                        }catch (\Exception $exception){
                            Db::name('log')->insert(['data'=>'支付渠道商错误：'.$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】']);
                        }
                    }

                    break;
                case "withdrawal_5upay":
                    $request['data'] = $data;
                    $request['encryptKey'] = $header['encryptkey'];
                    $request['merchantId'] = $header['merchantid'];
                    $request['requestId'] = $header['requestid'];
                    $res = ShouxinyiApiRequest::returnDecode($request);
                    Db::name("log")->insert(array('data'=>"提现回调data:".json_encode($data)));//日志记录
                    Db::name("log")->insert(array('data'=>"提现回调header:".json_encode($header)));//日志记录
                    Db::name("log")->insert(array('data'=>"提现回调res:".json_encode($res)));//日志记录
                    if($res["status" ]=="SUCCESS"){
                        Db::name('business_wthdrawal')
                            ->where(['requestId'=>$res['requestId']])
                            ->update(['status'=>2,'success_time'=>time(),'desc'=>'提现成功']);
                    }
                    break;
                default:
                    Db::name("log")->insert(array('data'=>$type));//日志记录
            }

        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }
    }

    public function add_activation_code($uid,$num){
        for($i=1;$i<=$num;$i++){
            Db::name('activation_code')->insert([
                'uid'=>$uid,
                'code'=>$this->randomFromDev(20),
                'ctime'=>time(),
                'status'=>1,
                'utime'=>time(),
                'use_uid'=>0,
                'type'=>2
            ]);
        }
    }


    public function nianfei_yj($id){

        try{
            //商户拿5%养老金
            $annual=Db::name('merchant_annual_cost_order')-> where('id',$id)->find();
            $uid = $annual['uid'];
            $mer_id = $annual['mer_id'];
            $pay_price = $annual['pay_price'] ?? 0;
            if ($pay_price == 0) {
                return '';
            }
            //订单用户
            $user = Db::name('user')->where('uid', $uid)->find();
            //订单用户直接上级
            $top_user = Db::name('user')->where('uid', $user['spread_uid'])->find();
            //上级身份是否大仓会员
            $is_da_cang_vip=Db::name('da_cang_user')->where('status',1)->where('uid',$user['spread_uid'])->find();
            //上级身份是否商户
            $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$user['spread_uid'])->find();
            $is_shanghu2=Db::name('merchant')->where('uid',$user['spread_uid'])->find();
            $is_shanghu3=Db::name('merchant_intention')->where('uid',$user['spread_uid'])->find();
            //渠道商
            $is_channel = Db::name('channel_user') -> where('uid',$user['spread_uid'])->where('status',1)->find();

            $number = bcmul($pay_price, 0.1, 2);//养老金
            //购买者本人给10%养老金
            if($number > 0){
                $data=[
                    'link_id' => $annual['id'],
                    "uid"=>$uid,
                    "pm"=>1,
                    "title"=>'商户养老金',
                    "category"=>"now_money",
                    "type"=>"commission",
                    "number"=>$number,
                    "balance"=>0,
                    "mark"=>'成为商户获得'.$number.'元养老金',
                    "status"=>1,
                    "commission_type"=>5,
                    "order_sn"=>$annual['order_no'],
                    "mer_id"=>$mer_id,
                    "source"=>0,
                    "type_shop"=>0,
                    'gzc'=>0
                ];
                Db::name("user_bill")->insert($data);
                Db::name("user")->where("uid",$uid)->inc('annuity', $number) ->update();
                Db::name("user")->where("uid",$uid)->inc('annuity_num', 1) ->update();
            }
            $top_yongjin = 0;//直接上级佣金
            $top_top_yongjin = 0;//间接上级佣金

            //直接上级
            if ($top_user['uid'] != 0) {
                //如果是大仓会员
                if($is_da_cang_vip){
                    //如果上级是金卡会员 15%佣金
                    if($is_da_cang_vip['type'] == 1){
                        $top_yongjin = bcmul($pay_price, 0.15, 2);
                    }elseif ($is_da_cang_vip['type'] == 2){
                        //如果上级是银卡会员 10%佣金
                        $top_yongjin = bcmul($pay_price, 0.10, 2);
                    }
                }
                //如果是商户 20%佣金
                if($is_shanghu1||$is_shanghu2||$is_shanghu3){
                    $top_yongjin = bcmul($pay_price, 0.20, 2);
                }
                //如果是渠道商 25% 佣金
                if($is_channel){
                    $top_yongjin = bcmul($pay_price, 0.25, 2);
                }
                //如果上级有返本商户系统.直接佣金为60%
                $mer = Db::name('user_mer') -> where('uid',$user['spread_uid']) -> find();
                $mer_num = $mer['mer'] ?? 0;
                if($mer_num > 0){
                    $top_yongjin = bcmul($pay_price, 0.6, 2);
                    //减掉一次返本商户系统
                    Db::name('user_mer') -> where('uid',$user['spread_uid']) -> dec('mer',1) ->update();
                }
                if($top_yongjin > 0){
                    $bill_data = [
                        'uid' => $top_user['uid'],
                        'link_id' => $annual['id'],
                        'pm' => 1,
                        'title' => '佣金',
                        'category' => 'now_money',
                        'type' => 'commission',
                        'number' => $top_yongjin,
                        'mark' => '推荐商户获得' . $top_yongjin . '招募奖励',
                        'status' => 1,
                        'commission_type' => 10,
                        'order_sn' => $annual['order_no'],
                        'type_shop' => 0,
                        'mer_id' => $mer_id,
                        'source' => 0,
                        'order_type' => 1
                    ];
                    Db::name('user_bill')->insert($bill_data);
                    Db::name('user')->where('uid', $top_user['uid'])->inc('brokerage_price', $top_yongjin)->update();
                }
            }
            //间接上级 如果直接上级是渠道商。间接上级是渠道商推荐人，如果没渠道商推荐人找注册推荐人
            if($is_channel){
                $top_top_user = Db::name('channel_user') -> where('uid',$top_user['spread_uid'])->where('status',1)->value('recommend_uid');
                if($top_top_user == ''){
                    $top_top_user = Db::name('user')->where('uid', $top_user['spread_uid'])->value('uid');
                }
            }else{
                //直接上级不是渠道商，就找注册推荐人
                $top_top_user = Db::name('user')->where('uid', $top_user['spread_uid'])->value('uid');
            }
            if($top_top_user > 0){
                //商户
                $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_top_user)->find();
                $is_shanghu2=Db::name('merchant')->where('uid',$top_top_user)->find();
                $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_top_user)->find();
                //大仓会员
                $is_da_cang_vip=Db::name('da_cang_user')->where('uid',$top_top_user)->where('status',1)->find();
                //渠道商
                $is_channel = Db::name('channel_user') -> where('uid',$top_top_user)->where('status',1)->find();
                //如果是大仓会员
                if($is_da_cang_vip){
                    //如果间接上级是金卡会员 25%佣金
                    if($is_da_cang_vip['type'] == 1){
                        $top_top_yongjin = bcmul($pay_price, 0.25, 2);
                    }elseif ($is_da_cang_vip['type'] == 2){
                        //如果上级是银卡会员 20%佣金
                        $top_top_yongjin = bcmul($pay_price, 0.20, 2);
                    }
                }
                //如果是商户 30%佣金
                if($is_shanghu1||$is_shanghu2||$is_shanghu3){
                    $top_top_yongjin = bcmul($pay_price, 0.3, 2);
                }
                //如果是渠道商 30% 佣金
                if($is_channel){
                    $top_top_yongjin = bcmul($pay_price, 0.3, 2);
                }
                if($top_top_yongjin > 0){
                    $bill_data = [
                        'uid' => $top_top_user,
                        'link_id' => $annual['id'],
                        'pm' => 1,
                        'title' => '佣金',
                        'category' => 'now_money',
                        'type' => 'commission',
                        'number' => $top_top_yongjin,
                        'mark' => '推荐商户获得' . $top_top_yongjin . '培育奖励',
                        'status' => 1,
                        'commission_type' => 10,
                        'order_sn' => $annual['order_no'],
                        'type_shop' => 0,
                        'mer_id' => $mer_id,
                        'source' => 0,
                        'order_type' => 1
                    ];
                    Db::name('user_bill')->insert($bill_data);
                    Db::name('user')->where('uid', $top_top_user)->inc('brokerage_price', $top_top_yongjin)->update();
                }
            }
        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>'年费佣金error'.$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }


        return true;

        //2022年6月21号之前的版本
        try {
            //用户注册成为平台商家会员（6000元），商户自己获得666元养老金；商户上级获得666佣金无养老金 ，上上级如果为商户或者大仓会员的话再给666佣金无养老金 上上上级是商户的话再给666佣金无养老金
            //商户拿666养老金
            $annual=Db::name('merchant_annual_cost_order')-> where('id',$id)->find();
            $uid = $annual['uid'];
            $mer_id = $annual['mer_id'];
            $number = 666;//养老金
            $data=[
                'link_id' => $annual['id'],
                "uid"=>$uid,
                "pm"=>1,
                "title"=>'商户养老金',
                "category"=>"now_money",
                "type"=>"commission",
                "number"=>$number,
                "balance"=>0,
                "mark"=>'成为商户获得'.$number.'元养老金',
                "status"=>1,
                "commission_type"=>5,
                "order_sn"=>$annual['order_no'],
                "mer_id"=>$mer_id,
                "source"=>0,
                "type_shop"=>0,
                'gzc'=>0
            ];
            Db::name("user_bill")->insert($data);
            Db::name("user")->where("uid",$uid)->inc('annuity', $number) ->update();
            Db::name("user")->where("uid",$uid)->inc('annuity_num', 1) ->update();
//公证处入账
//            $certification = UserCertification::getInstance()->where('uid', $uid)->find();
//            if($certification) {
//                $user_data = Db::name('user')->where('uid', $uid)->find();
//                $user_data['real_name']=Db::name('user_certification')->where('status',1)->where('uid',$user_data['uid'])->value('user_name');
//                $user_data['account']=Db::name('user_certification')->where('status',1)->where('uid',$user_data['uid'])->value('mobile');
//                $online = ['uid' => $uid, 'pay_type' => $annual['pay_type'] == 'al' ? 4 : 1, 'order_sn' => $annual['order_no'], 'order_id' => $annual['id']];
//                $certification = ['user_name' => $user_data['real_name'], 'mobile' => $user_data['account'], 'user_card' => $user_data['card_id']];
//                $this->GZC($online, $certification, $number);
//            }
            //商户上级普通会员获得333佣金无养老金
            //商户上级大仓会员获得666佣金无养老金
            //商户上级商户获得999佣金无养老金
            //商户上级渠道商获得999佣金无养老金
            $top_user = Db::name('user') -> where('uid',Db::name('user')->where('uid',$uid)->value('spread_uid')) -> find();
            $is_da_cang_vip=Db::name('da_cang_user')->where('status',1)->where('uid',$top_user['uid'])->find();
            $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_user['uid'])->find();
            $is_shanghu2=Db::name('merchant')->where('uid',$top_user['uid'])->find();
            $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_user['uid'])->find();
            //渠道商
            $is_channel = Db::name('channel_user') -> where('uid',$top_user['uid'])->where('status',1)->find();
            $direct_number = 333;
            if($is_da_cang_vip){
                $direct_number = 666;
            }
            if($is_shanghu1||$is_shanghu2||$is_shanghu3){
                $direct_number = 999;
            }
            if($is_channel){
                $direct_number = 1999;
            }
            if($top_user){
                $spread_data=[
                    'link_id' => $annual['id'],
                    "uid"=>$top_user['uid'],
                    "pm"=>1,
                    "title"=>'商户佣金',
                    "category"=>"now_money",
                    "type"=>"commission",
                    "number"=>$direct_number,
                    "balance"=>0,
                    "mark"=>'推荐商户获得'.$direct_number.'元佣金',
                    "status"=>1,
                    "commission_type"=>10,
                    "order_sn"=>$annual['order_no'],
                    "mer_id"=>$mer_id,
                    "source"=>0,
                    "type_shop"=>0
                ];
                Db::name("user_bill")->insert($spread_data);
                Db::name("user")->where("uid", $top_user['uid'])->inc('brokerage_price', $direct_number)->update();
            }
//            $certification = UserCertification::getInstance()->where('uid', $spread_uid)->find();
//            if($certification) {
//                $user_data = Db::name('user')->where('uid', $spread_uid)->find();
//                $user_data['real_name']=Db::name('user_certification')->where('status',1)->where('uid',$user_data['uid'])->value('user_name');
//                $user_data['account']=Db::name('user_certification')->where('status',1)->where('uid',$user_data['uid'])->value('mobile');
//
//                $online = ['uid' => $uid, 'pay_type' => $annual['pay_type'] == 'al' ? 4 : 1, 'order_sn' => $annual['order_no'], 'order_id' => $annual['id']];
//                $certification = ['user_name' => $user_data['real_name'], 'mobile' => $user_data['account'], 'user_card' => $user_data['card_id']];
//                $this->GZC($online, $certification, $number);
//            }

            //商户上级普通会员获得0佣金无养老金   间接
            //商户上级大仓会员获得666佣金无养老金   间接
            //商户上级商户获得999佣金无养老金      间接
            //商户上级渠道商获得1999佣金无养老金    间接
            $yj = 0;
            $is_shanghu=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_user['spread_uid'])->find();
            $is_shanghu2=Db::name('merchant')->where('uid',$top_user['spread_uid'])->find();
            $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_user['spread_uid'])->find();
            $is_daCang=Db::name('da_cang_user')->where('uid',$top_user['spread_uid'])->where('status',1)->find();
            //渠道商
            $is_channel = Db::name('channel_user') -> where('uid',$top_user['spread_uid'])->where('status',1)->find();

            if($is_daCang){
                $yj = 666;
            }
            if($is_shanghu||$is_shanghu2||$is_shanghu3||$is_channel){
                $yj = 999;
            }

            $spread_yh_data = [
                'link_id' => $annual['id'],
                "uid" => $top_user['spread_uid'],
                "pm" => 1,
                "title" => '商户佣金',
                "category" => "now_money",
                "type" => "commission",
                "number" => $yj,
                "balance" => 0,
                "mark" => '推荐商户获得' . $yj . '元佣金',
                "status" => 1,
                "commission_type" => 10,
                "order_sn" => $annual['order_no'],
                "mer_id" => $mer_id,
                "source" => 0
            ];
            if($yj > 0){
                Db::name("user_bill")->insert($spread_yh_data);
                Db::name("user")->where("uid", $top_user['spread_uid'])->inc('brokerage_price', $yj)->update();
            }

//            $top_top_data=Db::name('user')->where('uid',Db::name('user')->where('uid',$top_user['spread_uid'])->value('spread_uid'))->find();
//            $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_top_data['uid'])->find();
//            $is_shanghu2=Db::name('merchant')->where('uid',$top_user['spread_uid'])->find();
//            $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_user['spread_uid'])->find();
//            if($is_shanghu1||$is_shanghu2||$is_shanghu3){
//                $spread_yh_data = [
//                    'link_id' => $annual['id'],
//                    "uid" => $top_top_data['uid'],
//                    "pm" => 1,
//                    "title" => '商户佣金',
//                    "category" => "now_money",
//                    "type" => "commission",
//                    "number" => $yj,
//                    "balance" => 0,
//                    "mark" => '推荐商户获得' . $yj . '元佣金',
//                    "status" => 1,
//                    "commission_type" => 10,
//                    "order_sn" => $annual['order_no'],
//                    "mer_id" => $mer_id,
//                    "source" => 0
//                ];
//                Db::name("user_bill")->insert($spread_yh_data);
//                Db::name("user")->where("uid", $top_top_data['uid'])->inc('brokerage_price', $yj)->update();
//            }
        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>'年费佣金error'.$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }
    }

    public function test1111()
    {
//        $domain = $this->request->domain();
//        if(strpos($domain, 'test.hebeiyhc.com') !== false){
        $requestId[0]=input('order_sn');
//        $pay_type=5;
        Db::name('store_group_order') -> where('group_order_sn',$requestId[0]) -> update(['rand'=>mt_rand(1000,9999)]);

        $orderSn = $requestId[0];
        $groupOrder = app()->make(StoreGroupOrderRepository::class)->getWhere(['group_order_sn' => $orderSn]);
        if (!$groupOrder || $groupOrder->paid == 1) return;
        app()->make(StoreOrderRepository::class)->paySuccess($groupOrder);
//        event('pay_success_order', ['order_sn' => $requestId[0],'pay_type'=>$pay_type]);
        dump('成功');
//        dump($this->randomFromDev(20));
//        }
    }


    function randomFromDev($len)
    {
        $fp = @fopen('/dev/urandom','rb');
        $result = '';
        if ($fp !== FALSE) {
            $result .= @fread($fp, $len);
            @fclose($fp);
        }
        else
        {
            trigger_error('Can not open /dev/urandom.');
        }
        // convert from binary to string
        $result = base64_encode($result);
        // remove none url chars
        $result = strtr($result, '+/', '-_');
        // Remove = from the end
        $result = str_replace('=', 't', $result);
        $result=rtrim($result,' ');
        return $result;
    }



    //app小程序话费支付
    public function hf_pay_wechat_mp(){
        try {
            log::info("微信小程序回调");
            Db::name('log')->insert(['data'=>'汇付订单支付pay_wechat_mp-66666666---发起支付']);
            $oid = Request::param('oid','');
            $code = Request::param('code','');
            $type = Request::param('type','');
            if($oid == '') return app('json')->fail("请检查参数是否正确");

            $groupOrder = Db::name('order_huafei_hf')->where('order_id', (int)$oid)->find();
            if (!$groupOrder) return app('json')->fail('订单不存在或已支付');

            $res = $this->pay_huifu($type,$code,$groupOrder,"幸福宝",env('APP_URL')."/api/hf_notify/huafei",'delay');
            Db::name('log')->insert(['data'=>'汇付话费订单支付--- 返回参数'.json_encode($res)]);
            if (isset($res['id'])) {
                return app('json')->success($res);
            }
            return app('json')->fail($res);
        }catch (Exception $exception){
            log::info("支付异常======");
            log::info($exception);
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail("异常");
        }
    }



    //小程序支付
    public function pay_wechat_mp(StoreGroupOrderRepository $groupOrderRepository){

        $oid = Request::param('oid','');


        $store_order_data = Db::name('store_order')->where('group_order_id',$oid)->find();

        $array_fzone_paytype = json_decode(  $store_order_data['fzone_paytype'],true);
        if(!empty($array_fzone_paytype['type'])){

            //a3 会员专区的现金+VR支付
            if($array_fzone_paytype['type'] == 'a3'){

                $userdata = Db::name('user')->where('uid',$store_order_data['uid'])->find();
                //查询用户的VR是否足够
                $vr_pri = $userdata['vr'] - $array_fzone_paytype['other'];

               // return app('json')->fail($oid);
                //return app('json')->fail($userdata['vr'] . " pri:" .$array_fzone_paytype['other']);

                if($vr_pri < 0){
                    return app('json')->fail('VR不足，请重试!');
                }

                //如果VR足够，修改订单的实际价格
                $group_order_datas = Db::name('store_group_order')->where('group_order_id',$oid)->find();
                if(!empty($group_order_datas)){
                    Db::name('store_group_order')->where('group_order_id',$oid)->update(['pay_price'=>$array_fzone_paytype['price']]);
                }else{
                    return app('json')->fail('找不到订单，请重试!');
                }
            }
            //b2 精彩生活区的现金+积分支付
            if($array_fzone_paytype['type'] == 'b2'){

                $userdata = Db::name('user')->where('uid',$store_order_data['uid'])->find();
                //查询用户的积分是否足够
                $score_pri = $userdata['score'] - $array_fzone_paytype['other'];
                if($score_pri < 0){
                    return app('json')->fail('积分不足，请重试!');
                }

                 //如果积分足够，修改订单的实际价格
                 $group_order_datas = Db::name('store_group_order')->where('group_order_id',$oid)->find();
                 if(!empty($group_order_datas)){
                     Db::name('store_group_order')->where('group_order_id',$oid)->update(['pay_price'=>$array_fzone_paytype['price']]);
                 }else{
                     return app('json')->fail('找不到订单，请重试!');
                 }

            }

            //b4 现金+京豆支付
            if($array_fzone_paytype['type'] == 'b4'){

                $userdata = Db::name('user')->where('uid',$store_order_data['uid'])->find();
                //查询用户的京豆是否足够
                $jingdou_pri = $userdata['jingdou'] - $array_fzone_paytype['other'];
                if($jingdou_pri < 0){
                    return app('json')->fail('京豆不足，请重试!');
                }

                //如果京豆足够，修改订单的实际价格
                $group_order_datas = Db::name('store_group_order')->where('group_order_id',$oid)->find();
                if(!empty($group_order_datas)){
                    Db::name('store_group_order')->where('group_order_id',$oid)->update(['pay_price'=>$array_fzone_paytype['price']]);
                }else{
                    return app('json')->fail('找不到订单，请重试!');
                }

            }


        }else{
            return app('json')->fail('数据异常，请重新下单,并选择支付方式!');
        }


        try {
            log::info("微信小程序回调");
            Db::name('log')->insert(['data'=>'汇付订单支付pay_wechat_mp-66666666---发起支付']);
            $oid = Request::param('oid','');
            $code = Request::param('code','');
            $type = Request::param('type','');
            $pay_open_id = Request::param('pay_open_id','');
            if($oid == '')
                return app('json')->fail("请检查参数是否正确");
            $groupOrder = $groupOrderRepository->detail_noUid((int)$oid);
            db::name("test_log")->insert(["note"=>json_encode($groupOrder)]);
            if (!$groupOrder)
                return app('json')->fail('订单不存在或已支付');

            $cart = Db::name("store_order")->where(['group_order_id'=>$oid]) -> value("cart_id");//日志记录
            if($cart){
                Db::name("log")->insert(array('data'=>json_encode($cart)));//日志记录
                $cart = explode(",",$cart);
                $cart_id = $cart[0];
                $product = Db::name("store_product")
                    ->alias('sp')
                    ->join('store_cart sc', 'sp.product_id = sc.product_id')
                    ->where(["sc.cart_id"=>$cart_id])
                    ->value('sp.store_name');
            }
            $res = $this -> pay_huifu($type,$code,$groupOrder,$product ?? "幸福宝",env('APP_URL')."/api/hf_notify/pay",'delay');
            Db::name('log')->insert(['data'=>'汇付订单支付--- 返回参数'.json_encode($res)]);
            if (isset($res['id'])) {
                Db::name('store_group_order')->where('group_order_id', $oid)->update(['hf_pay_id' => $res['id'],'pay_wx'=>systemConfig('pay_wx')]);
                if($pay_open_id)
                    Db::name('store_order')->where('group_order_id', $oid)->update(['pay_open_id' => $pay_open_id]);
                return app('json')->success($res);
            }
            return app('json')->fail($res);
//////////////////////////////////////////////首信易/////////////////////////////////////////////////////////

            if($type == 'wx'){
                if(!$code || $code == '' || $code =='undefined')
                    return app('json')->fail("授权失败，code为空");
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env('WECHAT_MP.APPID')."&secret=".env('WECHAT_MP.SECRET')."&js_code=".$code."&grant_type=authorization_code";
                $get = curlGet($url);
                if(!isset($get['openid']) || empty($get['openid'])){
                    return app('json')->fail('授权失败');
                }
                $openid = $get['openid'];
//            $openid = 'ow5su5GbH-RhPFfJv0JUPrMfvPfE';
                $datas['openId'] = $openid;
                $datas['paymentModeCode'] = "MINIAPPS-WEIXIN_PAY-P2P";
            }else{
                $datas['paymentModeCode'] = "ALIPAY-OFFICIAL";
            }


            $datas['requestId'] = $groupOrder['group_order_sn']."_".rand(1000,9999);//订单号
            $datas['orderAmount'] = strval($groupOrder['pay_price'] * 100);//金额。单位分
            $datas['callbackUrl'] = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg4NzQ4NDgzNQ==&scene=124&uin=&key=&devicetype=Windows+10+x64&version=6302019c&lang=zh_CN&a8scene=7&fontgear=2';//同步地址微信公众号

            $cart = Db::name("store_order")->where(['group_order_id'=>$oid]) -> value("cart_id");//日志记录
            Db::name("log")->insert(array('data'=>json_encode($cart)));//日志记录
            $cart = explode(",",$cart);
            $cart_id = $cart[0];
            $product = Db::name("store_product")
                ->alias('sp')
                ->join('store_cart sc', 'sp.product_id = sc.product_id')
                ->where(["sc.cart_id"=>$cart_id])
                ->value('sp.store_name');

            Db::name("log")->insert(array('data'=>Db::name("store_product")->getLastSql()));//日志记录

            $productDetails = array(
                'name' => $product ?? "幸福宝",//商品名称。需传递真实产品名称。
                'quantity' => 1,//商品数量
                'amount' => strval($groupOrder['pay_price'] * 100),//商品单价
            );
            $datas['productDetails'] = [$productDetails];//商品信息

            $datas['clientIp'] = $this -> getRealIP();//客户端外网IP
            $datas['notifyUrl']='/api/notify/pay_5upay';
            $res = ShouxinyiApiRequest::onlinePay($datas);
            $return = array(
                'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
                'status' => $res['status'],
                'scanCode' => $res['scanCode'] ?? '',//Base64二维码
                'appParams' => $res['appParams'] ?? '',//App调用码
                'jsString' => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
                'wechatId' => $res['wechatId'] ?? '',//微信原始ID串
                'tradeNo' => $res['tradeNo'] ?? '',//支付宝生活号调用id
                'token' => $res['token'] ?? '',    //微包支付调用token
            );
            Db::name("log")->insert(array('data'=>'支付回调---'.json_encode($return)));//日志记录

            return app('json')->success($return);

        }catch (Exception $exception){
            log::info("支付异常======");
            log::info($exception);
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail("异常");
        }

    }



    //小程序支付

    public function pay_wechat_mp_copy(StoreGroupOrderRepository $groupOrderRepository){
        try {

            Db::name('log')->insert(['data'=>'汇付订单支付pay_wechat_mp6666666---发起支付']);
            $oid = Request::param('oid','');
            $code = Request::param('code','');
            $type = Request::param('type','');
            $pay_open_id = Request::param('pay_open_id','');
            if($oid == '')
                return app('json')->fail("请检查参数是否正确");
            $groupOrder = $groupOrderRepository->detail_noUid((int)$oid);
            if (!$groupOrder)
                return app('json')->fail('订单不存在或已支付');

            $cart = Db::name("store_order")->where(['group_order_id'=>$oid]) -> value("cart_id");//日志记录
            if($cart){
                Db::name("log")->insert(array('data'=>json_encode($cart)));//日志记录
                $cart = explode(",",$cart);
                $cart_id = $cart[0];
                $product = Db::name("store_product")
                    ->alias('sp')
                    ->join('store_cart sc', 'sp.product_id = sc.product_id')
                    ->where(["sc.cart_id"=>$cart_id])
                    ->value('sp.store_name');
            }
            $res = $this -> pay_huifu($type,$code,$groupOrder,$product ?? "幸福宝",env('APP_URL')."/api/hf_notify/pay",'delay');
            Db::name('log')->insert(['data'=>'汇付订单支付--- 返回参数'.json_encode($res)]);
            if (isset($res['id'])) {
                Db::name('store_group_order')->where('group_order_id', $oid)->update(['hf_pay_id' => $res['id'],'pay_wx'=>systemConfig('pay_wx')]);
                if($pay_open_id)
                    Db::name('store_order')->where('group_order_id', $oid)->update(['pay_open_id' => $pay_open_id]);
                return app('json')->success($res);
            }
            return app('json')->fail($res);
//////////////////////////////////////////////首信易/////////////////////////////////////////////////////////

            if($type == 'wx'){
                if(!$code || $code == '' || $code =='undefined')
                    return app('json')->fail("授权失败，code为空");
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env('WECHAT_MP.APPID')."&secret=".env('WECHAT_MP.SECRET')."&js_code=".$code."&grant_type=authorization_code";
                $get = curlGet($url);
                if(!isset($get['openid']) || empty($get['openid'])){
                    return app('json')->fail('授权失败');
                }
                $openid = $get['openid'];
//            $openid = 'ow5su5GbH-RhPFfJv0JUPrMfvPfE';
                $datas['openId'] = $openid;
                $datas['paymentModeCode'] = "MINIAPPS-WEIXIN_PAY-P2P";
            }else{
                $datas['paymentModeCode'] = "ALIPAY-OFFICIAL";
            }


            $datas['requestId'] = $groupOrder['group_order_sn']."_".rand(1000,9999);//订单号
            $datas['orderAmount'] = strval($groupOrder['pay_price'] * 100);//金额。单位分
            $datas['callbackUrl'] = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg4NzQ4NDgzNQ==&scene=124&uin=&key=&devicetype=Windows+10+x64&version=6302019c&lang=zh_CN&a8scene=7&fontgear=2';//同步地址微信公众号

            $cart = Db::name("store_order")->where(['group_order_id'=>$oid]) -> value("cart_id");//日志记录
            Db::name("log")->insert(array('data'=>json_encode($cart)));//日志记录
            $cart = explode(",",$cart);
            $cart_id = $cart[0];
            $product = Db::name("store_product")
                ->alias('sp')
                ->join('store_cart sc', 'sp.product_id = sc.product_id')
                ->where(["sc.cart_id"=>$cart_id])
                ->value('sp.store_name');

            Db::name("log")->insert(array('data'=>Db::name("store_product")->getLastSql()));//日志记录

            $productDetails = array(
                'name' => $product ?? "幸福宝",//商品名称。需传递真实产品名称。
                'quantity' => 1,//商品数量
                'amount' => strval($groupOrder['pay_price'] * 100),//商品单价
            );
            $datas['productDetails'] = [$productDetails];//商品信息

            $datas['clientIp'] = $this -> getRealIP();//客户端外网IP
            $datas['notifyUrl']='/api/notify/pay_5upay';
            $res = ShouxinyiApiRequest::onlinePay($datas);
            $return = array(
                'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
                'status' => $res['status'],
                'scanCode' => $res['scanCode'] ?? '',//Base64二维码
                'appParams' => $res['appParams'] ?? '',//App调用码
                'jsString' => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
                'wechatId' => $res['wechatId'] ?? '',//微信原始ID串
                'tradeNo' => $res['tradeNo'] ?? '',//支付宝生活号调用id
                'token' => $res['token'] ?? '',    //微包支付调用token
            );

            return app('json')->success($return);

        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail("异常");
        }

    }

    public function pay_demo(StoreGroupOrderRepository $groupOrderRepository){
        Db::name("log")->insert(array('data'=>'测试支付---1'));//日志记录
        $oid = Request::param('oid','');
        $type = Request::param('type','');
        $code = Request::param('code','');
        if($oid == '')
            return app('json')->fail("请检查参数是否正确");
        $groupOrder = $groupOrderRepository->detail_noUid((int)$oid);
        if (!$groupOrder)
            return app('json')->fail('订单不存在或已支付');
        $goods_title=Db::name('merchant')->where('mer_id',$groupOrder['mer_id'])->find();

        $cart = Db::name("store_order")->where(['group_order_id'=>$oid]) -> value("cart_id");//日志记录
        Db::name("log")->insert(array('data'=>'测试支付---购物车---'.json_encode($cart)));//日志记录
        $cart = explode(",",$cart);
        $cart_id = $cart[0];
        $product = Db::name("store_product")
            ->alias('sp')
            ->join('store_cart sc', 'sp.product_id = sc.product_id')
            ->where(["sc.cart_id"=>$cart_id])
            ->value('sp.store_name');

        if($type=='WX'){


            if(!$code || $code == '' || $code =='undefined')
                return app('json')->fail("授权失败，code为空");
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env('WECHAT_MP.APPID')."&secret=".env('WECHAT_MP.SECRET')."&js_code=".$code."&grant_type=authorization_code";
            $get = curlGet($url);
            if(!isset($get['openid']) || empty($get['openid'])){
                return app('json')->fail('授权失败');
            }
            $openid = $get['openid'];


            $member_id=$goods_title['hf_member_id_wx'];
            $app_id='app_0827b960-b932-45ec-b800-4e850091b419';
            $type='2';
            $pay_channel='wx_lite';
            $key='api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';
            $expend=[
                'open_id'=>$openid
            ];
            $params=[
                'order_no'=>$groupOrder['group_order_sn']."_".rand(1000,9999),//订单号
                'app_id'=>$app_id,
                'pay_channel'=>$pay_channel,
                'pay_amt'=>strval($groupOrder['pay_price']),//金额。,
                'goods_title'=>$product ?? "幸福宝",
                'goods_desc'=>$product ?? "幸福宝",
                'device_info'=>[
                    'device_ip'=>app('request')->ip()
//                    'device_ip'=>'115.171.134.68'
                ],

                'expend'=>json_encode($expend),
                'fee_mode'=>'I',
                'notify_url'=>env('APP_URL')."/api/jsapiPay/notify/HF_demo"
            ];
        }elseif($type=='ALI'){
            if(!$code || $code == '' || $code =='undefined')
                return app('json')->fail("授权失败，code为空");
            $res = $this -> getAliUserId($code);
            return app('json')->success($res);
            $buyer_id = Request::param('buyer_id','');
            $member_id=$goods_title['hf_member_id'];
            $app_id='app_44108546-d27a-48ee-88c1-84b45b75114f';
            $type='1';
            $pay_channel='alipay_pub';
            $expend=[
                'buyer_id'=>$buyer_id
            ];
            $key='api_live_b23537ed-64b8-45d6-832e-fb228aa9e0a9';
            $params=[
                'order_no'=>$groupOrder['group_order_sn']."_".rand(1000,9999),//订单号
                'app_id'=>$app_id,
                'pay_channel'=>$pay_channel,
                'pay_amt'=>strval($groupOrder['pay_price']),//金额。,
                'goods_title'=>$product ?? "幸福宝",
                'goods_desc'=>$product ?? "幸福宝",
                'device_info'=>[
                    'device_ip'=>app('request')->ip()
//                    'device_ip'=>'115.171.134.68'
                ],

                'expend'=>json_encode($expend),
                'fee_mode'=>'I',
                'notify_url'=>env('APP_URL')."/api/jsapiPay/notify/HF_demo"
            ];
        }
        $res=$this->Payment_create_traits($params,$type,$key);
        $res['code']='1000';
        $res['return_code']='999';
        if(!empty($res['error_code'])){
            $res['code']='1000';
            $res['return_msg']=$res['error_msg'];
            $res['return_code']=1200;
        }
        return app('json')->success($res);

    }

    public function getAliUserId($code){
        $aop = new AopClient();
        $url = "https://openapi.alipay.com/gateway.do";
//        $app_id="2021002194632049";
//        $privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGxceDFVT6VTYClinyAdY4PxE6MadNYLZ3sbLOLV14e39kuu1lkKDBZ/KPRNruPlSPGdiRVe+L8v4rsVk6bthsS/vMk5aH1wQyt58/HvHmZ5QVo3U5UD7cgqqefTcRJjKhjjM1rU/OrOkOqyssaLRukW3jeKRlBccUgtaGsXXrbMxWYpzl1OMDhKRRUVxu3LTfqlMpHghOasQrgyD92q9wlUN7U6hBYzGUocO/N3sz97PZwptwWAW0r3CFdlLCpgnMr+xb/Zh8td1OKGl3wEghiGavgDDlc2+w/xtk1SZ3pJbnGAU+D+oyJ6r76po6vkyGIlLrKp/zQ50az7fObzgNAgMBAAECggEBAK60szERlMkaEAih92gQGTsCo5+keMnX0UjO1LvGv7rfwQ7GBVYZklGrjVRDTrHL8wJ70w+amptFDgVVMXncZzh4aG5c4heu8q+pGLyf9DlwnIWQT736O+YQqun2YGogSqwYkgYBuH2NGKKd66pytPPhutYN+WAZfesXPHrSizRJtZMfuZvvGzm6ZJLZ1LmhvkOuLrX4xrJGRs1nAwZOmOfi4MY5VASblfPj59fUim9hErocNaX4uiMVwmhQl2QuOM/EbTd1UkW+dkV/gyQMOFzpcfN+SEi+hdLN+JiR9TVEcwity6ihOG5+3X33GKzfY4WFxeHHUaqA0SQWSkKofMECgYEA5OF5Imtq8/6JjWJ0jvYCpUnj9742McGJZTWBoTn9Hp0d3bwyE3YbH8pBVJyvzlfPKB9TUjE2FzVZvQtxEu+ZxToccp/LPqlgITWNHCmEtzAgXW7ww2PafgDZJ2QRSyjLUeRIWSAkeilj64XMCEC/bEs/nb5nmUb2gnsNTvvpMLUCgYEA3lMMtaIZH1fMI4XMNaPFzeRiKc0FIcLEem/efnPetPuOCujIWQJ/x9cCDCcfqO59I1FXQuiC/E1dFvme2qs/H7h2bFu8RG0M/ZQWd9twg31Sh+R7gCQakFERag8HXc4AWfBGXCvMu1SmSovU49KecSLxYGOAUdp77j1GxtLiePkCgYAQjc45ExPVOd+w/iH4BQsD8Wgvju5Ugu7xBwGtK4iHIk36r5XfmnczwWkgOYTto6Qz/rAEDdMfspge+CjhebrhbOaJ08zbZ1ywijL+inIy3aQ5ncCEIUC4RE9wbehiSz0JWz1wVMbOnxe+/RpYrnYp2vdq7U6I430IyuWXhNjE0QKBgEtJUmd7oghEIgPxfiq37/b+HOPM4q0BGKnhkjW+JS+idAJru9SwjPbub2oQIZ+CS2wXUnZ86EZqKFjsZQflr7WdMLUXB5UgXKLOcCFcdSiB2t3b2JqXH0u5uCzzM+pnJSVPwXPa/TR+wOVDnu8bVr43OAgNCdouI4OUyo/vv/N5AoGATJaIvpsZ9v1zmhbtJbgPBM9dhD2PIp2ufZ7yvhGGzA02FqAbyAeVsI2d+W+uA6jJ1X87x27pQv//mFoFXStxX3/bhdgTWbUYEWobAhw1jBS1rMQfLuBGGI/LsHGhzau3U+59erC5sYhGgZKSdXDyjOduWQlPWAv6ufkNZ+I3FCU=";
//        $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUb+0sJSNXjWiG0VJIPzn55+18af/fubYMpRLlreu34ewMgLx1zpCNpB3wrA+dylfWPMAm8PzvKnakByB+VJ/LMNhWHmF8Qkdo4astAikjlI4TMQCK/G384NzrtjHR4DGCDM5CMVt1xw5noF7kNBMYIvgDfhMCYmygdlIjuVdIlVEoQKOsT0RaNMleES0aZvbjvBGkGM0dsetqUExSjid9BF1NAO2ET+J3XMxCtMgCUVmFUvxsCKe6Rapa1/Lk3rzIeG6CRpoabuYfPM9E+3y3f3luSOMXLfH9lOSW1RA8qrF+Ms1RZv8gmzUnbyrPLmmZPmmN/Qs6DGzDVg73fpSwIDAQAB';
        $app_id = '2021001197698727';
        $privateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCf1r70C/D+XWtDuuV07/41UnEHRyas0Y92TRS5eI+S4v4r8lDY8aLcWM6ssE/dVaKrGulEqG3jv12WLRP7ZDiHSzlcgrHZLm9sub+rY9r7dPMn69xaVg/wMh7SQ5yduHXr1WtjIlnb4ng29ZoQjzHy9kgQ0i92Vtk1PRsQrlUWeYGXjftBShdHMraP7km8tvA5S+tTalczzkDm5i2lXHeycAkIiTJ1dqebA74ZCe47kyG0AtNbRBOMOB0zOFcHX865Faa1hPPlug98o6D6oyR4M/rkehqtf1Y1AIuBGIDSey4BmOvIqOiu/WbLTSx7TS9OxXBoP3SFMKiVKMqR7yH5AgMBAAECggEAGf3QpVy/vo0wYR4mK+LOwpr6WEWgq1+UZZdZNGO/bRJOZJUNwolgg1ZJnVk6U3KWdh51Kj39SJiYvk/sPOfqLU31MO7rvrZHVjXKTjN5q4Qz+hzngyUViGiODIEEGb2iJ0xYHxG57QChrcY4XFL8u1aDF4EmSKcMwRSDry26FmI/uEfjuF30kl11r24CtifE/NkbnqeWzOvoXteWxb1DbUsiqjRydnqUme5BPNoFhp5maYMZVUyg+I92G39FlQ1xQSJVq68TpL7ePOf8JBrGLqHSqNAiAfFwuvUWpELBstc4GPvQeWAw8142dsQGWz2wHZjUZW9CEyfrPDXZUz2wkQKBgQDdzpWkLNSjqhzdxcWw6z4bTguRVc594s5wbMftrKEybVbutVYjVKYi3rzSRRMcbr7vkkCj7FkQsmjY5l/wrv/CBrN/OPhQ7dDGTdEjtU2pnhDOvLaXIvcinz9YeAVHGePXXyx43wo5LysCqhAIxA5lS+LOuZZxQJzYVOv18uI6NQKBgQC4eqT8DiYb81Ke5l4Q5irOOd9Q/PqtCDJAyOkZVjMKBNOJauHZdx+rFgB2GEB2EdI5rUPDLn4XBkmeHlqk15HjLGA2kl4AojB2eCfD9voYHOTOEiAGpm9AL9Ws8ALFg27W1XKu/Ih1IxHifCAeR86lnIejJCizQ/P2lilWBj9hNQKBgQC8E9cZbhYkbTOq7W9TNDXmi0gNxXehkPdBp0vkAhRxoPss0ECpFrcFLF9p4L5yxolKtXXwSZHAMbfr63SArrMZv/rmLtWIMg9sh0GGiM7Au9I+qxAcmb568hORnbvD7XUgA4i/OUj+8jsDOFb+R9h5Fl7MsduaTpJwcZnfZENl3QKBgEKMq9vp1sGag6GjBSgfgC2pHvB+cofdPxOz5rMnL35bw1v9XMAwgxIa+8uecBKn1yjLYniU2xO/Ruttk9GHmq9TINpO7u5XlBgIvH+rJwlv0vKsAzWi8Ns85l5erwFFqsSBd7+8hhWLszX7BTMnQFrqHtwxfSU+TFIWVY8c7dxJAoGAaXqh1VejqHCPLfQ7Dthx0lEkzXOdUaPVh+LW7F5RPCBBnhsaFGlKVOQYHm6oFtH9qLgZBT1IkA7HTGX9YYTX8jl1zvgUNvxFOprPyYCo5O7vsa7KfkIzZt2FnycI83NAKYDTpA8q28YI81rcHcRLRbmun2drEPyj9dG79uy6Xg8=';
        $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';

        $aop->gatewayUrl = $url;
        $aop->appId = $app_id;
        $aop->rsaPrivateKey = $privateKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='GBK';
        $aop->format='json';
        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
//        $request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return $result;
        } else {
            return false;
        }
    }

    /**
     * @remarks 小程序支付年费
     * @author Tang
     * @created 2021/8/27 9:18
     */
    public function pay_annual_cost(){
        try {
            $oid = Request::param('oid','');
            $code = Request::param('code','');
            $payType = Request::param('type','');
            $appid = Request::param('appid','');
            if($oid == '')
                return app('json')->fail("请检查参数是否正确");
//            $groupOrder = $groupOrderRepository->detail_noUid((int)$oid);
            $groupOrder=Db::name('merchant_annual_cost_order')->where('id',$oid)->where('status',0)->find();
            if (!$groupOrder)
                return app('json')->fail('订单不存在或已支付');
            Db::name('log')->insert(['data'=>'汇付商户支付---groupOrder'.json_encode($groupOrder)]);

            $res = $this -> pay_huifu($payType,$code,$groupOrder,'商户',env('APP_URL')."/api/hf_notify/pay_annual",null,$appid);
//            Db::name('log')->insert(['data'=>'汇付商户支付---'.json_encode($res)]);
            Db::name('merchant_annual_cost_order')->where('id',$oid) ->update(['hf_pay_id'=>$res['id']]);
            return app('json')->success($res);



///////////////////////////////年费/////////////////////////////////////////////
            if($payType == 'wx'){
                if(!$code || $code == '' || $code =='undefined')
                    return app('json')->fail("授权失败，code为空");
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env('WECHAT_MP.APPID')."&secret=".env('WECHAT_MP.SECRET')."&js_code=".$code."&grant_type=authorization_code";
                $get = curlGet($url);
                if(!isset($get['openid']) || empty($get['openid'])){
                    return app('json')->fail('授权失败');
                }
                $openid = $get['openid'];
//            $openid = 'ow5su5GbH-RhPFfJv0JUPrMfvPfE';
                $datas['openId'] = $openid;
                $datas['paymentModeCode'] = "MINIAPPS-WEIXIN_PAY-P2P";
                Db::name('merchant_annual_cost_order')->where('id',$oid)->update(['pay_type'=>'wx']);
            }else{
                Db::name('merchant_annual_cost_order')->where('id',$oid)->update(['pay_type'=>'al']);
                $datas['paymentModeCode'] = "ALIPAY-OFFICIAL";
            }


            $datas['requestId'] = $groupOrder['order_no']."_".rand(1000,9999);//订单号
            $datas['splitMark'] = 'NOT_DO_SPLIT';//不分账
            $datas['orderAmount'] = strval($groupOrder['pay_price'] * 100);//金额。单位分
            $datas['callbackUrl'] = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg4NzQ4NDgzNQ==&scene=124&uin=&key=&devicetype=Windows+10+x64&version=6302019c&lang=zh_CN&a8scene=7&fontgear=2';//同步地址微信公众号

            $cart = Db::name('merchant_annual_cost_order')->where('id',$oid)->where('status',0)-> value("id");//日志记录
            Db::name("log")->insert(array('data'=>json_encode($cart)));//日志记录
            $product = '商家年费';

            Db::name("log")->insert(array('data'=>Db::name("store_product")->getLastSql()));//日志记录

            $productDetails = array(
                'name' => $product ?? "幸福宝年费",//商品名称。需传递真实产品名称。
                'quantity' => 1,//商品数量
                'amount' => strval($groupOrder['pay_price'] * 100),//商品单价
            );
            $datas['productDetails'] = [$productDetails];//商品信息

            $datas['clientIp'] = $this -> getRealIP();//客户端外网IP
            $datas['notifyUrl']='/api/notify/pay_annual';
            $res = ShouxinyiApiRequest::onlinePay($datas);
            $return = array(
                'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
                'status' => $res['status'],
                'scanCode' => $res['scanCode'] ?? '',//Base64二维码
                'appParams' => $res['appParams'] ?? '',//App调用码
                'jsString' => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
                'wechatId' => $res['wechatId'] ?? '',//微信原始ID串
                'tradeNo' => $res['tradeNo'] ?? '',//支付宝生活号调用id
                'token' => $res['token'] ?? '',    //微包支付调用token
            );

            return app('json')->success($return);

        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail("异常");
        }

    }
    /**
     * @remarks 小程序支付激活码
     * @author Tang
     * @created 2021/8/27 9:18
     */
    public function pay_activation_code(){
        try {

            $oid = Request::param('oid','');
            $code = Request::param('code','');
            $payType = Request::param('type','');
            if($oid == '')
                return app('json')->fail("请检查参数是否正确");
//            $groupOrder = $groupOrderRepository->detail_noUid((int)$oid);
            $groupOrder=Db::name('activation_code_order')->where('id',$oid)->where('status',0)->find();
//            $group_type=Db::name('activation_code_order')->where('id',$oid)->where('status',0)->update(['pay_type'=>$type]);
            if (!$groupOrder)
                return app('json')->fail('订单不存在或已支付');

            $res = $this -> pay_huifu($payType,$code,$groupOrder,"商户激活码",env('APP_URL')."/api/hf_notify/pay_activation",'delay');
            Db::name('log')->insert(['data'=>'汇付激活码支付---'.json_encode($res)]);
            Db::name('activation_code_order')->where('group_order_id',$oid) ->update(['hf_pay_id'=>$res['id']]);
            return app('json')->success($res);

//////////////////////////////////////首信易/////////////////////////////////////////////

            if($payType == 'wx'){
                Db::name('log')->insert(['data'=>'code---'.$code]);
                if(!$code || $code == '' || $code =='undefined')
                    return app('json')->fail("授权失败，code为空");
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env('WECHAT_MP.APPID')."&secret=".env('WECHAT_MP.SECRET')."&js_code=".$code."&grant_type=authorization_code";
                $get = curlGet($url);
                Db::name('log')->insert(['data'=>'open_id---'.json_encode($get)]);
                if(!isset($get['openid']) || empty($get['openid'])){
                    return app('json')->fail('授权失败');
                }
                $openid = $get['openid'];
//            $openid = 'ow5su5GbH-RhPFfJv0JUPrMfvPfE';
                $datas['openId'] = $openid;
                $datas['paymentModeCode'] = "MINIAPPS-WEIXIN_PAY-P2P";
                Db::name('activation_code_order')->where('id',$oid)->update(['pay_type'=>'al']);
            }else{
                Db::name('activation_code_order')->where('id',$oid)->update(['pay_type'=>'al']);
                $datas['paymentModeCode'] = "ALIPAY-OFFICIAL";
            }


            $datas['requestId'] = $groupOrder['order_no']."_".rand(1000,9999);//订单号
            $datas['orderAmount'] = strval($groupOrder['pay_price'] * 100);//金额。单位分
            $datas['callbackUrl'] = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg4NzQ4NDgzNQ==&scene=124&uin=&key=&devicetype=Windows+10+x64&version=6302019c&lang=zh_CN&a8scene=7&fontgear=2';//同步地址微信公众号

            $cart = Db::name('activation_code_order')->where('id',$oid)->where('status',0)-> value("id");//日志记录
            Db::name("log")->insert(array('data'=>json_encode($cart)));//日志记录
            $product = '商家激活码';

            Db::name("log")->insert(array('data'=>Db::name("store_product")->getLastSql()));//日志记录

            $productDetails = array(
                'name' => $product ?? "激活码",//商品名称。需传递真实产品名称。
                'quantity' => 1,//商品数量
                'amount' => strval($groupOrder['pay_price'] * 100),//商品单价
            );
            $datas['productDetails'] = [$productDetails];//商品信息

            $datas['clientIp'] = $this -> getRealIP();//客户端外网IP
            $datas['notifyUrl']='/api/notify/pay_activation';
            Db::name('log')->insert(['data'=>'请求数据--'.json_encode($datas)]);
            $res = ShouxinyiApiRequest::onlinePay($datas);
            $return = array(
                'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
                'status' => $res['status'],
                'scanCode' => $res['scanCode'] ?? '',//Base64二维码
                'appParams' => $res['appParams'] ?? '',//App调用码
                'jsString' => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
                'wechatId' => $res['wechatId'] ?? '',//微信原始ID串
                'tradeNo' => $res['tradeNo'] ?? '',//支付宝生活号调用id
                'token' => $res['token'] ?? '',    //微包支付调用token
            );

            return app('json')->success($return);

        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail("异常");
        }

    }
    /**
     * @remarks 小程序支付渠道商
     * @author Tang
     * @created 2021/8/27 9:18
     */
    public function pay_channel(){
        try {

            $oid = Request::param('oid','');
            $code = Request::param('code','');
            $payType = Request::param('type','');
            if($oid == '')
                return app('json')->fail("请检查参数是否正确");
//            $groupOrder = $groupOrderRepository->detail_noUid((int)$oid);
            $groupOrder=Db::name('channel_order')->where('id',$oid)->where('status',0)->find();
//            $group_type=Db::name('channel_order')->where('id',$oid)->where('status',0)->update(['pay_type'=>$type]);
            if (!$groupOrder)
                return app('json')->fail('订单不存在或已支付');

            $res = $this -> pay_huifu($payType,$code,$groupOrder,'渠道商',env('APP_URL')."/api/hf_notify/pay_channel");
            Db::name('log')->insert(['data'=>'汇付渠道商支付---'.json_encode($res)]);
            Db::name('channel_order')->where('id',$oid) ->update(['hf_pay_id'=>$res['id']]);
            return app('json')->success($res);

/////////////////////////////首信易/////////////////////////////////////////////////
            if($payType == 'wx'){
                Db::name('log')->insert(['data'=>'code---'.$code]);
                if(!$code || $code == '' || $code =='undefined')
                    return app('json')->fail("授权失败，code为空");
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".env('WECHAT_MP.APPID')."&secret=".env('WECHAT_MP.SECRET')."&js_code=".$code."&grant_type=authorization_code";
                $get = curlGet($url);
                Db::name('log')->insert(['data'=>'open_id---'.json_encode($get)]);
                if(!isset($get['openid']) || empty($get['openid'])){
                    return app('json')->fail('授权失败');
                }
                $openid = $get['openid'];
//            $openid = 'ow5su5GbH-RhPFfJv0JUPrMfvPfE';
                $datas['openId'] = $openid;
                $datas['paymentModeCode'] = "MINIAPPS-WEIXIN_PAY-P2P";
                Db::name('channel_order')->where('id',$oid)->update(['pay_type'=>'wx']);
            }else{
                Db::name('channel_order')->where('id',$oid)->update(['pay_type'=>'al']);
                $datas['paymentModeCode'] = "ALIPAY-OFFICIAL";
            }


            $datas['requestId'] = $groupOrder['order_no']."_".rand(1000,9999);//订单号
            $datas['orderAmount'] = strval($groupOrder['pay_price'] * 100);//金额。单位分
            $datas['callbackUrl'] = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg4NzQ4NDgzNQ==&scene=124&uin=&key=&devicetype=Windows+10+x64&version=6302019c&lang=zh_CN&a8scene=7&fontgear=2';//同步地址微信公众号
            $product = '渠道商';

            Db::name("log")->insert(array('data'=>Db::name("store_product")->getLastSql()));//日志记录

            $productDetails = array(
                'name' => $product ?? "渠道商",//商品名称。需传递真实产品名称。
                'quantity' => 1,//商品数量
                'amount' => strval($groupOrder['pay_price'] * 100),//商品单价
            );
            $datas['productDetails'] = [$productDetails];//商品信息

            $datas['clientIp'] = $this -> getRealIP();//客户端外网IP
            $datas['notifyUrl']='/api/notify/pay_channel';
            Db::name('log')->insert(['data'=>'请求数据--'.json_encode($datas)]);
            $res = ShouxinyiApiRequest::onlinePay($datas);
            $return = array(
                'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
                'status' => $res['status'],
                'scanCode' => $res['scanCode'] ?? '',//Base64二维码
                'appParams' => $res['appParams'] ?? '',//App调用码
                'jsString' => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
                'wechatId' => $res['wechatId'] ?? '',//微信原始ID串
                'tradeNo' => $res['tradeNo'] ?? '',//支付宝生活号调用id
                'token' => $res['token'] ?? '',    //微包支付调用token
            );

            return app('json')->success($return);

        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
            return app('json')->fail("异常");
        }

    }


    //退款
    public function refund(){
        $data['requestId'] = ShouxinyiApiRequest::getOrderNumber('refund');    //订单号
        $data['orderId'] = '4bd333679fc94d61b88b7e758a71e8bc';//交易订单的流水号
        $data['isCollect'] = '1';
        $data['amount'] = 7900;//退款金额
        $data['remark'] = '备注';

        $refundCollectDetail = array(
            'collectAccType' => 'WAIT_ACC',//归集类型
            'collectAmount' => 7900,//归集金额
        );
        $data['refundCollectDetail'] = [$refundCollectDetail];//商品信息


        $res = ShouxinyiApiRequest::refund($data);
        return app('json')->success($res);
    }



    //客户端IP
    public function getRealIP()
    {
        $forwarded = request()->header("x-forwarded-for");
        if ($forwarded) {
            $ip = explode(',', $forwarded)[0];
        } else {
            $ip = request()->ip();
        }
        return $ip;
    }

    //修改首信易商户银行信息
    public function save_bank(){

        $data['merchantId'] = '899104033';
        $data['subMerchantId'] = '897401634';
        $data['requestId'] = ShouxinyiApiRequest::getOrderNumber('modifyBankCard');    //订单号;
        $data['bankCode'] = 'ICBC';
        $data['bankBranchName'] = '中国工商银行股份有限公司北京万年花城支行';
        $data['bankCardNo'] = '0200244909200054497';
        $data['cityCode'] = '110100';
        $data['provinceCode'] = '110000';
        $save = ShouxinyiApiRequest::modifyBankCard($data);
        dump($save);
    }
    //佣金处理
    public function activation_yj($order_no)
    {
        $num=0.3;
        $order_data=Db::name('activation_code_order')->where('order_no',$order_no)->where('status',1)->find();
//        $order_data['pay_price']=6000;//测试养老金佣金改为6000
        if(empty($order_data)){
            return $num;
        }
        $eb_data=Db::name('entropy_barter_user_276')->where('uid',$order_data['uid'])->find();
        $jifen=$order_data['pay_price'];
        $uid=$order_data['uid'];
        $bill=[
            'from_id'=>'0',
            'number'=>$jifen,
            'to_id'=>$eb_data['eb_id'],
            'type'=>'1',
            'order_no'=>$order_no,
            'remarks'=>'购买激活码得积分',
            'pm'=>1,
            'status'=>2,
            'on_line'=>1,
            'mer_id'=>276
        ];
        $this->eb_user_bill($bill);
        Db::name('entropy_barter_user_276')->where('eb_id',$eb_data['eb_id'])->inc('integral',$jifen)->update();
        $mer_id = 276;
        $number = bcmul($order_data['pay_price'],'0.01',2);//养老金
        $data=[
            'link_id' => $order_data['id'],
            "uid"=>$uid,
            "pm"=>1,
            "title"=>'激活码养老金',
            "category"=>"now_money",
            "type"=>"commission",
            "number"=>$number,
            "balance"=>0,
            "mark"=>'购买激活码获得'.$number.'元养老金',
            "status"=>1,
            "commission_type"=>5,
            "order_sn"=>$order_data['order_no'],
            "mer_id"=>$mer_id,
            "source"=>0,
            "type_shop"=>0,
            'gzc'=>0
        ];
        Db::name("user_bill")->insert($data);
        Db::name("user")->where("uid",$uid)->inc('annuity', $number) ->update();
        Db::name("user")->where("uid",$uid)->inc('annuity_num', 1) ->update();
        //公证处入账
//        $certification = UserCertification::getInstance()->where('uid', $order_data['uid'])->find();
//        if($certification) {
//            $user_data = Db::name('user')->where('uid', $uid)->find();
//            $user_data['real_name']=Db::name('user_certification')->where('status',1)->where('uid',$user_data['uid'])->value('user_name');
//            $user_data['account']=Db::name('user_certification')->where('status',1)->where('uid',$user_data['uid'])->value('mobile');
//            $online = ['uid' => $uid, 'pay_type' => $order_data['pay_type'] == 'alpay' ? 4 : 1, 'order_sn' => $order_data['order_no'], 'order_id' => $order_data['id']];
//            $certification = ['user_name' => $user_data['real_name'], 'mobile' => $user_data['account'], 'user_card' => $user_data['card_id']];
//            $this->GZC($online, $certification, $number);
//        }
        //上级数据
        $top_eb_data=Db::name('entropy_barter_user_276')->where('eb_id',$eb_data['top_eb_id'])->find();
        $top_eb_id=$top_eb_data['eb_id']??0;
        //上级上级数据
        $top_top_eb_data=Db::name('entropy_barter_user_276')->where('eb_id',$top_eb_data['top_eb_id'])->find();
        $top_top_eb_id=$top_top_eb_data['eb_id']??0;
        //一级奖励
        $one_yj=bcmul($order_data['pay_price'],'0.1',2);

        if($top_eb_id==0){//为0 不执行直接返回
            return $num;
        }
        if($top_eb_data['type']!=1) {
            $bill = [
                'from_id' => '0',
                'number' => $one_yj,
                'to_id' => $top_eb_id,
                'type' => '2',
                'order_no' => $order_no,
                'remarks' => '易熵易物直推佣金',
                'pm' => 1,
                'status' => 2,
                'on_line' => 1,
                'mer_id' => 276
            ];
            $this->eb_user_bill($bill);
            Db::name('entropy_barter_user_276')->where('eb_id', $top_eb_id)->inc('wallet', $one_yj)->update();
            $num=$num - 0.1;
        }
        if($top_top_eb_id==0){//为0 不执行直接返回
            return $num;
        }
        if($top_top_eb_data['type']!=1) {
            if($top_top_eb_data['type']==2){
                $bl=0.15;
            }elseif ($top_top_eb_data['type']==3){
                $bl=0.20;
            }
            //二级奖励
            $two_yj=bcmul($order_data['pay_price'],$bl,2);
            $bill = [
                'from_id' => '0',
                'number' => $two_yj,
                'to_id' => $top_top_eb_id,
                'type' => '1',
                'order_no' => $order_no,
                'remarks' => '易熵易物间推佣金',
                'pm' => 1,
                'status' => 2,
                'on_line' => 1,
                'mer_id' => 276
            ];
            $this->eb_user_bill($bill);
            Db::name('entropy_barter_user_276')->where('eb_id', $top_top_eb_id)->inc('wallet', $two_yj)->update();
            $num = $num-$bl;
        }

        //公证处入账


        return $num;
    }

    public function GZC($online,$certification,$pension)
    {
        $OrderMerchantRepository = app()->make(OrderMerchantRepository::class);
        $orderId = $OrderMerchantRepository->getNewOrderId('IN10');
        $OrderGzcRepository = app()->make(OrderGzcRepository::class);
        $create = [
            'uid' => $online['uid'],
            'platform_no' => $orderId,
            'account_type' => $online['pay_type'] == 1 ? 3 : 2,
            'user_name' => $certification['user_name'],
            'mobile' => $certification['mobile'],
            'user_card' => $certification['user_card'],
            'pension' => $pension,
            'order_type' => 2,
            'out_trade_no' => $online['order_sn']
        ];
        $OrderGzcRepository->create($create);
    }
    //账单记录
    public function eb_user_bill($bill)
    {
        $insert=[
            'from_id'=>$bill['from_id'],
            'number'=>$bill['number'],
            'to_id'=>$bill['to_id'],
            'type'=>$bill['type'],
            'order_no'=>$bill['order_no'],
            'remarks'=>$bill['remarks'],
            'pm'=>$bill['pm'],
            'ctime'=>time(),
            'on_line'=>$bill['on_line'],
            'status'=>$bill['status'],
            'pm2_msg'=>$bill['pm2_msg']??'',
            'mer_id'=>$bill['mer_id'],
            'commission_scale'=>$bill['commission_scale']??0,
            'commission_type'=>$bill['commission_type']??0,
            'to_user_type'=>$bill['to_user_type']??'',
            'to_user_type_1'=>$bill['to_user_type_1']??'',

        ];
        Db::name('log')->insert(['data'=>json_encode($insert)]);
        Db::name('entropy_barter_bill')->insert($insert);


    }
    //分账
    public function activation_spilet($order_no,$num)
    {
        Db::name('log')->insert(['data'=>'分账比例'.$num]);
        $bili=0.33;
        $bili=bcadd($bili,$num,2);
        Db::name('log')->insert(['data'=>'分账比例'.$bili]);
        $order_data=Db::name('activation_code_order')->where('order_no',$order_no)->where('status',1)->find();
        if(empty($order_data)){
            return '';
        }
        $goods_title=Db::name('merchant')->where('mer_id',276)->find();

        $mer_price=bcmul($order_data['pay_price'],$bili,2);
        $yongjin=bcmul($order_data['pay_price'],'0.37',2);
        $shouxufei=bcmul($order_data['pay_price'],'0.006',3);
        $yongjin=bcadd($yongjin,round($shouxufei,2));
        $mer_price=bcsub($mer_price,round($shouxufei,2),2);

        $payment_id = ShouxinyiApiRequest::getOrderNumber('split');

        $div_members=[
            [
                'member_id'=>$goods_title['hf_member_id_wx'],
                'amount'=>$mer_price,
                'fee_flag'=>'Y'
            ],
            [
                'member_id'=>0,
                'amount'=>$yongjin,
                'fee_flag'=>'N'
            ]
        ];
        $params = [
            'payment_id'=>$order_data['hf_pay_id'],
            'order_no'=>$payment_id,
            'confirm_amt' => $order_data['pay_price'],
            'div_members'=>json_encode($div_members)
        ];

        $res = $this -> payment_confirm_create_traits($params);
        Db::name("log")->insert(array('data'=>'汇付延时分账-----'.json_encode($res)));//日志记录

        ////////////////////////////////首信易///////////////////////////////////////////
        $sxy_submerchant_id=Db::name('Merchant')->where('mer_id',276)->value('sxy_submerchant_id');
        $splitDetails = array(
            array(
                'subSplitRequestId' => $data['requestId'] . '_1',
                'splitAccType' => 'MERCHANT_ACC',
                'splitAccId' => $sxy_submerchant_id,
                'splitAmount' => $mer_price
            ),
            array(
                'subSplitRequestId' => $data['requestId'] . '_2',
                'splitAccType' => 'MERCHANT_ACC',
                'splitAccId' => '895961180',
                'splitAmount' => $yongjin
            )
        );
        $insertData=[
            [
                'mid' => $order['mer_id']??0,
                'requestId' => $data['requestId'],
                'group_order_id' => $data['orderId'],
                'subSplitRequestId' => $data['requestId'].'_1',
                'splitAccId' => $sxy_submerchant_id,
                'splitAmount' => $splitDetails[0]['splitAmount'],
                'totalSplitAmount' => $data['totalSplitAmount'],
                'status' => 0
            ],
            [
                'mid' => $order['mer_id']??0,
                'requestId' => $data['requestId'],
                'group_order_id' => $data['orderId'],
                'subSplitRequestId' => $data['requestId'].'_2',
                'splitAccId' => 895961180,
                'splitAmount' => $splitDetails[1]['splitAmount'],
                'totalSplitAmount' => $data['totalSplitAmount'],
                'status' => 0
            ]
        ];
        $data['splitDetails'] = $splitDetails;

        Db::name("store_split_order") -> insertAll($insertData);

        return ShouxinyiApiRequest::split($data);
    }
    //渠道商分佣
    public function channel_fenyong($order_sn)
    {
        try{
            $order_data=Db::name('channel_order')->where('order_no',$order_sn)->find();//订单数据
            $channelrecommend=Db::name('channel_user')->where('uid',$order_data['uid'])->find();
            //渠道商表中查无此人
            if(!$channelrecommend){
                return false;
            }
            $user_data=Db::name('user')->where('uid',$order_data['uid'])->find();//渠道商用户信息
            $top_user_data=Db::name('user')->where('uid',$user_data['spread_uid'])->find();//用户的推荐人（邀请注册的人）
            $top_uid = $top_user_data['uid'];
            if($channelrecommend['recommend_uid'] != '' || $channelrecommend['recommend_uid'] != 0){
                $top_uid=$channelrecommend['recommend_uid'];
            }
            //渠道商本人给养老金10%
            $ylj=bcmul($order_data['pay_price'],'0.1',5);//10%的养老金
            $ylj=round($ylj,2);

            $top_yongjin = 0;//直接上级佣金
            $top_top_yongjin = 0;//间接上级佣金

            $title='养老金';
            $mark = '成为渠道商获得' . $ylj . '养老金';
            $billData=[
                'uid'=>$order_data['uid'],
                'link_id'=>$order_data['id'],
                'pm'=>1,
                'title'=>$title,
                'category'=>'now_money',
                'type'=>'commission',
                'number'=>$ylj,
                'balance'=>0,
                'mark'=>$mark,
                'create_time'=>date("Y-m-d H:i:s",time()),
                'status'=>1,
                'order_sn'=>$order_sn,
                'type_shop'=>0,
                'commission_type'=>5,
                'order_type'=>1,
                'gzc'=>0
            ];

            Db::name('user_bill')->insert($billData);
            Db::name("user")->where("uid",$order_data['uid'])->inc('annuity', $ylj) ->update();
            Db::name("user")->where("uid",$order_data['uid'])->inc('annuity_num', 1) ->update();
            //如果存在上级
            if($top_uid > 0){
                //上级身份是否大仓会员
                $is_da_cang_vip=Db::name('da_cang_user')->where('status',1)->where('uid',$top_uid)->find();
                //上级身份是否商户
                $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_uid)->find();
                $is_shanghu2=Db::name('merchant')->where('uid',$top_uid)->find();
                $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_uid)->find();
                //渠道商
                $is_channel = Db::name('channel_user') -> where('uid',$top_uid)->where('status',1)->find();

                Db::name('log')->insert(['data'=>'会员状态'.json_encode($is_da_cang_vip)]);
                Db::name('log')->insert(['data'=>'商户支付订单'.json_encode($is_shanghu1)]);
                Db::name('log')->insert(['data'=>'商户'.json_encode($is_shanghu2)]);
                Db::name('log')->insert(['data'=>'商户入驻表'.json_encode($is_shanghu3)]);
                Db::name('log')->insert(['data'=>'渠道商'.json_encode($is_channel)]);

                //如果是大仓会员
                if($is_da_cang_vip){
                    //如果上级是金卡会员 20%佣金
                    if($is_da_cang_vip['type'] == 1){
                        $top_yongjin = bcmul($order_data['pay_price'], 0.12, 5);
                    }elseif ($is_da_cang_vip['type'] == 2){
                        //如果上级是银卡会员 15%佣金
                        $top_yongjin = bcmul($order_data['pay_price'], 0.1, 5);
                    }
                }
                //如果是商户 22%佣金
                if($is_shanghu1||$is_shanghu2||$is_shanghu3){
                    $top_yongjin = bcmul($order_data['pay_price'], 0.15, 5);
                }
                //如果是渠道商 20% 佣金
                if($is_channel){
                    $top_yongjin = bcmul($order_data['pay_price'], 0.20, 5);
                }

                $top_yongjin=round($top_yongjin,2);
                if($top_yongjin > 0){
                    $title='佣金';
                    $mark = '邀请渠道商获得' . $top_yongjin . '招募奖励';
                    $billData=[
                        'uid'=>$top_uid,
                        'link_id'=>$order_data['id'],
                        'pm'=>1,
                        'title'=>$title,
                        'category'=>'now_money',
                        'type'=>'commission',
                        'number'=>$top_yongjin,
                        'balance'=>0,
                        'mark'=>$mark,
                        'create_time'=>date("Y-m-d H:i:s",time()),
                        'status'=>1,
                        'order_sn'=>$order_sn,
                        'type_shop'=>0,
                        'commission_type'=>9,
                        'order_type'=>1
                    ];
                    Db::name('user_bill')->insert($billData);
                    Db::name('user')->where('uid',$top_uid)->inc('brokerage_price',$top_yongjin)->update();
                }
            }
            //间接上级
            $top_top_uid =Db::name('user')->where('uid',$top_uid)->value('spread_uid');//推荐人的推荐人（邀请注册的人）
            $top_channelrecommend=Db::name('channel_user')->where('uid',$top_uid)->find();//推荐人的推荐人（渠道商推荐人）
            if($top_channelrecommend && ($top_channelrecommend['recommend_uid'] != '' || $top_channelrecommend['recommend_uid'] != 0)){
                $top_top_uid = $top_channelrecommend['recommend_uid'];
            }
            if($top_top_uid > 0){
                //商户
                $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_top_uid)->find();
                $is_shanghu2=Db::name('merchant')->where('uid',$top_top_uid)->find();
                $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_top_uid)->find();
                //大仓会员
                $is_da_cang_vip=Db::name('da_cang_user')->where('uid',$top_top_uid)->where('status',1)->find();
                //渠道商
                $is_channel = Db::name('channel_user') -> where('uid',$top_top_uid)->where('status',1)->find();

                Db::name('log')->insert(['data'=>'会员状态'.json_encode($is_da_cang_vip)]);
                Db::name('log')->insert(['data'=>'商户支付订单'.json_encode($is_shanghu1)]);
                Db::name('log')->insert(['data'=>'商户'.json_encode($is_shanghu2)]);
                Db::name('log')->insert(['data'=>'商户入驻表'.json_encode($is_shanghu3)]);
                Db::name('log')->insert(['data'=>'渠道商'.json_encode($is_channel)]);
                //如果是大仓会员
                if($is_da_cang_vip){
                    //如果间接上级是金卡会员 8%佣金
                    if($is_da_cang_vip['type'] == 1){
                        $top_top_yongjin = bcmul($order_data['pay_price'], 0.08, 5);
                    }elseif ($is_da_cang_vip['type'] == 2){
                        //如果上级是银卡会员 5%佣金
                        $top_top_yongjin = bcmul($order_data['pay_price'], 0.05, 5);
                    }
                }
                //如果是商户 10%佣金
                if($is_shanghu1||$is_shanghu2||$is_shanghu3){
                    $top_top_yongjin = bcmul($order_data['pay_price'], 0.1, 5);
                }
                //如果是渠道商 15% 佣金
                if($is_channel){
                    $top_top_yongjin = bcmul($order_data['pay_price'], 0.15, 5);
                }
                $top_top_yongjin=round($top_top_yongjin,2);
                $title='佣金';
                $mark = '下级邀请渠道商获得' . $top_top_yongjin . '培育奖励';
                $billData=[
                    'uid'=>$top_top_uid,
                    'link_id'=>$order_data['id'],
                    'pm'=>1,
                    'title'=>$title,
                    'category'=>'now_money',
                    'type'=>'commission',
                    'number'=>$top_top_yongjin,
                    'balance'=>0,
                    'mark'=>$mark,
                    'create_time'=>date("Y-m-d H:i:s",time()),
                    'status'=>1,
                    'order_sn'=>$order_sn,
                    'type_shop'=>0,
                    'commission_type'=>9,
                    'order_type'=>1
                ];
                Db::name('user_bill')->insert($billData);
                Db::name('user')->where('uid',$top_top_uid)->inc('brokerage_price',$top_top_yongjin)->update();
            }

        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>'渠道商佣金error'.$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }

        return true;

        //2022年6月22号前版本
        $order_data=Db::name('channel_order')->where('order_no',$order_sn)->find();//订单数据
        $channelrecommend=Db::name('channel_user')->where('uid',$order_data['uid'])->find();
        //渠道商表中查无此人
        if(!$channelrecommend){
            return false;
        }
        $user_data=Db::name('user')->where('uid',$order_data['uid'])->find();//渠道商用户信息
        $top_user_data=Db::name('user')->where('uid',$user_data['spread_uid'])->find();//用户的推荐人（邀请注册的人）
        $top_uid = $top_user_data['uid'];
        if($channelrecommend['recommend_uid'] != '' || $channelrecommend['recommend_uid'] != 0){
            $top_uid=$channelrecommend['recommend_uid'];
        }
        //渠道商本人给养老金5%
        $ylj=bcmul($order_data['pay_price'],'0.05',5);//5%的养老金
        $ylj=round($ylj,2);
        $title='养老金';
        $mark = '成为渠道商获得' . $ylj . '养老金';
        $billData=[
            'uid'=>$order_data['uid'],
            'link_id'=>$order_data['id'],
            'pm'=>1,
            'title'=>$title,
            'category'=>'now_money',
            'type'=>'commission',
            'number'=>$ylj,
            'balance'=>0,
            'mark'=>$mark,
            'create_time'=>date("Y-m-d H:i:s",time()),
            'status'=>1,
            'order_sn'=>$order_sn,
            'type_shop'=>0,
            'commission_type'=>5,
            'order_type'=>1,
            'gzc'=>0
        ];

        Db::name('user_bill')->insert($billData);
        Db::name("user")->where("uid",$order_data['uid'])->inc('annuity', $ylj) ->update();
        Db::name("user")->where("uid",$order_data['uid'])->inc('annuity_num', 1) ->update();

        //如果有直接上级，给佣金10%
        if($top_uid > 0){
            $price=bcmul($order_data['pay_price'],'0.1',5);//10%的推荐佣金
            $price=round($price,2);
            $title='佣金';
            $mark = '邀请渠道商获得' . $price . '佣金';
            $billData=[
                'uid'=>$top_uid,
                'link_id'=>$order_data['id'],
                'pm'=>1,
                'title'=>$title,
                'category'=>'now_money',
                'type'=>'commission',
                'number'=>$price,
                'balance'=>0,
                'mark'=>$mark,
                'create_time'=>date("Y-m-d H:i:s",time()),
                'status'=>1,
                'order_sn'=>$order_sn,
                'type_shop'=>0,
                'commission_type'=>9,
                'order_type'=>1
            ];
            Db::name('user_bill')->insert($billData);
            Db::name('user')->where('uid',$top_uid)->inc('brokerage_price',$price)->update();


            $top_top_uid =Db::name('user')->where('uid',$top_uid)->value('spread_uid');//推荐人的推荐人（邀请注册的人）
            $top_channelrecommend=Db::name('channel_user')->where('uid',$top_uid)->find();//推荐人的推荐人（渠道商推荐人）
            if($top_channelrecommend && ($top_channelrecommend['recommend_uid'] != '' || $top_channelrecommend['recommend_uid'] != 0)){
                $top_top_uid = $top_channelrecommend['recommend_uid'];
            }
            //如果有间接上级，给佣金5%
            if($top_top_uid > 0){
                //大仓会员
                $is_da_cang_vip=Db::name('da_cang_user')->where('status',1)->where('uid',$top_top_uid)->find();
                //商户
                $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$top_top_uid)->find();
                $is_shanghu2=Db::name('merchant')->where('uid',$top_top_uid)->find();
                $is_shanghu3=Db::name('merchant_intention')->where('uid',$top_top_uid)->find();
                //渠道商
                $is_channel = Db::name('channel_user') -> where('uid',$top_top_uid)->where('status',1)->find();
                //第二级 必需是会员或者商户 或者渠道商
                if($is_da_cang_vip || $is_shanghu1 || $is_shanghu2 || $is_shanghu3 || $is_channel){
                    $price=bcmul($order_data['pay_price'],'0.05',5);//5%的推荐佣金
                    $price=round($price,2);
                    $title='佣金';
                    $mark = '下级邀请渠道商获得' . $price . '佣金';
                    $billData=[
                        'uid'=>$top_top_uid,
                        'link_id'=>$order_data['id'],
                        'pm'=>1,
                        'title'=>$title,
                        'category'=>'now_money',
                        'type'=>'commission',
                        'number'=>$price,
                        'balance'=>0,
                        'mark'=>$mark,
                        'create_time'=>date("Y-m-d H:i:s",time()),
                        'status'=>1,
                        'order_sn'=>$order_sn,
                        'type_shop'=>0,
                        'commission_type'=>9,
                        'order_type'=>1
                    ];
                    Db::name('user_bill')->insert($billData);
                    Db::name('user')->where('uid',$top_top_uid)->inc('brokerage_price',$price)->update();
                }
            }
        }

        return true;
        //以下为原逻辑。2022.05.30更改
        //消费者上级奖励
        if($top_user_data){//上级用户信息是否存在
            $uid=$top_user_data['uid'];
            $price=bcmul($order_data['pay_price'],'0.05',3);//5%的推荐佣金
            $price=round($price,2);
            $title='养老金';
            $mark='下级成为渠道商获得'.$price.'养老金';
            $billData=[
                'uid'=>$uid,
                'link_id'=>$order_data['id'],
                'pm'=>1,
                'title'=>$title,
                'category'=>'now_money',
                'type'=>'commission',
                'number'=>$price,
                'balance'=>0,
                'mark'=>$mark,
                'create_time'=>date("Y-m-d H:i:s",time()),
                'status'=>1,
                'order_sn'=>$order_sn,
                'type_shop'=>0,
                'commission_type'=>5,
                'order_type'=>1,
                'gzc'=>0
            ];

            Db::name('user_bill')->insert($billData);
            Db::name("user")->where("uid",$uid)->inc('annuity', $price) ->update();
            Db::name("user")->where("uid",$uid)->inc('annuity_num', 1) ->update();
        }
        //上级奖励
        //备注同上

        $channelrecommend=Db::name('channel_user')->where('uid',$order_data['uid'])->find();
        if(!$channelrecommend){
            return false;
        }
        $uid=$channelrecommend['recommend_uid'];

        $price=bcmul($order_data['pay_price'],'0.1',3);
        $price=round($price,2);
        $mark = '邀请渠道商获得' . $price . '佣金';
        $commission_type=9;
        $is_implement=1;
        if($uid==0){
            $uid=$top_user_data['uid'];
            $commission_type=3;
            $is_implement=0;
        }
        $title='佣金';

        $billData=[
            'uid'=>$uid,
            'link_id'=>$order_data['id'],
            'pm'=>1,
            'title'=>$title,
            'category'=>'now_money',
            'type'=>'commission',
            'number'=>$price,
            'balance'=>0,
            'mark'=>$mark,
            'create_time'=>date("Y-m-d H:i:s",time()),
            'status'=>1,
            'order_sn'=>$order_sn,
            'type_shop'=>0,
            'commission_type'=>$commission_type,
            'order_type'=>1
        ];
        Db::name('user_bill')->insert($billData);
        Db::name('user')->where('uid',$uid)->inc('brokerage_price',$price)->update();
        if($is_implement){
            if($channelrecommend['recommend_uid']!=0){
                $price=bcmul($order_data['pay_price'],'0.05',3);
                $price=round($price,2);
                $mark = '邀请渠道商获得' . $price . '佣金';
                $title='佣金';
                $tuijian=Db::name('channel_user')->where('uid',Db::name('channel_user')->where('uid',$channelrecommend['recommend_uid'])->value('recommend_uid'))->find();
                if($tuijian){
                    $billData=[
                        'uid'=>$tuijian['uid'],
                        'link_id'=>$order_data['id'],
                        'pm'=>1,
                        'title'=>$title,
                        'category'=>'now_money',
                        'type'=>'commission',
                        'number'=>$price,
                        'balance'=>0,
                        'mark'=>$mark,
                        'create_time'=>date("Y-m-d H:i:s",time()),
                        'status'=>1,
                        'order_sn'=>$order_sn,
                        'type_shop'=>0,
                        'commission_type'=>9,
                        'order_type'=>1
                    ];
                    Db::name('user_bill')->insert($billData);
                    Db::name('user')->where('uid',$tuijian['uid'])->inc('brokerage_price',$price)->update();
                }
            }
        }




    }
    //渠道商分账
    public function channel_spilet($order_no)
    {
        $order_data=Db::name('channel_order')->where('order_no',$order_no)->where('status',1)->find();
        if(empty($order_data)){
            return '';
        }
        $data['requestId'] = ShouxinyiApiRequest::getOrderNumber('split');
        $data['orderId'] = $order_no.'_'.$order_data['rand'];
        $data['totalSplitAmount'] = bcmul($order_data['pay_price'],'100');
        $monent=bcmul($order_data['pay_price'],'100');
        $splitDetails = array(
            array(
                'subSplitRequestId' => $data['requestId'] . '_1',
                'splitAccType' => 'MERCHANT_ACC',
                'splitAccId' => '895152791',
                'splitAmount' => $monent
            )
        );
        $insertData=[
            [
                'mid' => $order['mer_id']??0,
                'requestId' => $data['requestId'],
                'group_order_id' => $data['orderId'],
                'subSplitRequestId' => $data['requestId'].'_1',
                'splitAccId' => '895152791',
                'splitAmount' => $splitDetails[0]['splitAmount'],
                'totalSplitAmount' => $data['totalSplitAmount'],
                'status' => 0
            ]
        ];
        $data['splitDetails'] = $splitDetails;

        Db::name("store_split_order") -> insertAll($insertData);

        return ShouxinyiApiRequest::split($data);
    }

    public function marketing_spilet($order_id){

    }

    public function pay_huifu($payType,$code,$groupOrder,$title,$notify_url,$pay_mode=null,$appid=''){

        $order_no = $groupOrder['group_order_sn'] ?? $groupOrder['order_no'];



        if($payType == 'wx'){

            if(!$code || $code == '' || $code =='undefined')
                return "授权失败，code为空";
            if($appid == '') {


                $pay_wx = systemConfig('pay_wx');

                if ($pay_wx == 2){
                    $appid = env('WECHAT_MP.APPID');
                    $new_secret = env('WECHAT_MP.SECRET');

                    $app_id='app_0827b960-b932-45ec-b800-4e850091b419';
                    $key='api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';

                }elseif ($pay_wx == 3){
                    $appid = env('WECHAT_TDYL.APPID');
                    $new_secret = env('WECHAT_TDYL.SECRET');


                    Db::name('log')->insert(['data'=>'appid---'.$appid]);
                    Db::name('log')->insert(['data'=>'new_secret---'.$new_secret]);
                    $app_id='app_383a75dd-c03d-44ab-8f58-92c60fe9b9d0';
                    $key='api_live_b0a687ec-5450-4ada-a0e4-65bac0f46871';

                }

            }else{
                $app_id='app_0827b960-b932-45ec-b800-4e850091b419';
                $key='api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';
                $new_secret = "c8cbe24fa3b83f77a88b79554b3aeab4";
            }

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$new_secret."&js_code=".$code."&grant_type=authorization_code";
            $get = curlGet($url);
            Db::name('log')->insert(['data'=>'pay_wx---'.$pay_wx]);
            Db::name('log')->insert(['data'=>'code---'.$code]);
            Db::name('log')->insert(['data'=>'url---'.$url]);
            Db::name('log')->insert(['data'=>'open_id---'.json_encode($get)]);
            if(!isset($get['openid']) || empty($get['openid'])){
                return '授权失败';
            }
            $openid = $get['openid'];

            $member_id=0;
            $type='2';
            $pay_channel='wx_lite';

            $expend=[
                'open_id'=>$openid,
                'wx_app_id'=> $appid
            ];


            if ($groupOrder['order_type'] = "marketing"){

                db::name("test_log")->insert(["note"=>"pay_huifu" . json_encode($groupOrder)]);
                // 创富宝 分账
                //创富宝
                $cfb = sprintf("%01.2f",round(bcmul($groupOrder['pay_price'],'0.094',5),2));//9.4%的分账

                $cfb_member = "jsdk_member_1680162243019";
                //  平台
                $cxb = sprintf("%01.2f",round(bcsub($groupOrder['pay_price'],$cfb,5),2));//剩下的归平台

                $div_members=[
                    [
                        'member_id'=>$member_id,
                        'amount'=>$cxb,
                        'fee_flag'=>'Y'
                    ],
                    [
                        'member_id'=>$cfb_member,
                        'amount'=>$cfb,
                        'fee_flag'=>'N'
                    ]
                ];
            }else{
                $div_members=[
                    [
                        'member_id'=>$member_id,
                        'amount'=>$groupOrder['pay_price'],
                        'fee_flag'=>'Y'
                    ]
                ];
            }

            $params=[
                'order_no'=>$order_no."_".rand(1000,9999),
                'app_id'=>$app_id,
                'pay_channel'=>$pay_channel,
                'pay_amt'=>(string)$groupOrder['pay_price'],
                'goods_title'=> strlen($title) > 64 ? mb_substr($title, 0, 64,'utf-8') : $title,// 解决因为太长不能支付问题
                'goods_desc' => strlen($title) > 42 ? mb_substr($title, 0, 127,'utf-8') : $title,// 解决因为太长不能支付问题
                'device_info'=>[
                    'device_ip'=>app('request')->ip()
//                    'device_ip'=>'115.171.134.68'
                ],

                'expend'=>json_encode($expend),
                'div_members'=>json_encode($div_members),
                'fee_mode'=>'I',
                'notify_url'=>$notify_url
            ];
            if($pay_mode == 'delay'){
                $params['pay_mode'] = 'delay';
                unset($params['div_members']);
                unset($params['fee_mode']);
            }
            return $this->Payment_create_traits_b($params,$type,$key);
        }elseif($payType=='ALI'){
//            throw new AuthException('支付宝正在升级，请使用微信支付');
            $member_id=0;
            $type='1';
            $pay_channel='alipay_qr';
            // 天地博爱科技通道
            $app_id='app_44108546-d27a-48ee-88c1-84b45b75114f';
            $key='api_live_b23537ed-64b8-45d6-832e-fb228aa9e0a9';
            // 天地博爱通道
//            $app_id='app_0827b960-b932-45ec-b800-4e850091b419';
//            $key='api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';

            $div_members=[
                [
                    'member_id'=>$member_id,
                    'amount'=>$groupOrder['pay_price'],
                    'fee_flag'=>'Y'
                ]
            ];

            $params=[
                'order_no'=>$order_no."_".rand(1000,9999),
                'app_id'=>$app_id,
                'pay_channel'=>$pay_channel,
                'pay_amt'=>(string)$groupOrder['pay_price'],
                'goods_title'=> strlen($title) > 64 ? mb_substr($title, 0, 64,'utf-8') : $title,// 解决因为太长不能支付问题
                'goods_desc' => strlen($title) > 42 ? mb_substr($title, 0, 127,'utf-8') : $title,// 解决因为太长不能支付问题
                'device_info'=>[
                    'device_ip'=>app('request')->ip()
//                    'device_ip'=>'115.171.134.68'
                ],

//                    'expend'=>json_encode($expend),
                'div_members'=>json_encode($div_members),
                'fee_mode'=>'I',
                'notify_url'=>$notify_url
            ];
            if($pay_mode == 'delay'){
                $params['pay_mode'] = 'delay';
                unset($params['div_members']);
                unset($params['fee_mode']);
            }
            return $this->Payment_create_traits_a($params,$type,$key);
        }

    }

    /**
     * 电影票支付
     *
     * @return mixed
     */
    public function dy_pay_wechat_mp()
    {
        $order_id = Request::param('oid', '');
        $code = Request::param('code', '');
        $pay_type = Request::param('type', '');
        if (empty($order_id)) return app('json')->fail('订单不存在');
        if (empty($pay_type) || !in_array(strtolower($pay_type), ['wx', 'ali'])) return app('json')->fail('请选择支付方式');

        try {
            /** @var MovieRepository $movieRepository */
            $movieRepository = new MovieRepository(new MovieOrderDao());
            return app('json')->success($movieRepository->confirmOrder(null, $order_id, $pay_type, $code));
        } catch (\Exception $exception) {
            return app('json')->fail($exception->getMessage());
        }
    }
}
