<?php


namespace Modules\Wechat\Utils;


class WechatUtil
{

	/**
	 * @notes 敏感信息加解密
	 */
	public static function getEncrypt($user_name,$cert_path)
	{
		//$str是待加密字符串
		$public_key = file_get_contents($cert_path);
		$encrypted = '';
		if (openssl_public_encrypt($user_name, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
			//base64编码
			$sign = base64_encode($encrypted);
		} else {
			throw new \Exception('encrypt failed');
		}
		return $sign;
	}

	/**
	 * 敏感信息解密
	 * @param $str
	 * @return string
	 * @throws Exception
	 */
    public static function getDecrypt($data,$cert_path_key) {
		$private_key = file_get_contents($cert_path_key);
		$encrypted = '';
		if (openssl_private_decrypt($data, $encrypted, $private_key, OPENSSL_PKCS1_OAEP_PADDING)) {
			//base64编码
			$sign = $encrypted;
		} else {
			throw new \Exception('解密失败');
		}
		return $sign;
	}

	/**
	 * @notes 获取签名
	 */
	public static function getToken($url, $http_method, $data,$mch_id,$wxpayCert,$wxPayCertKey)
	{
		$timestamp   = time(); //请求时间戳
		$url_parts   = parse_url($url); //获取请求的绝对URL
		$nonce       = $timestamp . rand('10000', '99999'); //请求随机串
		$body        = empty($data) ? '' : json_encode((object)$data); //请求报文主体
		$stream_opts = [
			"ssl" => [
				"verify_peer" => false,
				"verify_peer_name" => false,
			]
		];

		$apiclient_cert_arr = openssl_x509_parse(file_get_contents($wxpayCert, false, stream_context_create($stream_opts)));
		$serial_no          = $apiclient_cert_arr['serialNumberHex']; //证书序列号
		$mch_private_key    = file_get_contents($wxPayCertKey, false, stream_context_create($stream_opts)); //密钥
		$merchant_id = $mch_id; //商户id
		$canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
		$message = $http_method . "\n" .
			$canonical_url . "\n" .
			$timestamp . "\n" .
			$nonce . "\n" .
			$body . "\n";
		openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
		$sign = base64_encode($raw_sign); //签名
		$schema = 'WECHATPAY2-SHA256-RSA2048';
		$token = sprintf(
			'mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
			$merchant_id,
			$nonce,
			$timestamp,
			$serial_no,
			$sign
		); //微信返回token
		return $schema . ' ' . $token;
	}

	/**商家转账到零钱
	 * @notes 新发送请求
	 */
	public static function https_request_transfer($url, $data, $token,$serial_no='')
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, (string)$url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//添加请求头
		$headers = [
			'Authorization:' . $token,
			'Wechatpay-Serial: '.$serial_no,
			'Accept: application/json',
			'Content-Type: application/json; charset=utf-8',
			'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
		];

		if (!empty($headers)) {
			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		}
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}


}