<?php

namespace Home\Api;

class WXcash{
    private $params;
    private $res;
    public function __construct($id){
        $this->params['nonce_str'] = $this->getRandChar(32);
        $this->params['mch_id'] = '1384123802';
        $this->params['mch_billno'] = $id;
        $this->params['wxappid'] = 'wx8e5787326363f877';
        $this->params['nick_name'] = '卡士520·爱在一起照片挑战';
        $this->params['send_name'] = '卡士特别专送';
        $this->params['total_num'] = '1';
        $this->params['wishing'] = '卡士520·爱在一起';
        $this->params['client_ip'] = '21.42.11.44';
		$this->params['act_name'] = '卡士520·爱在一起';
        $this->params['remark'] = '如参与人数较多,可能会造成红包发放延迟现象，请耐心等待';
        //$this->params['logo_imgurl'] = 'https://czbank-tp.dev.izhida.cn/img/swipe-icon.png';
        $this->params['share_content'] = '';
        //$this->params['share_imgurl'] = 'https://wx.gtimg.com/mch/img/ico-logo.png';

    }
    function resend( $tickno ){
        $this->params['mch_billno'] = $tickno;
    }
    function send( $openid , $moneyNum ){
        $this->params['total_amount'] = $moneyNum;
        $this->params['min_value'] = $moneyNum;
        $this->params['max_value'] = $moneyNum;

            $this->params['re_openid'] = $openid;
        $this->makeSign();
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $xml = $this->ToXml();
        $res = self::postXmlCurl( $xml , $url );
        $this->res = $res;
        return $res;
    }
    function getReturnCode(){
        if(!$this->res){
            throw new WxPayException("xml数据异常！");
        }
        //将XML转为array
        $array = json_decode(json_encode(simplexml_load_string($this->res, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array;
    }
    function getTickNo(){
        return $this->params['mch_billno'];
    }
    private function ToXml(){
        if(!is_array($this->params)
            || count($this->params) <= 0)
        {
            throw new WxPayException("数组数据异常！");
        }

        $xml = "<xml>";
        foreach ($this->params as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    private static function postXmlCurl($xml, $url, $useCert = true, $second = 30){
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);


        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if($useCert == true){
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, __DIR__.'/WXDATA/zhida_apiclient_cert.pem');
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, __DIR__.'/WXDATA/zhida_apiclient_key.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new WxPayException("curl出错，错误码:$error");
        }
    }
    private function makeSign(){
        $key = 'D5FA3597D4D8A378179869AFD5E985C8';

        ksort($this->params);
        $stringA = $this->ToUrlParams();

        $stringSignTemp=$stringA.'&key='.$key;
        $this->params['sign'] = strtoupper(strtoupper( md5( $stringSignTemp) ));

    }
    public function ToUrlParams(){
        $buff = "";
        foreach ($this->params as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
    private function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }

        return $str;
    }
}