<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/28
 * Time: 上午9:22
 */

namespace App\Libs\lianlianpay;


class llpaypayment
{
    //平台来源
    public static $platform = 'pay.zhuishuyun.com';
    //版本号
    public static $api_version = '1.0';
    //服务器异步通知地址
    public static $notify_url = 'http://47.97.120.133:8094/api/tradepayapi/receiveNotify.htm';
    //实时付款交易接口地址
    public static $llpay_payment_url = 'https://instantpay.lianlianpay.com/paymentapi/payment.htm';
    //查询付款结果
    public static $llpayPaymentQuery = 'https://instantpay.lianlianpay.com/paymentapi/queryPayment.htm';
    //账户余额查询
    public static $llPayTraderAcctQuery = "https://traderapi.lianlianpay.com/traderAcctQuery.htm";

    /**
     * 连连代付
     * @param $transactionSerialNumber [交易流水号]
     * @param $bankCode [银行代码]
     * @param @param $bankName [交易银行名称]
     * @param $bankAccountNO [银行卡账号]
     * @param $bankAccountName [银行卡户主名称]
     * @param $amount [金额] 元元元
     * @param $summary [交易附言]
     * @param $remark [备注]
     * @param $channelId [渠道ID]
     * @param $is_company 0:私人； 1:公司
     * @return mixed
     */
    public static function payLianLianPay($transactionSerialNumber,
                                       $bankCode,
                                       $bankName,
                                       $bankAccountNO,
                                       $bankAccountName,
                                       $amount,
                                       $summary,
                                       $remark,
                                       $channelId,
                                       $is_company) {

        //构造要请求的参数数组，无需改动
        $llpayconfig = llpay_config::getLlpayConfig();
        //商户时间
        $dt_order = date("YmdHis");
        //对私标记
        $flag_card = "0";
        if($is_company == 1) {
            $flag_card = "1";
        }
        //dd($flag_card);

        $parameter = array (
            "oid_partner" => trim($llpayconfig['oid_partner']),
            "sign_type" => trim($llpayconfig['sign_type']),
            "no_order" => $transactionSerialNumber,//商户付款流水号
            "dt_order" => $dt_order,//商户时间
            "money_order" => $amount,//金额
            "acct_name" => $bankAccountName,//收款人姓名
            "card_no" => $bankAccountNO,//银行账号
            "info_order" => $summary,//订单描述
            "flag_card" => $flag_card,//对私标记
            "notify_url" => self::$notify_url,
            "platform" => self::$platform,
            "api_version" => self::$api_version
        );
        //建立请求
        $llpaySubmit = new llpay_apipost_submit($llpayconfig);
        //对参数排序加签名
        $sortPara = $llpaySubmit->buildRequestPara($parameter);
        //传json字符串
        $json = json_encode($sortPara);
        $parameterRequest = array (
            "oid_partner" => trim($llpayconfig['oid_partner']),
            "pay_load" => llpay_security::ll_encrypt($json,$llpayconfig['LIANLIAN_PUBLICK_KEY']) //请求参数加密
        );
//        dd($parameterRequest);
//        var_dump('$parameterRequest');
//        var_dump($parameterRequest);
        $html_text = $llpaySubmit->buildRequestJSON($parameterRequest, self::$llpay_payment_url);
        //调用付款申请接口，同步返回0000，是指创建连连支付单成功，订单处于付款处理中状态，最终的付款状态由异步通知告知
        //出现1002，2005，4006，4007，4009，9999这6个返回码时或者没返回码，抛exception（或者对除了0000之后的code都查询一遍查询接口）调用付款结果查询接口，明确订单状态，不能私自设置订单为失败状态，以免造成这笔订单在连连付款成功了，
        //而商户设置为失败,用户重新发起付款请求,造成重复付款，商户资金损失
        //对连连响应报文内容需要用连连公钥验签
//        $html_text = "[".$transactionSerialNumber."]".$html_text;
//        dd($html_text);
        /**
         * {
         *  "no_order": "2017122916450888_1",
         *  "oid_partner": "201711230001180015",
         *  "oid_paybill": "2017122996863947",
         *  "ret_code": "0000",
         *  "ret_msg": "交易成功",
         *  "sign": "HQW1jA0V/MJHiGIsv9sAt3olbGzatooscgXKEsLNrtolDJz42TRw7FUQxJ6ePdFN52ZS/IS/bMPVFWhmTGIItS9nDRcL5BcU7VSfeDY7VmlXlfwUNpV6W7pe3FKTX0ASFaA++XaT6pQlCCjkRol1A5IDxEHBF+p3Oky9jd8kfrI=",
         *  "sign_type": "RSA"
         *  }
         */
        $resultCode = 0;
        $resultMsg = "";
        if($html_text!=FALSE) {
            if($html_text.startsWith("{") && $html_text.endsWith("}")) {
                $resultCode = 1;
                $result = json_decode($html_text);
                if($result && isset($result->ret_msg)) {
                    $resultMsg = $result->ret_msg;
                }
                if($result && isset($result->ret_code)) {
                    $RET_CODE = $result->ret_code;
                    if ($RET_CODE == "0000") {
                        if(isset($result->result_pay)) {
                            $result_pay = $result->result_pay;

                            if($result_pay == "SUCCESS" ) {
                                $resultMsg = "处理成功";
                            } else if($result_pay == "APPLY"
                                || $result_pay == "CHECK"
                                || $result_pay == "PROCESSING" ) {

                            } else if($result_pay == "CANCEL"
                                || $result_pay == "FAILURE"
                                || $result_pay == "CLOSED") {

                                $resultCode = 0;
                            }
                        }

                    } else if($RET_CODE == "1001"// 商户请求签名未通过
                        || $RET_CODE == "1002"//商户付款流水号重复
                        || $RET_CODE == "1004"// 商户请求参数校验错误，商户请求参数 非法
                        || $RET_CODE == "1005"// 不支持该银行账户类型
                        || $RET_CODE == "1008"// 商户请求IP错误
                        || $RET_CODE == "3001"// 非法商户
                        || $RET_CODE == "4003"// 收款银行卡和姓名不一至
                        || $RET_CODE == "4005"// 商户没有实时付款权限
                        || $RET_CODE == "4006"// 敏感信息加密异常
                        || $RET_CODE == "4007"// 敏感信息解密异常
                        || $RET_CODE == "4012"// 银行卡查询异常
                        || $RET_CODE == "4013"// 账户异常
                        || $RET_CODE == "4014"// 付款订单创建失败
                        || $RET_CODE == "4015"// 打款行号查询失败
                        || $RET_CODE == "9104"// 账户余额不足
                        || $RET_CODE == "9910"// 风险等级过高
                        || $RET_CODE == "9911"// 超过单笔限额
                        || $RET_CODE == "9912"// 超过单日限额
                        || $RET_CODE == "9913"// 超过单月限额
                        || $RET_CODE == "9999"// 系统错误
                        || $RET_CODE == "1004") {

                        $resultCode = 0;
                    }
                }
            } else {
                $resultMsg = "验签失败";
            }
        } else {
            $resultMsg = "验签失败";
        }

        $reqData = [
            'code' => $resultCode,
            'msg' => $resultMsg,
            'http_result_data' => $html_text
        ];
        return $reqData;
    }


