<?php

/**
 * 支付宝（旧版 alipay）退款接口
 * 由 Pay::payrefund() require 调用
 *
 * 旧版即时到账使用 mapi 无密退款服务 refund_fastpay_by_platform_nopwd
 * 需在支付宝签约「无密退款」产品；未签约时会返回支付宝错误信息
 *
 * 可用变量：$data 流水记录，$config 接口配置，$money 退款金额
 * 须设置：$return = dr_return_data(...)
 */

$money = abs(isset($money) ? $money : $data['value']);
$trade_no = trim((string)$data['result']);
$batch_no = date('Ymd') . $data['id'] . mt_rand(1000, 9999);
$batch_num = 1;
// 格式：原付款支付宝交易号^退款总金额^退款理由
$detail_data = $trade_no . '^' . number_format($money, 2, '.', '') . '^' . dr_lang('订单退款');

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

    require_once dirname(__FILE__) . '/pc/alipay_core.function.php';
    require_once dirname(__FILE__) . '/pc/alipay_md5.function.php';
    require_once dirname(__FILE__) . '/pc/alipay_submit.class.php';

    $alipay_config = [];
    $alipay_config['partner'] = $config['id'];
    $alipay_config['seller_id'] = $config['id'];
    $alipay_config['key'] = $config['key'];
    $alipay_config['sign_type'] = strtoupper('MD5');
    $alipay_config['input_charset'] = strtolower('utf-8');
    $alipay_config['cacert'] = dirname(__FILE__) . '/pc/cacert.pem';
    $alipay_config['transport'] = 'http';
    $alipay_config['payment_type'] = '1';
    $alipay_config['service'] = 'refund_fastpay_by_platform_nopwd';

    $parameter = [
        'service' => $alipay_config['service'],
        'partner' => $alipay_config['partner'],
        'notify_url' => ROOT_URL . 'api/pay/' . $data['type'] . '/pc_notify_url.php',
        'seller_user_id' => $alipay_config['seller_id'],
        'refund_date' => date('Y-m-d H:i:s'),
        'batch_no' => $batch_no,
        'batch_num' => $batch_num,
        'detail_data' => $detail_data,
        '_input_charset' => trim(strtolower($alipay_config['input_charset'])),
    ];

    $alipaySubmit = new AlipaySubmit($alipay_config);
    $url = $alipaySubmit->alipay_gateway_new . $alipaySubmit->buildRequestParaToString($parameter);

    $response = '';
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = (string)curl_exec($ch);
        curl_close($ch);
    } else {
        $response = (string)@file_get_contents($url);
    }

    // 成功时一般为 XML，含 <is_success>T</is_success>
    if ($response && (stripos($response, '<is_success>T</is_success>') !== false || stripos($response, '<is_success>t</is_success>') !== false)) {
        $return = dr_return_data(1, dr_lang('退款成功'), [
            'batch_no' => $batch_no,
            'trade_no' => $trade_no,
            'response' => $response,
        ]);
    } else {
        $msg = dr_lang('支付宝退款失败');
        if ($response && preg_match('/<error>([^<]+)<\/error>/i', $response, $m)) {
            $msg = $m[1];
        } elseif ($response && preg_match('/<msg>([^<]+)<\/msg>/i', $response, $m)) {
            $msg = $m[1];
        }
        $return = dr_return_data(0, $msg, ['response' => $response, 'batch_no' => $batch_no]);
    }
}
