<?php
/**
 * 天泽付
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/4
 * Time: 17:28
 */

namespace Biz\Pay\Payment;

use Biz\Pay\NewBasePayment;

/**
 * Class TianzePayment
 * @package Biz\Pay\Payment
 */
class TianzePayment extends NewBasePayment
{

    /**
     * 基础配置
     * @return void
     */
    function config()
    {
        $this->apiUrl = 'http://101.132.128.241/GateWay/ReceiveBank.aspx';
        $this->setReturnType();//根据客户端类型返回支付接口类型
        $this->success = 'success';
    }

    /**
     * 接收通知
     * @param array $data
     * @return void [type] [description] 返回为1或success视接口而定
     */
    function notify(array $data)
    {
        $param['r0_Cmd'] = trim(strip_tags($data['r0_Cmd']));
        $param['r1_Code'] = trim(strip_tags($data['r1_Code']));
        $param['r2_TrxId'] = trim(strip_tags($data['r2_TrxId']));
        $param['r3_Amt'] = trim(strip_tags($data['r3_Amt']));
        $param['r4_Cur'] = trim(strip_tags($data['r4_Cur']));
        $param['r5_Pid'] = iconv("UTF-8", "gb2312//TRANSLIT", trim(strip_tags($data['r5_Pid'])));
        $param['r6_Order'] = strip_tags(trim($data['r6_Order']));
        $param['r7_Uid'] = strip_tags(trim($data['r7_Uid']));
        $param['r8_MP'] = iconv("UTF-8", "gb2312//TRANSLIT", trim(strip_tags($data['r8_MP'])));
        $param['r9_BType'] = trim(strip_tags($data['r9_BType']));
        $order_no = $param['r6_Order'] ?? '';
        $price = $param['r3_Amt'] ? $param['r3_Amt'] : 0;
        $real_price = $param['r3_Amt'] ? $param['r3_Amt'] : 0;
        $bill_no = $param['r2_TrxId'] ?? $order_no;
        $sign = strip_tags(trim($data['hmac']));
        $this->checkSign($param, $sign, $order_no, $price, $real_price, $is_bill_no = 0, $bill_no);
    }

    /**
     * 同步跳转
     * @param array $data
     * @return void [type] [description]
     */
    function redirect(array $data)
    {
        $html = <<<EOT
        <script>setTimeout(function() {
          window.history.go(-2);
        },3000);</script>
EOT;
        echo '支付已受理。如有疑问请联系客服！3秒后返回支付页，请稍候...';
        echo $html;
    }

    /**
     * 检查支付信息
     * @return void [type]            0=失败，1=成功
     */
    function check()
    {
        // TODO: Implement check() method.
    }

    /**
     * 返回支付类型的数组
     * @return void [type] [description]
     */
    function getPaymentType()
    {
        // TODO: Implement getPaymentType() method.
    }

    /**
     * 构建订单提交数组
     * @return array
     */
    function buildOrder(): array
    {
        $this->dataAccess->orderSn = str_replace(array('-', '_'), '', $this->dataAccess->orderSn);
        $orderInfo = array(
            'p0_Cmd' => 'Buy',
            'p1_MerId' => $this->paymentConfig['merchant_id'],
            'p2_Order' => $this->dataAccess->orderSn,
            'p3_Amt' => number_format($this->dataAccess->money, 2, '.', ''),
            'p4_Cur' => 'CNY',
            'p5_Pid' => iconv("UTF-8", "gb2312//TRANSLIT", $this->dataAccess->goodsName ?? 'testGoods'),
            'p6_Pcat' => iconv("UTF-8", "gb2312//TRANSLIT", $this->dataAccess->goodsName ?? 'testGoodsDesc'),
            'p7_Pdesc' => iconv("UTF-8", "gb2312//TRANSLIT", $this->dataAccess->goodsName ?? 'testGoodsDesc'),
            'p8_Url' => $this->notifyUrl,
            'p9_SAF' => '0',
            'pa_MP' => iconv("UTF-8", "gb2312//TRANSLIT", $this->dataAccess->goodsName ?? 'testGoods'),
            'pd_FrpId' => $this->dataAccess->payType,
            'pr_NeedResponse' => '1',
        );
        $orderInfo['hmac'] = $this->getReqHmacString($orderInfo['p2_Order'], $orderInfo['p3_Amt'], $orderInfo['p4_Cur'], $orderInfo['p5_Pid'], $orderInfo['p6_Pcat'], $orderInfo['p7_Pdesc'], $orderInfo['p8_Url'], $orderInfo['pa_MP'], $orderInfo['pd_FrpId'], $orderInfo['pr_NeedResponse'], $orderInfo['p0_Cmd'], $orderInfo['p9_SAF'], $orderInfo['p1_MerId'], $this->paymentConfig['merchant_md5_secret']);
        return $orderInfo;
    }

