<?php

namespace Shop\Src;

use Dever;
use Main\Lib\Core;

class Yspay
{
	public function test()
	{
		
		$class = new Chinaums();

		# 查看当前余额
		$cash = $class->query('89810007372107C');

		echo $cash;die;
		return $cash;
	}

	public function act()
	{
		$order = Dever::order();

		$result = $this->action('89810007372107C', $order, 2, 127);

		return $result;
	}

	public function action($mid, $order, $type, $cash)
	{
		$class = new Chinaums();

		$notify = Dever::url('yspay.notify?order=' . $order, 'shop');

		$result = $class->act($mid, $order, $type, $cash, $notify);

		return $result;
	}

	public function notify()
	{
		$msg = Dever::input();
		Dever::log($msg, 'yspay');
		$order = $msg['order'];

        if (!$order) {
            echo 'FAILED';die;
        }
		$where['order_num'] = $order;
		$order = Dever::db('shop/sell_order')->find($where);
		$class = new Chinaums();

		if ($order && $order['withdraw'] == 1) {
			$content = $msg['content'];

			$content = $class->privateDecrypt($content);

			if ($content && isset($content['responseCode']) && ($content['responseCode'] == '000000' || $content['responseCode'] == '000001')) {
				Dever::db('shop/sell_order')->update(array('where_id' => $order['id'], 'withdraw' => 2));
                echo 'SUCCESS';die;
			} else {
				Dever::load('shop/lib/cron')->yspayOne($order);
			}
		}

        echo 'FAILED';die;
	}
}

/**
 * 银联商务代付
 * Class Chinaums
 */
class Chinaums
{
	//测试地址
	protected $test_host = 'https://mobl-test.chinaums.com/';

	//正式地址
	protected $host = 'https://managefree.chinaums.com/';

    //系统编号（sysId）
    protected $sys_id = '10119';

    //商户号
    protected $mch_id = '89810007372106N';

    //外部平台私钥
    protected $private_key = 'MIIEowIBAAKCAQEApzpOtvWGclmdw+/aEzAxwyTgUwnC9qjQEhL+qfMWDBIbFR8N4q6GQ8fRKZ9Zyvm0voFhgpH44Y6sh2U7rF9HQOuw2puywvU8kk5JAUxpxykbH7QqW/ijH1gBG3Ck/Ip/5I4co+q9K/CjQRmId5nSJ8ffnaiAOogNZycrP+AgEEU8vL1eNtnagVxT3EC1LEh0wBwecT9Tkyi0tMD0sMeIUl9POrnh7YADJtUzGf+TTNrqK6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8tPzeZ6mPdvO1sJHpiq7TR0aVwZecQVOiDKUQX8LukRlwF810c1QPQVeY93XLle/LyGmoLBlKMzwlujw0MQKBgDZT/egpnQM3x4TR9ERrk0o5GOLHNFiNkSfkzzZ3D2nRGT+6GRlmb40LtPzBy5+vAgLqBlfEEfToaMGZ+Vrl2CePBBoR/j/q8nlziqZ3H5b8plqHSbX85zONT6tF+YZ2nRMxpI2gQtecRzoozm+ilELCNSd6V7pAzpl14KRU2V5l';

    //外部平台PKCS1私钥（银联商务提供的PKCS8格式需转为PKCS1格式）
    protected $private_key_pkcs1 = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCnOk629YZyWZ3D79oTMDHDJOBTCcL2qNASEv6p8xYMEhsVHw3iroZDx9Epn1nK+bS+gWGCkfjhjqyHZTusX0dA67Dam7LC9TySTkkBTGnHKRsftCpb+KMfWAEbcKT8in/kjhyj6r0r8KNBGYh3mdInx9+dqIA6iA1nJys/4CAQRTy8vV422dqBXFPcQLUsSHTAHB5xP1OTKLS0wPSwx4hSX086ueHtgAMm1TMZ/5NM2uoroOGhP2YTc+XDSmrEpKTj+0c3HVkhd/gj9R5hIQCt5cdZV8tD+J/UL0dFiEQYHnuaaqfQl2axJEPsNft5Ts6Nr5Gq1Z9D8of7Z+eOr25LAgMBAAECggEAEAJS+szyfAv8QH+7vs6EVQw4tXpfwcFTegd7fcWZvLoXAaShbawLin2cloF81SOmm/5C2X8j9mP0PFoCpnPQnHRzz9nL+UIE9HSuJIOuNLTItfZHf9qDs0J3iKr2AH850yWPtFmKlqRI3LiXCewd5FUMIUm6TOAteEyVpV3NdAElN0RE/cbwD2/DG69s4TereQcJNZ6lVh3cp0RDmsM+tiH8fB9UHa1ZKd7tn826u61bmosDpqIkZwOgXsfjUWK3zPDVAOfAk2+xR5H884UUPTOiDv5mkxfc6InAUoFl9M2/Mm0feaSqc3rYknCkk2pNMxZ19LOIWVA0noasKqFrEQKBgQDVJMnPQYALu2Gj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E987kXYK209uFcte+Y8YofQ2AYamImpzSf7pXomAu+8D98HIOs5bKITHTk30vPdNhrQdpDRO1TuX0x8bwhCykcwAEdB/Z9YGXkLU5S3QJY2qvCZJY08YdNqIpbDqifSRvOg0sqeKFXPfI2M0GsOh6PArTEmh0QHxDht9xjPPt11aVgh8kgkQIDAQAB';

    private function host()
    {
    	return $this->host;
    }

