User.php 16.0 KB
<?php

namespace app\api\controller;

use addons\third\library\Service;
use app\api\model\MoneyLog;
use app\api\model\Level;
use app\api\model\promoter\ApplePromoter;
use app\api\validate\IndexValidate;
use app\common\controller\Api;
use app\common\library\CalculatedAmount;
use app\common\library\Sms;
use EasyWeChat\Factory;
use think\Db;
use think\Model;

/**
 * 个人中心接口
 */
class User extends Api
{
    protected $noNeedLogin = ['third', 'getCode', 'combineURL', 'login','apply_content'];
    protected $noNeedRight = ['*'];
    const GET_CODE = 'https://open.weixin.qq.com/connect/oauth2/authorize';// 获取code(网页授权使用)

    /**
     * 用户同意授权获取code
     * @param string $redirect_uri 授权后重定向的回调链接地址,需要urlEncode处理
     */
    public function getCode()
    {
//	    $redirect_uri=$this->request->param('redirect_uri');
        $redirect_uri = urlencode('http://repairsh5.n.broing.cn');//重定向地址
        $uri          = $this->combineURL(self::GET_CODE, [
            'appid'         => 'wx2a7905afabd3899e',
            'scope'         => 'snsapi_userinfo',
            'response_type' => 'code',
            'redirect_uri'  => $redirect_uri,
            'state'         => 'STATE#wechat_redirect',
        ]);
        $this->success('url', $uri);
    }

    /**
     * @ApiInternal
     * 拼接url
     * @param string $baseURL 请求的url
     * @param array $keysArr 参数列表数组
     * @return string 返回拼接的url
     */
    public function combineURL($baseURL, $keysArr)
    {
        $combined = $baseURL . "?";
        $valueArr = array();
        foreach ($keysArr as $key => $val) {
            $valueArr[] = "$key=$val";
        }
        $keyStr   = implode("&", $valueArr);
        $combined .= ($keyStr);
        return $combined;
    }

    /**
     * 公众号登录
     * @ApiTitle (公众号登录)
     * @ApiParams   (name="code", type="string", description="code")
     */
    public function third()
    {
        $code     = $this->request->param("code");
        $platform = 'wechat';
        $config   = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result,
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'));
    }

    /**
     * 个人中心
     * @ApiTitle (个人中心)
     * @ApiReturnParams   (name="nickname", type="string", description="昵称")
     * @ApiReturnParams   (name="avatar", type="string", description="头像")
     * @ApiReturnParams   (name="level", type="string", description="等级")
     * @ApiReturnParams   (name="level_name", type="string", description="等级称号")
     * @ApiReturnParams   (name="mobile", type="string", description="电话号")
     * @ApiReturnParams   (name="is_promoter", type="string", description="是否推广员:1=是,2=否")
     * @ApiReturnParams   (name="promotion_code", type="string", description="二维码")
     * @ApiReturnParams   (name="promotion_no", type="string", description="推广码")
     * @ApiReturnParams   (name="promotion_commission", type="string", description="累计推广佣金")
     * @ApiReturnParams   (name="direct_commission", type="string", description="累计直推佣金")
     * @ApiReturnParams   (name="total_commission", type="string", description="累计获得佣金")
     * @ApiReturnParams   (name="total_commission", type="string", description="累计获得佣金")
     * @ApiReturnParams   (name="withdrawable_cash_price", type="string", description="可提现金额")
     * @ApiReturnParams   (name="cumulative_withdrawal_price", type="string", description="累计提现金额")
     * @ApiReturnParams   (name="freeze_commission", type="string", description="冻结佣金")
     * @ApiReturnParams   (name="customer_service", type="string", description="联系客服")
     * @ApiReturnParams   (name="promotion_rules", type="string", description="推广规则")
     */
    public function user_info()
    {
        $model = new \app\api\model\User();
        //判断是否推广员
        if ($this->auth->is_promoter == 1) {
            CalculatedAmount::calculation_level($this->auth->id);
            $field = [
                'id,nickname,avatar,level,mobile,is_promoter,promotion_code,promotion_no,promotion_commission,
            withdrawable_cash_price,cumulative_withdrawal_price,direct_commission,last_time',
            ];
            $data  = $model
                ->field($field)
                ->where('id', $this->auth->id)
                ->find();

            //计算可提现金额
            CalculatedAmount::calculation($this->auth->id);

            //计算用户等级
            if ($data['level'] <= 0) {
                $data['level'] = 1;
            }
            if ($data['is_promoter'] == 1 && $data['level'] != 0) {
                $data['level_name'] = (new Level())->where('level', $data['level'])->value('leve_name');
            }
            //计算累计获得佣金
	        $moneyModel      = new MoneyLog();
//	        $out_money = $moneyModel->where(['user_id' => $this->auth->id, 'type' => 'out'])->sum('money');
            $data['total_commission'] = $data['promotion_commission'] + $data['direct_commission'];
            //后台设置的冻结佣金
            $freeze_commission = config('site.freeze_commission');
            //查询用户是否有过佣金
            $price = db('user_money_log')->where('user_id', $this->auth->id)->find();

	        //计算待审核状态的提现信息
	        $withdrawal_prices = Db::name('withdrawal_log')->where('user_id',$this->auth->id)
		        ->where(function ($query){
			        $query->whereOr('status',2)->whereOr('status',0);
		        })
//		        ->where('status',2)
		        ->sum('withdrawal_price');
            if (empty($price)) {
	            //如果从未获得过佣金,则可提现金额与冻结佣金为0
                $data['withdrawable_cash_price'] = 0;
                $data['freeze_commission']       = 0;
            } else {
            	//$data['last_time'] 最后获得佣金时间
                //判断是否九十天内没有获得过佣金
                if ($model->thawing($data['last_time'])) {
                    //如果未获得,则冻结金额释放到提现金额中,可提现金额=可提现佣金加冻结佣金
                    $data['withdrawable_cash_price'] = number_format($data['withdrawable_cash_price']-$withdrawal_prices,2,'.','');
                    $data['freeze_commission']       = 0;
                } else {
                    //如果获得佣金小于冻结佣金,可提现金额为0,冻结佣金为获得佣金
                    if ($data['withdrawable_cash_price'] < $freeze_commission) {
                        $data['freeze_commission']       = number_format($data['withdrawable_cash_price'],2,'.','');
	                    $data['withdrawable_cash_price'] = 0;
                    } else {
                        $data['withdrawable_cash_price'] = number_format($data['withdrawable_cash_price'] - $freeze_commission - $withdrawal_prices,2,'.','');
                        $data['freeze_commission']       = $freeze_commission;
                    }
                }
            }

            //联系客服
            $data['customer_service'] = config('site.customer_service');
            //推广规则
            $data['promotion_rules'] = set_img_style(config('site.promotion_rules'));
            $this->success('ok', $data);
        }

        $field = [
            'id,nickname,avatar,is_promoter',
        ];
        $data  = $model
            ->field($field)
            ->where('id', $this->auth->id)
            ->find();
        //联系客服
        $data['customer_service'] = config('site.customer_service');
        //推广规则
        $data['promotion_rules'] = set_img_style(config('site.promotion_rules'));
        $this->success('ok', $data);
    }