    /**
     * 查询付款结果
     * @param $transactionSerialNumber
     * @param $reqSn
     * @return array
     */
    public static function payQuery($transactionSerialNumber, $reqSn) {
        $llpayconfig = llpay_config::getLlpayConfig();
        $parameter = array (
            "oid_partner" => trim($llpayconfig['oid_partner']),
            "platform" => self::$platform,
            "api_version" => self::$api_version,
            "sign_type" => trim($llpayconfig['sign_type']),
            "no_order" => $transactionSerialNumber,//商户付款流水号
            "oid_paybill" => '',//连连支付单号，可不传
        );
        //建立请求
        $llpaySubmit = new llpay_apipost_submit($llpayconfig);
        //对参数排序加签名
        $sortPara = $llpaySubmit->buildRequestPara($parameter);
        $html_text = $llpaySubmit->buildRequestJSON($sortPara, self::$llpayPaymentQuery);
//        dd($html_text);
        /**
         * {
         *      "dt_order": "20171229164508", //商户下单时间 YYYYMMDDH24MISS 14位数字，精确到秒
         *      "info_order": "summary", //订单描述
         *      "money_order": "0.01", //付款金额 付款金额大于 0 ，精确到小数点后两位
         *      "no_order": "2017122916450888_1", //商户付款流水号   商户系统唯一标识该付款的流水号
         *      "oid_partner": "201711230001180015",//
         *      "oid_paybill": "2017122996863947",//连连支付支付单号 银通付款流水号，付款支付单创建成功才有
         *      "result_pay": "SUCCESS",//付款结果
         *      "ret_code": "0000",
         *      "ret_msg": "交易成功", //
         *      "settle_date": "20171229", //清算日期 付款成功后有
         *      "sign": "kdhZczxi4oh7JSndKbuxkwhIlpiiVelpH5yzdpTTL1kII2glR6fioMiWlhaTiBh9GrWC9OGJugO0dEEhoSxl2umMP8QUWZdbajBv3+b3fTaNzDX29vFDasmHDryyS2nhJom/Fm/4L56b2CcAjMbOeBefK4grxtdm5w3/KlTqPsI=",
         *      "sign_type": "RSA"
         * }
         */
        //中间状态，等待下次查询
        $resultCode = 2;
        $resultMsg = "";
        if($html_text!=FALSE) {
            if($html_text.startsWith("{") && $html_text.endsWith("}")) {
                $result = json_decode($html_text);
                if($result && isset($result->ret_msg)) {
                    $resultMsg = $result->ret_msg;
                }

                if($result && isset($result->ret_code)) {
                    $RET_CODE = $result->ret_code;
                    if ($RET_CODE == "0000") {
                        if(isset($result->result_pay)) {
                            $result_pay = $result->result_pay;
                            if($result_pay == "SUCCESS" ) {
                                $resultCode = 1;
                                $resultMsg = "处理成功";
                            } else if($result_pay == "APPLY" //付款申请
                                || $result_pay == "CHECK" //复核申请
                                || $result_pay == "PROCESSING" ) { //付款处理中

                            } else if($result_pay == "CANCEL" //退款
                                || $result_pay == "FAILURE" //失败
                                || $result_pay == "CLOSED") { //关闭
                                //退款， 失败， 关闭
                                $resultCode = 0;
                            }
                        }
                    }
                }
            }
        } else {
            $resultCode = 0;
            $resultMsg = "验签失败";
//            print_r("验签结果：验签失败，请检查通联公钥证书是否正确");
        }
        $reqData = [
            'code' => $resultCode,
            'msg' => $resultMsg,
            'http_result_data' => $html_text
        ];

        return $reqData;
    }


