<?php

/**
 * Description of config_vivo
 * @version
 *          1.0.0 Created at 2018-3-3. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2018-3-3, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
class config_sanxing {

    /**
     * @var string 验证登录token接口 URI
     */
    public $sanxing_api_login = 'https://siapcn1.ipengtai.com/api/oauth/get_token_info';

    /**
     * @var string 三星后台创建订单接口 URI
     */
    public $sanxing_api_trade = 'http://siapcn1.ipengtai.com:7002/payapi/order';
//put your code here

    /**
     * @var string sanxing 后台应用ID
     */
    public $appId = '500151089';

    /**
     * @var string 三星平台客户端包名
     */
    public $packageName = "com.loyalsoft.ylsj.samsung";

    /**
     * @var string sanxing 后台开发商ID
     */
    public $cpId = 'a8f45473e4699ba87f96';

    /**
     * @var string sanxing 后台应用 appkey
     */
    public $appKey = '3a1090587b91686582f5e3e6ecfe58b0';
//cp公钥 公钥
    public $cppkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwDqNB3fC2FbmINIIOKq/4EjEqHnxlox2A4XybCGHAz1hwbthNKjYlIukmoQ0SKc3x7lmP0i9JBD3QHec1qve2BIdnzEIM1I5SfNAvinekMIFH7ECrqxReeHt4KlzBQdNZ8VdK0zxeeOTBAdaJJVlqS5ExS8F917rSClpMSevoBQIDAQAB";

    /**
     * @var type cp私钥
     */
    public $cpvkey = "MIICXAIBAAKBgQCmzt5jLDQh59ynaO/ypcSMXvPPrZ6bN5Stv1kiGOd4rO9tYhMjZAXNXohMYCfKahzgO1LKrg5F+XQ9AXmBkwYvcsUPOiKzXG7TCUyUUNatf6mWowK5Suwr6fzBBzmbOf4ZgAGMrHT6UCRe8XocmbmqFZ+1KG53HSdfhjcGxTDDHwIDAQABAoGAB52KKZzrBGFBgaMY0UsgHgh3uROEGjH/Z69EsnnQl4HNrIC9vu/iE+4s6s+5AVS23MXYkchAfpFU7TQUCAZeUdkFFyLtjHqBep75jKkVhOgKIYlKbTmfJCNcFWSf16d4KYLbHKK2wcHOWvD/YC04HILjErboFRQktG7sBm1/SoECQQD6DcgRl43Fn/f2Q2jf9jqQwc/Yx9TSAEkMMWiIofSDLAydHiH9oFs5Pw27WubIN9pQCH6DMirXQwgN5nyBXQbtAkEAqsZSyw1AR5Trdp1ktoIpN4s8OtUHuDSiT2apNDgkCPmqvuYyvZlfYi4m1AqTM11irlp/t3o+5/bGDCAq/YUEuwJBAJfUIGPWIuYZMKVd3uMGDh9xHvPgui9crv3xTiiQNfgjmfEYp8jpQhqrV3ooQrLVfwBTeAXPQ0X7VHukNHsT8i0CQDF10SLYCqbwvaWT/khRuGhK3j3X1y2FqQDAJf9mxyEGVmqFt2psUlDYNwywp2N4B42hzl2wfSmnskJuyqS0cuMCQCwg0tWcYjhFKmu1deNxTgaP6C3hNO9b3yD9+EbbRCsEPR2TrreG8iVW9mu5PEyIo5h6Ty2CFxEY+vxCMvtGpWE=";

    /**
     * @var type 平台公钥
     */
    public $platpkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCBD5ksV+NwPjC2X/zKbFRl6J0zFyYV6Zb210FeD5XaPEuAysdo4T54eEh425z5z62nkgJ7Qwkd6pgSNgSOcnAVBfuHn3B9i9sQtwSSMpxt+EhaZBIv5YoR7yFUApjSBnQ6pdizlOIyIs7+fYecQYiBiVf7Txu75T85gl+kFwhbswIDAQAB";

    /**
     * 从product_id获得三星后台商品ID
     * @param type $product_id
     * @return string
     */
    function getWaresid($product_id) {
        $arr = array(
            '801801' => 1,
            '801802' => 2,
            '801803' => 3,
            '801804' => 4,
            '801805' => 5,
            '801806' => 6
        );
        return $arr[$product_id];
    }

    /**
     *  从三星后台商品ID转到product_id
     * @param type $samsungWaresid
     * @return string
     */
    function getProductId($samsungWaresid) {
        $itemMap = array(
            '1' => '801801',
            '2' => '801802',
            '3' => '801803',
            '4' => '801804',
            '5' => '801805',
            '6' => '801806'
        );
        return $itemMap[$samsungWaresid];
    }

    /**
     *
     * @return \config_vivo
     */
    static public function Inst() {
        return new config_sanxing();
    }

    /** 格式化公钥
     * $pubKey PKCS#1格式的公钥串
     * return pem格式公钥， 可以保存为.pem文件
     */
    static function formatPubKey($pubKey) {
        $fKey = "-----BEGIN PUBLIC KEY-----\n";
        $len = strlen($pubKey);
        for ($i = 0; $i < $len;
        ) {
            $fKey = $fKey . substr($pubKey, $i, 64) . "\n";
            $i += 64;
        }
        $fKey .= "-----END PUBLIC KEY-----";
        return $fKey;
    }

    /** 格式化公钥
     * $priKey PKCS#1格式的私钥串
     * return pem格式私钥， 可以保存为.pem文件
     */
    static function formatPriKey($priKey) {
        $fKey = "-----BEGIN RSA PRIVATE KEY-----\n";
        $len = strlen($priKey);
        for ($i = 0; $i < $len;
        ) {
            $fKey = $fKey . substr($priKey, $i, 64) . "\n";
            $i += 64;
        }
        $fKey .= "-----END RSA PRIVATE KEY-----";
        return $fKey;
    }

    /** RSA签名
     * $data待签名数据
     * $priKey商户私钥
     * 签名用商户私钥
     * 使用MD5摘要算法
     * 最后的签名，需要用base64编码
     * return Sign签名
     */
    static function sign($data, $priKey) {
        $res = openssl_get_privatekey($priKey);                    //转换为openssl密钥
        openssl_sign($data, $sign, $res, OPENSSL_ALGO_MD5);        //调用openssl内置签名方法，生成签名$sign 
        openssl_free_key($res);                                    //释放资源
        $sign = base64_encode($sign);                              //base64编码
        return $sign;
    }

    /** RSA验签
     * $data待签名数据
     * $sign需要验签的签名
     * $pubKey爱贝公钥
     * 验签用爱贝公钥，摘要算法为MD5
     * return 验签是否通过 bool值
     */
    static function verify($data, $sign, $pubKey) {
        $res = openssl_get_publickey($pubKey);                   //转换为openssl格式密钥
        $result = (bool) openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_MD5); //调用openssl内置方法验签，返回bool值
        openssl_free_key($res);                                 //释放资源
        return $result;                                         //返回资源是否成功
    }

    /**
     * 组装request报文
     * $reqJson 需要组装的json报文
     * $vkey  cp私钥，格式化之前的私钥
     * return 返回组装后的报文
     */
    function composePayReq($reqJson) {
        $content = json_encode($reqJson);                                       # 获取待签名字符串
        $vkey = self::formatPriKey($this->cpvkey);                              # 格式化key，建议将格式化后的key保存，直接调用
        $sign = self::sign($content, $vkey);                                    # 生成签名
        $reqData = "transdata=" . urlencode($content) . "&sign=" . urlencode($sign) . "&signtype=RSA"; //组装请求报文，目前签名方式只支持RSA这一种s
        return $reqData;
    }

    /**
     * 组装request报文
     * $reqJson 需要组装的json报文
     * $vkey  cp私钥，格式化之前的私钥
     * return 返回组装后的报文
     */
    function composeReq($data) {
        $vkey = self::formatPriKey($this->cpvkey);                              # 格式化key，建议将格式化后的key保存，直接调用
        ksort($data);
        $content = loyalsoft\HttpUtil::makeQueryString($data);
        $sign = self::sign($content, $vkey);                                    # 生成签名
        $reqData = $content . "&sign=" . urlencode($sign);                      # 组装请求报文，目前签名方式只支持RSA这一种s
        return $reqData;
    }

    /**
     * 解析response报文
     * $content  收到的response报文
     * $pkey     爱贝平台公钥，用于验签
     * $respJson 返回解析后的json报文
     * return    解析成功TRUE，失败FALSE
     */
    function parseResp($content, &$respJson) {
        $arr = array_map(create_function('$v', 'return explode("=", $v);'), explode('&', $content));
        foreach ($arr as $value) {
            $resp[($value[0])] = urldecode($value[1]);
        }
        if (array_key_exists("transdata", $resp)) {                //解析transdata
            $respJson = json_decode($resp["transdata"]);
        } else {
            return FALSE;
        }
        if (array_key_exists("sign", $resp)) {                     //验证签名，失败应答报文没有sign，跳过验签
            $pkey = self::formatPubKey($this->platpkey);                     //校验签名 
            return self::verify($resp["transdata"], $resp["sign"], $pkey);
        } else if (!array_key_exists("errmsg", $respJson)) {
            return FALSE;
        }
        return TRUE;
    }

    /**
     * @param type $str
     * @return type 给字符串签名
     */
    function getSign($str) {
        $vkey = self::formatPriKey($this->cpvkey);                //格式化key，建议将格式化后的key保存，直接调用
        return self::sign($str, $vkey);                       //生成签名
    }

}
