<?php

namespace Shop\Src;

use Dever;
use Main\Lib\Core;

class Yspay
{
    public function t1()
    {
        $content = '0c62d6b7f1177314c9ee257915b20298fbf63e53e23a11ab728569370a1037132156a34e0c14d4201f08064e35be918c1e8b8dd2611bca1b6f1251acb399e2a84b644ab4def69d92
1b781970c0bea960ddbb3169d58ef8c7094a35d03ed110b7d75d5a9881aae448ea95f3355c28941fda2e43b3efbc21918faffefe4392a04b293ec8d6d709f5802aca91cdf7a597d837bcb8ad7464cba2434d65ffb6c63475405381cc56e83842c8ae462ab70653e40ea482b2980f683b9f263018eca
bfdc6069eaeb89ec0c4295f5230c13820a578f13ef0086d15a720ea2712ff2040f3ae09a8d3b8f125ff0c174da1b9b90abe18445c283c138126cbf1749097bcac6e197cc872983cd8cb32636e00b335325c60dd4480b7da012e8b1d5dfba885dad768f3f74597a1743a02fa21baddc177a00b4fb9cc
0fac04c11ce8404d92fced77eeb1808028e9bf24ff586f455cf0093829b592518797254d43357332eeca7bbf0b141f313fc72e503bd20dc2bfb1de2e6a22786c62e33b78a3308c3464089b51bdbc97368ed8a5c51d10a2bfeb1d88015abf9e042c72b74d167738359d278100f6df644d564174c1d92
051e206c4a80bbdf93ae102c02781089d1d526f8f6391590f9f4c8128ceb6a402c046746e8f1e341b72bbb5f3a818aa15726bd2930a190fef9d5b625f03020103c00526aa0e2d678f1601d20553d601dac686106c311586218bd446e23f55e19e6f5c322765ec9b88747a080cb8b9460dd91db4d47c
7b9a8e4873f4d319b56f0855a8209d3e2cb7edd84a043446dbc05dcf0fd2186d10653750b6db0e0f2c09dc583b3321021efffad62e6cfe5df4cca03429de98aed68bc15c054b99c08ad6c5a0a9ef1a8ae03caf052a7beda023aba98db8a796f889b180597aa899681f54a4b89498525ba24ce69d2d2
565175ab789410007fed227715c60f71304fd5dab209310f10a34ce1484dd76e4547fd2ff21f2a286e7f5c0b60a15274c1aaae47180a4b67dd7bedda2a04d6eb1cbec3331572bb1b311677189a337e1dd680f29ac3671ad4fea70c3d341999ba25acabecb03822c68d7f3a9bd7b09a4ce809f48f119
6cf39a10221c930b87bc43987b18bef819bf08e72a45b2969a54b27693f5d70260bb9adb93345454107c8c194e71c8612fdc13a663ff13184cb53833c21320cd0e66c61d54499b2b2ec3c188cb87bc2b61b50cda9d43b7d7bec1bef549c8dfa12e43eb9fb1004c1f43b988ac2e38d603df559fc467c
11398886f730494e7696645c99321fe4cb844b41267930da4c7b4622b6f260dc72b2eac1d7c4f6cfd41e6fd79cd50d7e4bfd6832e312e632847e8690288e4c51cddacea2521377bcab13209031442627d3ae55e5ff9c9ba2c19fd84814ec5ea221eed4d03c4703fa9d39f4c8c53202b858fbc4691c2
16fff191633c098221f22d21';
        $class = new Chinaums();

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

        print_r($content);die;
    }

	public function query()
	{
		# 查看当前余额
        $sid = Dever::input('sid');
		$cash = $this->query_action($sid);
		return $cash;
	}

    public function query_action($sid)
    {
        $class = new Chinaums();
        $data = $class->query($sid);

        return $data;
    }

    public function record()
    {
        # 查看提现记录
        $sid = Dever::input('sid');
        $start = Dever::input('start');
        $end = Dever::input('end');
        $log = $this->record_action($sid, $start, $end);

        return $log;
    }

    public function record_action($sid, $start, $end)
    {
        $class = new Chinaums();
        $log = $class->record($sid, $start, $end);

        return $log;
    }

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

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