    /**
     * 账户信息查询
     * @param $reqSn
     * @return array   balance:单位分
     */
    public static function payAccountInfo($reqSn) {
        //构造要请求的参数数组，无需改动
        $llpayconfig = llpay_config::getLlpayConfig();
        $parameter = array (
            "oid_partner" => trim($llpayconfig['oid_partner']),
            "sign_type" => trim($llpayconfig['sign_type']),
            "api_version" => self::$api_version,
        );
        //建立请求
        $llpaySubmit = new llpay_apipost_submit($llpayconfig);
        //对参数排序加签名
        $sortPara = $llpaySubmit->buildRequestPara($parameter);
        $html_text = $llpaySubmit->buildRequestJSON($sortPara, self::$llPayTraderAcctQuery);
//        dd($html_text);
        /*
         * {
         *     "amt_balance": "99.99",//该金额可作商户提现
         *     "amt_unsettle": "0.00",//该金额可进行退款，结转，不建议开通商户站充值业务的商户使用接口查询未结算余额作为退款依据
         *     "ret_code": "0000",
         *     "ret_msg": "交易成功",
         *     "sign": "eVy8IBAQzDhKJTgG9DzRNB86WbDnB35tQq8ZkMJ1D4KJ+tXtbbkk1lVToBgnmkTnnoyeVq3Y7D46aED0VmVz25G8ZLpIU6OLh18Z3zf/WA9p7LiUqDTZUT2w3FB+fRo+5vPHEA9kfnS6L00c2DESJr042RGPqzEQE3VifHf5jNw=",
         *     "sign_type": "RSA"
         *   }
         */
        $resultCode = 0;
        $resultMsg = "";
        $resultBalance = 0;//余额

        if($html_text!=FALSE) {
            if($html_text.startsWith("{") && $html_text.endsWith("}")) {
                $result = json_decode($html_text);
                if($result && isset($result->ret_code)) {
                    $RET_CODE = $result->ret_code;
                    if($RET_CODE == "0000") {
                        $resultBalance = ((float)$result->amt_balance) * 100;
                        $resultMsg = "查询成功";
                        $resultCode = 1;
                    } else {
                        $ERR_MSG = $result->ret_msg;
                        $resultMsg = $ERR_MSG;
                        $resultCode = 0;
                    }
                }
            }
        } else {
            $resultCode = 0;
            $resultMsg = "验签失败";
//            print_r("验签结果：验签失败，请检查通联公钥证书是否正确");
        }
        $reqData = [
            'code' => $resultCode,
            'msg' => $resultMsg,
            'balance' => $resultBalance,
            'http_result_data' => $html_text
        ];
        return $reqData;
    }
}