<?php

/**
 * 支付宝（alipay2）退款接口
 * 由 Pay::payrefund() require 调用
 *
 * 可用变量：$data 流水记录，$config 接口配置，$money 退款金额（由模型传入前已算 abs）
 * 须设置：$return = dr_return_data(...)
 */

$money = abs(isset($money) ? $money : $data['value']);
$trade_no = trim((string)$data['result']); // 支付成功时写入的支付宝交易号
$out_trade_no = trim((string)\Phpcmf\Service::C()->member_cache['pay']['prefix'])
    . date('YmdHis', (int)$data['inputtime']) . '00' . $data['id'];
$out_request_no = 'RF' . $data['id'] . date('YmdHis');

if (!$config || empty($config['id']) || empty($config['key']) || empty($config['key2'])) {
    $return = dr_return_data(0, dr_lang('支付宝退款配置不完整'));
} elseif (!$trade_no && !$out_trade_no) {
    $return = dr_return_data(0, dr_lang('缺少支付宝交易号，无法退款'));
} else {

    $alipy = [
        'app_id' => $config['id'],
        'merchant_private_key' => $config['key'],
        'charset' => 'UTF-8',
        'sign_type' => 'RSA2',
        'gatewayUrl' => 'https://openapi.alipay.com/gateway.do',
        'alipay_public_key' => $config['key2'],
        'notify_url' => '',
        'return_url' => '',
    ];

    require_once dirname(__FILE__) . '/pagepay/service/AlipayTradeService.php';
    require_once dirname(__FILE__) . '/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php';
    require_once dirname(__FILE__) . '/aop/request/AlipayTradeRefundRequest.php';

    $builder = new AlipayTradeRefundContentBuilder();
    if ($trade_no) {
        $builder->setTradeNo($trade_no);
    } else {
        $builder->setOutTradeNo($out_trade_no);
    }
    $builder->setRefundAmount((string)$money);
    $builder->setRefundReason(dr_lang('订单退款'));
    $builder->setOutRequestNo($out_request_no);

    try {
        $aop = new AlipayTradeService($alipy);
        $response = $aop->Refund($builder);
        if ($response && isset($response->code) && $response->code == '10000') {
            $return = dr_return_data(1, dr_lang('退款成功'), [
                'trade_no' => isset($response->trade_no) ? $response->trade_no : $trade_no,
                'out_request_no' => $out_request_no,
                'fund_change' => isset($response->fund_change) ? $response->fund_change : '',
            ]);
        } else {
            $msg = isset($response->sub_msg) && $response->sub_msg
                ? $response->sub_msg
                : (isset($response->msg) ? $response->msg : dr_lang('支付宝退款失败'));
            $return = dr_return_data(0, $msg, is_object($response) ? (array)$response : []);
        }
    } catch (\Exception $e) {
        $return = dr_return_data(0, dr_lang('支付宝退款异常：%s', $e->getMessage()));
    }
}
