<?php


namespace App\Services;


use http\Client\Curl\User;
use function GuzzleHttp\Psr7\build_query;

class Goopago
{

    protected $merchantOrder;
    protected $thirdUserId;
    protected $currency;
    protected $amount;


    public function getNonceStr( $length = 16 ) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= substr( $chars, mt_rand( 0, strlen( $chars ) - 1 ), 1 );
        }
        return $str;
    }


    /**
     * 充值
     * 传入数组进行HTTP POST请求
     * @param $url
     * @param array $post_data
     * @param int $timeout
     * @param string $header
     * @param string $data_type
     * @return bool|string
     */
    public function curlPost($url, $post_data = array(), $timeout = 120)
    {
        $header = [
            'Content-Type: application/json',
            'tmId:br_auto'
        ];

        $post_string = json_encode($post_data);

        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头

        $result = curl_exec($ch);

        curl_close($ch);
        return $result;
    }


    public function sign($data = [])
    {
        ksort($data);  //按照参数名ASCII码从小到大排序

        $payConfigService = new PayConfig();
        $config = $payConfigService->getConfig('Goopago');

        $md5key = $config['SecretKey'];  //md5密钥
        $str = '';
        foreach ( $data as $key => $val ) {
            if($val)
                $str .= $str ? '&' . $key . '=' . $val : $key . '=' . $val;
        }
        $str .= '&key=' . $md5key;
        return strtoupper(md5($str));  //拼接密钥后，md5加密后转为大写

    }





}