    /**
     * 申请成为推广员
     * @ApiTitle (申请成为推广员)
     * @ApiParams   (name="realname", type="string", description="真实姓名")
     * @ApiParams   (name="mobile", type="string", description="电话号")
     * @ApiParams   (name="id_number", type="string", description="身份证号")
     * @ApiParams   (name="code", type="string", description="验证码")
     * @ApiParams   (name="id_images", type="string", description="身份证图片")
     * @ApiParams   (name="recommender_name", type="string", description="推荐人姓名")
     * @ApiParams   (name="recommender_no", type="string", description="推荐人推广码")
     */
    public function apply()
    {
        if ($this->auth->is_promoter == 1) {
            $this->error('您已是推广员');
        }
        $validate = new IndexValidate();
        if (!$validate->scene('apply')->check($this->param)) {
            $this->error($validate->getError());
        }
        $userModel        = new \app\api\model\User();
        $applyModel       = new ApplePromoter();
        $realname         = $this->param['realname'];
        $mobile           = $this->param['mobile'];
        $id_number        = $this->param['id_number'];
        $code             = $this->param['code'];
        $id_images        = $this->param['id_images'];
        $recommender_name = $this->param['recommender_name'];
        $recommender_no   = $this->param['recommender_no'];

        //校验上传身份证数量
        if (count($id_images) !== 2) {
            $this->error('请上传身份证正反面两张图片');
        }

	    //校验推荐人、推广码
	    if (!empty($recommender_no) || !empty($recommender_name)) {
	        if(empty($recommender_no)) {
	            $this->error('请填写推荐人推广码');
            }
            if(empty($recommender_name)) {
                $this->error('请填写推荐人姓名');
            }
		    $user = $userModel
			    ->where(function ($query) use ($recommender_no, $recommender_name) {
				    if (!empty($recommender_no)) {
					    $query->where('promotion_no', $recommender_no);
				    }
				    if (!empty($recommender_name)) {
					    $query->where('username', $recommender_name);
				    }
				    if (!empty($recommender_name) && !empty($recommender_no)) {
					    $query->where(['username' => $recommender_name, 'promotion_no' => $recommender_no]);
				    }
			    })
			    ->find();
		    if (!$user) {
			    $this->error('抱歉,推荐人信息不存在');
		    }
		    $up_user_id = $user['id'];
	    }

        //校验验证码
        $result = Sms::check($mobile, $code);
        if (!$result) {
            $this->error('验证码错误');
        }

        $apply = [
            'user_id'          => $this->auth->id,
            'up_user_id'       => !empty($up_user_id) ? $up_user_id : '',
            'realname'         => $realname,
            'mobile'           => $mobile,
            'status'           => 0,
            'id_number'        => $id_number,
            'id_images'        => implode(',', $id_images),
            'recommender_name' => $recommender_name,
            'recommender_no'   => $recommender_no,
        ];

        if (ApplePromoter::get(['user_id' => $this->auth->id])) {
            $applyModel->save($apply, ['user_id' => $this->auth->id]);
            $this->success('申请提交成功');
        }
        $applyModel->save($apply);
        $this->success('申请提交成功');
    }

