<?php
namespace common\pay\kexing;

use Yii;
use yii\helpers\VarDumper;

class PayUtils
{

    /**
     * @param array $params
     * @param string $priCert
     * @return string
     */
    public static function makeSign($params, $priCert)
    {
		ksort($params);    
        $temp =  '';
        foreach($params as $key=>$value)
        {
            $temp = $temp . $key . '=' . $value . '&';
        }	
		$temp = substr($temp, 0,  strlen($temp) -1 );
		$priKey = openssl_get_privatekey(file_get_contents($priCert));
        openssl_sign($temp, $sign, $priKey, OPENSSL_ALGO_SHA1);
        $sign = base64_encode($sign);
        return $sign;
    }


    /**
     * @param array $data
     * @param $pubCert
     * @return bool|int
     */
    public static function verify($data, $pubCert)
    {
        // 签名
        if (!isset($data['signature']) || trim($data['signature']) === '') {
            return false;
        }
		$sign = $data['signature'];
        unset($data['signature']);
		ksort($data);   
		$temp =  '';
		foreach($data as $key=>$value)
		{
			$temp = $temp . $key . '=' . $value . '&';
		}
		$temp = substr($temp, 0,  strlen($temp) -1 );	
        $pubKey = openssl_get_publickey(file_get_contents($pubCert));
		return openssl_verify($temp, base64_decode($sign), $pubKey, OPENSSL_ALGO_SHA1);
   
    }
	
	/**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    public static function sendPost($url, $post_data) {

        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }
}