<?php
/**
 * +------------------------------------------------------------
 * | 财务 finance/controller/Alipay.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\finance\controller;

use think\Validate;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class Alipay extends Module
{

    private static $config;
    private $alipay;
    private $validate = [
        'msg' => [
            'out_trade_no.require' => '订单号不能为空',
            'subject.require' => '商品描述不能为空',
            'total_amount.require' => '订单金额不能为空'
        ],
        'rule' => [
            'out_trade_no' => 'require',
            'subject' => 'require',
            'total_amount' => 'require'
        ],
        'data' => []
    ];

    function initialize()
    {
        parent::initialize();
        self::$config = config('')['finance']['alipay'];
    }

    function _init_data($data = [])
    {
        $this->data = $data;
        $this->alipay = Pay::alipay(self::$config);
        $this->validate['data'] = [
            'out_trade_no' => empty($data['id']) ? '' : $data['id'],
            'subject' => empty($data['memo']) ? ('支付订单' . (empty($data['id']) ? '' : ':' . $data['id'])) : $data['memo'],
            'total_amount' => empty($data['money']) ? 0 : ($data['money'])
        ];
        return $this;
    }

    public function return()
    {
        $data = Pay::alipay(self::$config)->verify();
        if (!empty($data)) {
            $attr = [
                'money' => $data['total_amount'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_no' => $data['trade_no']
            ];
            $result = action('finance/api/check_pay_result', [$attr]);
            if ($result['code'] == 1) {
                $this->success('支付成功', url('finance/user/account'));
            } else {
                $this->error('支付失败：' . $result['msg']);
            }
        } else {
            $this->error('支付失败', url('finance/user/account'));
        }
        //订单号：$data->out_trade_no
        //支付宝交易号：$data->trade_no
        //订单总金额：$data->total_amount
    }

    public function notify()
    {
        $alipay = Pay::alipay(self::$config);
        try {
            $data = $alipay->verify();
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            Log::debug('Alipay notify', $data->all());
            $attr = [
                'money' => $data['total_amount'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_no' => $data['trade_no']
            ];
            $result = action('finance/api/check_pay_result', [$attr, 'notify']);
            if ($result['code'] == 1) {
                return 'success';
            } else {
                return 'fail';
            }
        } catch (Exception $e) {
            // $e->getMessage();
        }
        return $alipay->success()->send();
    }

    function wap()
    {
        $check = $this->check();
        if ($check === true) {
            $result = $this->alipay->wap($this->validate['data']);
            return ['code' => 1, 'msg' => '', 'data' => $result->getContent()];
        } else {
            return ['code' => 0, 'msg' => $check];
        }
    }

    function web()
    {
        $check = $this->check();
        if ($check === true) {
            $result = $this->alipay->web($this->validate['data']);
            return ['code' => 1, 'msg' => '', 'data' => $result->getContent()];
        } else {
            return ['code' => 0, 'msg' => $check];
        }
    }

    /**
     * 扫码支付
     */
    function scan()
    {
        $check = $this->check();
        if ($check === true) {
            $result = $this->alipay->scan($this->validate['data']);
            if (!empty($result['qr_code'])) {
                return ['code' => 1, 'msg' => '', 'data' => urlencode($result['qr_code']), 'order' => $this->validate['data']['out_trade_no']];
            } else {
                return ['code' => 0, 'msg' => $result['msg']];
            }
        } else {
            return ['code' => 0, 'msg' => $check];
        }
    }

    function check()
    {
        $validate = new Validate($this->validate['rule'], $this->validate['msg']);
        $result = $validate->check($this->validate['data']);
        if ($result === true) {
            return true;
        } else {
            return $validate->getError();
        }
    }
}