    /**
     * 《平台申请协议》和《查看分销员权益》
     * @ApiTitle (《平台申请协议》和《查看分销员权益》)
     * @ApiReturnParams   (name="platform_protocol", type="string", description="平台申请协议")
     * @ApiReturnParams   (name="distribution_interests", type="string", description="查看分销员权益")
     */
    public function apply_content()
    {
        $platform_protocol      = config('site.platform_protocol');
        $distribution_interests = config('site.distribution_interests');
        $this->success('ok', ['platform_protocol'      => set_img_style($platform_protocol),
                              'distribution_interests' => set_img_style($distribution_interests)]);
    }

    /**
     * 申请推广员详情
     * @ApiTitle (申请推广员详情)
     * @ApiReturnParams   (name="realname", type="string", description="真实姓名")
     * @ApiReturnParams   (name="mobile", type="string", description="电话号")
     * @ApiReturnParams   (name="id_number", type="string", description="身份证号")
     * @ApiReturnParams   (name="reasons_rejection", type="string", description="驳回理由")
     * @ApiReturnParams   (name="id_images", type="string", description="身份证图片")
     * @ApiReturnParams   (name="recommender_name", type="string", description="推荐人姓名")
     * @ApiReturnParams   (name="recommender_no", type="string", description="推荐人推广码")
     * @ApiReturnParams   (name="status", type="string", description="审核状态:-1=已驳回,0=审核中,1=已通过")
     */
    public function apply_detail()
    {
        $data = (new ApplePromoter())->where('user_id', $this->auth->id)->find();
        if (!empty($data)) {
            $data['id_images'] = !empty($data['id_images']) ? explode(',', $data['id_images']) : [];
        }

        $this->success('申请详情', $data);

    }

    /**
     * 服务说明列表
     * @ApiTitle (服务说明列表)
     * @ApiReturnParams   (name="id", type="string", description="id")
     * @ApiReturnParams   (name="title", type="string", description="标题")
     */
    public function explain_list()
    {
        $list = (new \app\api\model\service\Description())->field('id,title')->select();
        $this->success('服务说明列表', $list);
    }

    /**
     * 服务说明详情
     * @ApiTitle (服务说明详情)
     * @ApiParams   (name="id", type="string", description="id")
     * @ApiReturnParams   (name="id", type="string", description="id")
     * @ApiReturnParams   (name="title", type="string", description="标题")
     * @ApiReturnParams   (name="content", type="string", description="说明内容")
     */
    public function explain_detail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $list = (new \app\api\model\service\Description())
            ->field('id,title,content')->where('id', $id)->find();
        $this->success('服务说明列表', $list);
    }

    /**
     * 平台介绍
     * @ApiTitle (平台介绍)
     * @ApiReturnParams   (name="platform", type="string", description="平台介绍")
     */
    public function platform_introduction()
    {
        $platform = config('site.platform');
        $this->success('平台介绍', ['platform' => set_img_style($platform)]);
    }

	/**
	 * 申请提现页面
	 * @ApiTitle (申请提现页面)
	 * @ApiParams   (name="price", type="string", description="提现金额")
	 */
	public function calculate_price(){
		$price= $this->request->param('price');

		$withdrawal_fee = config('site.withdrawal_fee'); //手续费
		if (!empty($price)){
			$dec_price = number_format($price * ($withdrawal_fee/100),2,'.',''); //扣除费用
			$res_price = number_format($price-$dec_price,2,'.',''); //预计可提现金额
		}
		$this->success('成功',['withdrawal_fee'=>$withdrawal_fee,'dec_price'=>$dec_price,'res_price'=>$res_price]);

	}

    /**
     * 模拟登录
     * @ApiTitle (模拟登录)
     * @ApiParams   (name="user_id", type="string", description="用户ID")
     */
    public function login()
    {
        $user_id = $this->request->param('user_id');
        $this->auth->direct($user_id);
        $this->success('ok', $this->auth->getUserinfo());
    }
}