    # 查询余额
    public function query($mid)
    {
    	$url = $this->host() . 'uisouterfront/qrywithdrawbalance/process';

        $mid = $mid ? $mid : $this->mch_id;
    	//整理内容信息
        $content = [
            'sysId' => $this->sys_id,
            'mchntNo' => $mid,
            'timestamp' => date('YmdHis'),
        ];
        //设置签名并加密
        $body['content'] = $this->createSignature($content);

        $result = Dever::curl($url, $body, 'post');

        $decryptData = $this->privateDecrypt($result);
        print_r($content);
        print_r($decryptData);die;

        if (isset($decryptData['tzWithdrawAmtPublic'])) {
        	return $decryptData['tzWithdrawAmtPublic'];
        } elseif (isset($decryptData['t0WithdrawAmtPublic'])) {
        	return $decryptData['t0WithdrawAmtPublic'];
        }

        return 0;
    }

    # 提现
    public function act($mid, $order, $type = 2, $cash = 1, $notify = '')
    {
    	$url = $this->host() . 'uisouterfront/withdrawback/process';

    	$mid = $mid ? $mid : $this->mch_id;
    	$type = (string) $type;
		$cash = (string) $cash;

    	//整理内容信息
        $content = [
            'sysId' => $this->sys_id,
            'mchntNo' => $mid,
            'timestamp' => date('YmdHis'),
            'sysOrderId' => $order,
            'responseUrl' => $notify,
            'withdrawType' => $type,
            'withdrawAmt' => $cash,
        ];
        //设置签名并加密
        $body['content'] = $this->createSignature($content);

        $result = Dever::curl($url, $body, 'post');
        $decryptData = $this->privateDecrypt($result);
        if (isset($decryptData['responseCode']) && ($decryptData['responseCode'] == '000000' || $decryptData['responseCode'] == '000001')) {
        	return 'ok';
        } else {
        	return $decryptData['responseDesc'];
        }
    }

    /**
     * 私钥解密
     * @Author Abnermouke <abnermouke@gmail.com>
     * @Originate in Abnermouke's MBP
     * @Time 2021-08-26 16:36:58
     * @param $encryptData
     * @return string
     */
    public function privateDecrypt($encryptData)
    {
        $content = pack('H*', $encryptData);
        $result = '';
        foreach (str_split($content, 256) as $block) {
            openssl_private_decrypt($block, $dataDecrypt, $this->formatRsaKey($this->private_key_pkcs1), OPENSSL_PKCS1_PADDING);
            $result .= $dataDecrypt;
        }
        $result = Dever::json_decode($result);
        return $result;
    }

    /**
     * 创建签名
     * @Author Abnermouke <abnermouke@gmail.com>
     * @Originate in Abnermouke's MBP
     * @Time 2021-08-26 16:34:49
     * @param $body
     * @return false|string
     */
    private function createSignature($body)
    {
        //重新排序信息
        ksort($body);
        //整理加密字符串
        $signature_string = '';
        //循环数据
        foreach ($body as $key => $value) {
            //整合字符串
            $signature_string .= $key.'='.$value.'&';
        }
        //整理加密字符串
        $signature_string = rtrim($signature_string, '&');
        //获取加密数组
        $array_json = $this->rsaEncrypt($signature_string);
        //设置签名
        $body['sign'] = bin2hex($array_json);

        //print_r($body);
        //json序列化
        $json_data = json_encode($body);
        //加密RSA
        $json_rsa = $this->publicRsa($json_data);
        //返回结果
        return $json_rsa;
    }

    /**
     * 私钥加密
     * @Author Abnermouke <abnermouke@gmail.com>
     * @Originate in Abnermouke's MBP
     * @Time 2021-08-26 16:35:08
     * @param string $str
     * @return false
     */
    private function rsaEncrypt($str=''){
        $charSet = mb_detect_encoding($str, ["UTF-8", "GB2312", "GBK"]);
        $str = mb_convert_encoding($str, "UTF-8", $charSet);
        $pri_key = $this->private_key;
        $pri_key = $this->formatRsaKey($pri_key, 'RSA PRIVATE');
        $pi_key = openssl_pkey_get_private($pri_key);
        if(!$pi_key) return false;
        $algo = "SHA256";
        openssl_sign($str, $binary_signature, $pi_key, $algo);
        return $binary_signature;
    }

    /**
     * 公钥加密
     * @Author Abnermouke <abnermouke@gmail.com>
     * @Originate in Abnermouke's MBP
     * @Time 2021-08-26 16:35:14
     * @param string $str
     * @return false|string
     */
    private function publicRsa($str='')
    {
        $charSet = mb_detect_encoding($str, ["UTF-8", "GB2312", "GBK"]);
        $str = mb_convert_encoding($str, "UTF-8", $charSet);
        $pub_key = $this->public_key;
        $pub_key = $this->formatRsaKey($pub_key, 'PUBLIC');
        $pu_key = openssl_pkey_get_public($pub_key);
        if(!$pu_key)  return false;
        $result = '';
        foreach (str_split($str,245) as $chunk) {
            if(openssl_public_encrypt($chunk,$encryptData, $pub_key)){
                $result .= $encryptData;
            }
        }
        $result = bin2hex($result);
        openssl_free_key($pu_key);
        return $result;
    }

    /**
     * 格式化密钥
     * @Author Abnermouke <abnermouke@gmail.com>
     * @Originate in Abnermouke's MBP
     * @Time 2021-08-26 16:36:36
     * @param $key
     * @param string $alias
     * @param int $length
     * @return string
     */
    private function formatRsaKey($key, $alias = 'RSA PRIVATE', $length = 64)
    {
        //拆分格式
        $key = chunk_split($key, (int)$length, "\n");
        //生成pem
        $pem = "-----BEGIN $alias KEY-----\n".$key."-----END $alias KEY-----";
        //返回pem
        return $pem;
    }

}
