<?php

namespace App\Http\Appadapter;

class PartySign
{
    private $secret = '';
    public function __construct($secret)
    {
        $this->secret =$secret;
    }

    /**
     * 发送POST请求
     *
     * @param unknown $url
     * @param unknown $data
     * @return boolean
     */
    public function api_notice_increment($url, $data)
    {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6);
        curl_setopt($ch, CURLOPT_TIMEOUT, 6);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        } else {
            return $tmpInfo;
        }

    }
    /**
     * 将数组$data进行签名
     *
     * 签名方式：md5
     *
     * @param array $data
     * @return String 签名结果
     */
    public function signString($data) {
        $data = is_array($data) ? $data : json_decode($data, true);

        $data = $this->arraytolower($data);
         ksort($data);    //根据键值对数组升序排序
        $content = '';
        foreach ($data as $k=>$val) {
            $content .= $k .'='. $val;
        }

        $content .= $this->secret;
        $token = md5($content);

        return $token;
    }

    /**
     * 验证签名
     * @param array $data
     * @return boolean
     */
    public function checkSignature($data)
    {
        if(isset($data['token'])) {
            $token = $data['token'];
        } else {
            return false;
        }
        unset($data['token']);

        $data = $this->arraytolower($data);
        ksort($data);    //根据键值对数组升序排序
        $content = '';
        foreach ($data as $k=>$val) {
            $content .= $k .'='. $val;
        }
        $content .= $this->secret;
        $mySignature = md5($content);

        if($mySignature == $token) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 将数组$array的key全部转换为小写
     */
    public function arraytolower($array) {
        $new = array();
        foreach ($array as $key=>$val) {
            $new[strtolower($key)] = $val;
        }
        return $new;
    }
}