		return $result;
	}

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

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

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

		return $result;
	}

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

        if (!$order) {
            echo 'FAILED';die;
        }
        if (strstr($order, 'SD')) {
             $log = Dever::db('shop/yspay_tixian_log')->one(array('order_num' => $order));

             if ($log) {
                Dever::db('shop/yspay_tixian_log')->update(array('where_id' => $log['id'], 'status' => 2, 'response' => Dever::json_encode($content)));

                $account = Dever::db('shop/yspay_account')->one(array('shop_id' => $log['shop_id']));
                if ($account) {
                    Dever::db('shop/yspay_account')->dec(array('where_id' => $account['id'], 'set_cash' => $log['cash']));
                }
            }
            echo 'SUCCESS';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);

            $log = Dever::db('shop/yspay_tixian_log')->one(array('order_num' => $order, 'shop_id' => $order['shop_id']));
			if ($content && isset($content['responseCode']) && ($content['responseCode'] == '000000' || $content['responseCode'] == '000001')) {
				Dever::db('shop/sell_order')->update(array('where_id' => $order['id'], 'withdraw' => 2));
                if ($log) {
                    Dever::db('shop/yspay_tixian_log')->update(array('where_id' => $log['id'], 'status' => 2, 'response' => Dever::json_encode($content)));

                    $account = Dever::db('shop/yspay_account')->one(array('shop_id' => $log['shop_id']));
                    if ($account) {
                        Dever::db('shop/yspay_account')->dec(array('where_id' => $account['id'], 'set_cash' => $log['cash']));
                    }
                }
                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+AgEEU8vL1eNtnagVxT3EC1LEh0wBwecT9Tkyi0tMD0sMeIUl9POr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/9znCz/1z6YxdKE9aioOa8tPzeZ6mPdvO1sJHpiq7TR0aVwZecQVOiDKUQX8LukRlwF810c1QPQVeY93XLle/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/Mm0feaSqc3rYknCkk2pNMxZ19LOIWVA0noasKqFrE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fCVs0/hMo6CKbdXVKqaE987kXYK209uFcte+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);
        if (isset($decryptData['tzWithdrawAmtPublic'])) {
        	return $decryptData['tzWithdrawAmtPublic'];
        } elseif (isset($decryptData['t0WithdrawAmtPublic'])) {
        	return $decryptData['t0WithdrawAmtPublic'];
        }

        return 0;
    }

    # 查询提现记录
    public function record($mid, $start, $end, $page = '1')
    {
        $url = $this->host() . 'uisouterfront/withdraw/qryWithDrawLog';

        $mid = $mid ? $mid : $this->mch_id;
        //整理内容信息
        $content = [
            'sysId' => $this->sys_id,
            'mchntNo' => $mid,
            'timestamp' => date('YmdHis'),
            'page' =>  (string) $page,
            'beginDate' => $start,
            'endDate' => $end,
        ];
        //设置签名并加密
        $body['content'] = $this->createSignature($content);
        $result = Dever::curl($url, $body, 'post');
        $result = Dever::json_decode($result);
        $decryptData = $this->privateDecrypt($result['result']);
        if (isset($decryptData['recordList']) && $decryptData['recordList']) {
            $data = Dever::json_decode($decryptData['recordList']);
            if ($page == 1 && isset($decryptData['totalPage']) && $decryptData['totalPage'] > 1) {
                for ($i = 2; $i <= $decryptData['totalPage']; $i++) {
                    $temp = $this->record($mid, $start, $end, $i);
                    if ($temp) {
                        $data = array_merge($data, $temp);
                    }
                }
            }
            return $data;
        }
        return array();
    }

    # 提现
    public function act($mid, $order, $order_id, $type = 2, $cash = 1, $notify = '', $order_info = array())
    {
    	$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,
        ];
        Dever::log($content, 'yspay_act');
        $data['shop_id'] = $order_info['shop_id'];
        $data['mid'] = $mid;
        $data['order_num'] = $order;
        $data['type'] = $type;
        $data['cash'] = $cash;
        $data['tdate'] = time();
        $data['status'] = 1;
        $data['desc'] = $order_info['desc'];
        $data['mtype'] = $order_info['mtype'];
        Dever::db('shop/yspay_tixian_log')->insert($data);
        //设置签名并加密
        $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 {
            if ($decryptData['responseDesc'] == '订单号已存在' && $order_id > 0) {
                Dever::db('shop/sell_order')->update(array('where_id' => $order_id, 'withdraw' => 2));
            }
        	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, '&');
        //echo $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;
    }

}