    /**
     * 生成签名函数
     * @param array $param
     * @param string $merchantSecret
     * @return mixed
     */
    function buildSign(array $param, $merchantSecret)
    {
        //本例此函数只用于异步回调签名
        $order_info = $this->getOrder($param['r6_Order']);
        if (!$order_info) return false;
        $p1_MerId = $order_info->merchant_id;
        $r0_Cmd = $param['r0_Cmd'];
        $r1_Code = $param['r1_Code'];
        $r2_TrxId = $param['r2_TrxId'];
        $r3_Amt = $param['r3_Amt'];
        $r4_Cur = $param['r4_Cur'];
        $r5_Pid = $param['r5_Pid'];
        $r6_Order = $param['r6_Order'];
        $r7_Uid = $param['r7_Uid'];
        $r8_MP = $param['r8_MP'];
        $r9_BType = $param['r9_BType'];

        #取得加密前的字符串
        $sbOld = "";
        #加入商家ID
        $sbOld = $sbOld . $p1_MerId;
        #加入消息类型
        $sbOld = $sbOld . $r0_Cmd;
        #加入业务返回码
        $sbOld = $sbOld . $r1_Code;
        #加入交易ID
        $sbOld = $sbOld . $r2_TrxId;
        #加入交易金额
        $sbOld = $sbOld . $r3_Amt;
        #加入货币单位
        $sbOld = $sbOld . $r4_Cur;
        #加入产品Id
        $sbOld = $sbOld . $r5_Pid;
        #加入订单ID
        $sbOld = $sbOld . $r6_Order;
        #加入用户ID
        $sbOld = $sbOld . $r7_Uid;
        #加入商家扩展信息
        $sbOld = $sbOld . $r8_MP;
        #加入交易结果返回类型
        $sbOld = $sbOld . $r9_BType;
        return $this->HmacMd5($sbOld, $merchantSecret);
    }

    /**
     * 设置返回类型
     * @param string $type
     */
    function setReturnType($type = 'HTML')
    {
        // TODO: Implement setReturnType() method.
        $this->returnType = $type;
    }

    /**
     * 发起支付函数
     */
    function goPay()
    {
        $this->debug = 0;
        $this->method = "POST";
        $this->prePay();
    }

    /**
     * 签名函数
     * @param $param
     * @param $merchantSecret
     * @return string
     */
    protected function HmacMd5($param, $merchantSecret)
    {
        $key = iconv("GB2312", "UTF-8", $merchantSecret);
        $data = iconv("GB2312", "UTF-8", $param);
        $b = 64; // byte length for md5
        if (strlen($key) > $b) {
            $key = pack("H*", md5($key));
        }
        $key = str_pad($key, $b, chr(0x00));
        $ipad = str_pad('', $b, chr(0x36));
        $opad = str_pad('', $b, chr(0x5c));
        $k_ipad = $key ^ $ipad;
        $k_opad = $key ^ $opad;
        return md5($k_opad . pack("H*", md5($k_ipad . $data)));
    }

    /**
     * 发起支付签名字符串
     * @param $p2_Order
     * @param $p3_Amt
     * @param $p4_Cur
     * @param $p5_Pid
     * @param $p6_Pcat
     * @param $p7_Pdesc
     * @param $p8_Url
     * @param $pa_MP
     * @param $pd_FrpId
     * @param $pr_NeedResponse
     * @param $p0_Cmd
     * @param $p9_SAF
     * @param $p1_MerId
     * @param $merchantKey
     * @return mixed
     */
    protected function getReqHmacString($p2_Order, $p3_Amt, $p4_Cur, $p5_Pid, $p6_Pcat, $p7_Pdesc, $p8_Url, $pa_MP, $pd_FrpId, $pr_NeedResponse, $p0_Cmd, $p9_SAF, $p1_MerId, $merchantKey)
    {
        #进行签名处理，一定按照文档中标明的签名顺序进行
        $sbOld = "";
        #加入业务类型
        $sbOld = $sbOld . $p0_Cmd;
        #加入商户编号
        $sbOld = $sbOld . $p1_MerId;
        #加入商户订单号
        $sbOld = $sbOld . $p2_Order;
        #加入支付金额
        $sbOld = $sbOld . $p3_Amt;
        #加入交易币种
        $sbOld = $sbOld . $p4_Cur;
        #加入商品名称
        $sbOld = $sbOld . $p5_Pid;
        #加入商品分类
        $sbOld = $sbOld . $p6_Pcat;
        #加入商品描述
        $sbOld = $sbOld . $p7_Pdesc;
        #加入商户接收支付成功数据的地址
        $sbOld = $sbOld . $p8_Url;
        #加入送货地址标识
        $sbOld = $sbOld . $p9_SAF;
        #加入商户扩展信息
        $sbOld = $sbOld . $pa_MP;
        #加入支付通道编码
        $sbOld = $sbOld . $pd_FrpId;
        #加入是否需要应答机制
        $sbOld = $sbOld . $pr_NeedResponse;
        return $this->HmacMd5($sbOld, $merchantKey);
    }

}