<?php

namespace App\Libs\Pay\Merchants;

use GuzzleHttp\Client;
use Log;

/**
 *  市民卡支付
 */
class SmkPay {

	private $merchant_key;
	private $merchant_id;
	private $appid;
    private $private_key_path;
    private $private_key_pass;
    private $notify_cer_path;
	function __construct($config)
	{
        $this->appid = $config['appid'];
        $this->merchant_id = $config['merCode'];
        $this->private_key_path = $config['private_key_path'];
        $this->private_key_pass = $config['private_key_pass'];
        $this->notify_cer_path = $config['notify_cer_path'];
	}

	//订单发送
	function send($data)
	{
		$client = new client(['base_uri'=>'https://hpay.96225.com/','timeout'=>3]);
		//订单金额最小10分
        $price = max($data['price'],10);

		$data = [
		    'version'=>'2.0.0',
            'transCode'=>'AGGP0001',
            'merCode'=>$this->merchant_id,
            'chainNo'=>'004',
            'orderNo'=>$data['trade_no'],
            'dateTime'=>date('YmdHis'),
            'timeOut'=>date('YmdHis',time()+1800),
            'currency'=>'156',
            'txName'=>'novel',
            'amount'=>(string)sprintf("%.2f",$price/100),
            'deviceType'=>'MW',
            'payType'=>'WECHAT-OA',
            'goods'=>$data['body'],
            'notifyUrl'=>env('SMK_PAY_CALL_BACK_URL'),
            'returnUrl'=>env('SMK_PAY_CALL_BACK_URL'),
            'promoParams'=>'{"storeIdType":"1"}',
            'ip'=>$data['create_ip'],
            'outputType'=>'',
            'merCustId'=>'',
            'merAppname'=>'novel',
            'merAppid'=>'http://www.imycmh.com',
            'remark1'=>'',
            'remark2'=>'{"openid":"'.$data['openid'].'","appid":"'.$this->appid.'"}'
		];
		$data['sign'] = $this->sign($data);
		try {
		    $header = ['Content-Type'=>'application/x-www-form-urlencoded;charset=utf-8'];
            $response = $client->request('POST', "HzsmkAggPay/api/aggpay", ['form_params' => $data,'headers'=>$header])->getBody()->getContents();
            Log::info($data);
            Log::info($response);
            return $this->getPayInfo($response);
        }catch (\Exception $e)
        {
            Log::ERROR('smkpay REQUEST FAIL :'.json_encode($data));
            Log::ERROR($e->getMessage());
        }
	}

	//RSA签名
    public function  sign($data)
    {
        $sign_str = '';
        foreach ($data as $k=>$v)
        {
            $sign_str.= $k.'='.$v.'&';
        }
        Log::info('sign_str');
        Log::info($sign_str);
        $sign_str = rtrim($sign_str, '&');

        $sign_str = iconv('UTF-8','GBK', $sign_str);
        $pfxpath = storage_path($this->private_key_path);
        $cer_key = file_get_contents($pfxpath); //获取密钥内容

        openssl_pkcs12_read($cer_key, $certs, $this->private_key_pass);
        openssl_sign($sign_str, $signMsg, $certs['pkey'],OPENSSL_ALGO_SHA1); //注册生成加密信息
        return base64_encode($signMsg); //base64转码加密信息
    }

    //验签
    public function checkSign($data, $signature)
    {
        $to_sign_data = [
            'reqSeq'=>$data['reqSeq'],
            'merCode'=>$data['merCode'],
            'serialNo'=>$data['serialNo'],
            'orderNo'=>$data['orderNo'],
            'amount'=>$data['amount'],
            'status'=>$data['status'],
            'respCode'=>$data['respCode'],
            'respDesc'=>$data['respDesc']
        ];
        $sign_str = '';
        foreach ($to_sign_data as $k=>$v)
        {
            $sign_str.= $k.'='.$v.'&';
        }

        $sign_str = rtrim($sign_str, '&');
        $sign_str = iconv('UTF-8','GBK', $sign_str);
        $signature = iconv('UTF-8','GBK', $signature);

        $cer_path = storage_path($this->notify_cer_path);
        $cer_key = openssl_get_publickey(file_get_contents($cer_path)); //获取密钥内容
        return (bool)openssl_verify($sign_str, base64_decode($signature),$cer_key);
    }

	function getPayInfo($response)
	{
        $res = json_decode($response, 1);
        if ($res['respCode'] == '00') {
            $pay_info = json_decode($res['tn'], 1);

            return [
                'appId' => $pay_info['appId'],
                'package' => $pay_info['package'],
                'nonceStr' => $pay_info['nonceStr'],
                'timeStamp' => $pay_info['timeStamp'],
                'signType' => $pay_info['signType'],
                'paySign' => $pay_info['paySign'],
            ];
        }else{
            Log::ERROR('smkpay FAIL');
            Log::ERROR($response);
        }
	}

	

}