<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/21
 * Time: 18:24
 */

namespace Biz\Pay\Payment;

use Biz\Pay\NewBasePayment;

class KuaibeiPayment extends NewBasePayment
{

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

    /**
     * 接收通知
     * @param array $data
     * @return void [type] [description] 返回为1或success视接口而定
     */
    function notify(array $data)
    {
        //验证签名后返回对端服务器需要的响应内容
        $param = array(
            'api_id' => strip_tags($data['api_id']),
            'orderid' => strip_tags($data['orderid']),
            'orderuid' => strip_tags($data['orderuid']),
            'price' =>$data['price'],
            'realprice' =>$data['price'],
            'token' => '309990f0d5a24a5994b6ea72708272e7',
        );

        $order_no = $param['orderid'] ?? '';
        $price = $param['price'] ? $param['price'] : 0;
        $sign = strip_tags(trim($data['key']));
        $this->checkSign($param, $sign, $order_no, $price);
    }

    /**
     * 同步跳转
     * @param array $data
     * @return void [type] [description]
     */
    function redirect(array $data)
    {
        echo 'success';
    }

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

    /**
     * 构建订单提交数组
     * @return array
     */
    function buildOrder(): array
    {
        $orderInfo = [
            'istype' =>  $this->dataAccess->payType,
            'notify_url' => $this->notifyUrl,
            'orderid' =>  $this->dataAccess->orderSn,
            'orderuid' =>$this->paymentConfig['merchant_id'],
            'price' => number_format($this->dataAccess->money , 2, '.', ''),
            'return_url' =>$this->redirectUrl,
            'token'=>$this->paymentConfig['merchant_md5_secret'],
            'uid'=>$this->paymentConfig['merchant_id'],
        ];

        $sign = $this->buildSign($orderInfo,true);
        $orderInfo['key'] = $sign;
        $orderInfo['custno'] = 'wns888';

        return $orderInfo;
    }

    /**
     * 生成签名函数
     * @param array $param
     * @param string $merchantSecret
     * @return mixed
     */
    function buildSign(array $param,$key)
    {
        if (!is_array($param)) {
            return false;
        }
        $signStr = '';
        foreach ($param as $k => $v) {
            $signStr .= "{$v}";
        }
        return (md5($signStr));
    }

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

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

}
