yangzailu

导航

Alipay 支付类

本版本参考网友

<?php

namespace App\Tools;

class Alipay
{

    //应用ID,您的APPID。
    private $appID         = '111';
    //商户私钥
    private $rsaPrivateKey = '11'
    
    private $notifyUrl     = '/pay/alipay/notify';
    //同步跳转
    private $returnUrl     = '/pay/alipay/notify';
    //编码格式
    private $charset       = 'UTF-8';
    //签名方式
    private $signType      = 'RSA2';
    //支付宝网关
    private $gatewayUrl    = 'https://openapi.alipay.com/gateway.do';
    //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private $rsaPublicKey  = 'MIIBIjANBgkqhkiG9w0gws9xPckXVEoGDtrQTEeKvHmoJ81R+wKAHdXnHwzkts1pCYlvfQoAeJf8ibr6qyWkWX/aTrrM72Dd2HewIDAQAB';
    private $fileCharset   = "UTF-8";
    // 表单提交字符集编码
    public $postCharset    = "UTF-8";
    //私钥文件路径
    public $rsaPrivateKeyFilePath;

    /**
     * 发起订单
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 订单发起时间
     * @return array
     */
    public function pcPay($totalFee, $outTradeNo, $orderName, $httpmethod = "POST")
    {
        //公共提交参数
        $commonConfigs            = array(
            'app_id'     => $this->appID,
            'method'     => 'alipay.trade.page.pay', //接口名称
            'format'     => 'JSON',
            'return_url' => $this->returnUrl,
            'charset'    => $this->charset,
            'sign_type'  => 'RSA2',
            'timestamp'  => date('Y-m-d H:i:s'),
            'version'    => '1.0',
            'notify_url' => $this->notifyUrl,
        );
        //请求参数
        $requestConfigs           = array(
            'out_trade_no' => $outTradeNo,
            'product_code' => 'FAST_INSTANT_TRADE_PAY',
            'total_amount' => $totalFee, //单位 元
            'subject'      => $orderName, //订单标题
        );
        $apiParams['biz_content'] = json_encode($requestConfigs);

        //合并数组
        $totalParams         = array_merge($apiParams, $commonConfigs);
        //待签名字符串
        $preSignStr          = $this->getSignContent($totalParams);
        //生成签名
        $totalParams["sign"] = $this->generateSign($totalParams, $this->signType);

        if ("GET" == strtoupper($httpmethod)) {
            //        //value做urlencode
            $preString  = $this->getSignContentUrlencode($totalParams);
            //拼接GET请求串
            $requestUrl = $this->gatewayUrl . "?" . $preString;
            return $requestUrl;
        } else {
            //拼接表单字符串
            return $this->buildRequestForm($totalParams);
        }
    }

    /**
     * 支付回调
     * @param type $param
     */
    public function notify($param)
    {
        $result = $this->check($param);
        return $result;
    }

    /**
     * 验签方法
     * @param $arr 验签支付宝返回的信息,使用支付宝公钥。
     * @return boolean
     */
    protected function check($arr)
    {
        $result = $this->rsaCheckV1($arr, $this->rsaPublicKey, $this->signType);
        return $result;
    }

    /**
     * 建立请求,以表单HTML形式构造(默认)
     * @param $para_temp 请求参数数组
     * @return 提交表单HTML文本
     */
    protected function buildRequestForm($para_temp)
    {

        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='" . $this->gatewayUrl . "?charset=" . trim($this->postCharset) . "' method='POST' >";
        while (list($key, $val) = each($para_temp)) {
            if (false === $this->checkEmpty($val)) {
                //$val = $this->characet($val, $this->postCharset);
                $val = str_replace("'", "&apos;", $val);
                //$val = str_replace("\"","&quot;",$val);
                $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
            }
        }
//        foreach ($para_temp as $key => $val) {
//            if (false === $this->checkEmpty($val)) {
//                //$val = $this->characet($val, $this->postCharset);
//                $val   = str_replace("'", "&apos;", $val);
//                //$val = str_replace("\"","&quot;",$val);
//                $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
//            }
//        }

        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml . "<input type='submit' value='ok' style='display:none;''></form>";

        $sHtml = $sHtml . "<script>document.forms['alipaysubmit'].submit();</script>";

        return $sHtml;
    }

    /**
     * 生成签名所需字符串
     * @param type $params
     * @return string
     */
    public function getSignContent($params)
    {
        ksort($params);

        $stringToBeSigned = "";
        $i                = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {

                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset($k, $v);
        return $stringToBeSigned;
    }

    /**
     * url拼接转义字符
     * 此方法对value做urlencode
     * @param type $params
     * @return string
     */
    public function getSignContentUrlencode($params)
    {
        ksort($params);

        $stringToBeSigned = "";
        $i                = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {

                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . urlencode($v);
                } else {
                    $stringToBeSigned .= "&amp" . "$k" . "=" . urlencode($v);
                }
                $i++;
            }
        }

        unset($k, $v);
        return $stringToBeSigned;
    }

    /**
     * 生成签名
     * @param type $data
     * @param type $signType
     * @return type
     */
    protected function sign($data, $signType = "RSA")
    {
        if ($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            $priKey = $this->rsaPrivateKey;
            $res    = "-----BEGIN RSA PRIVATE KEY-----\n" .
                    wordwrap($priKey, 64, "\n", true) .
                    "\n-----END RSA PRIVATE KEY-----";
        } else {
            $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
            $res    = openssl_get_privatekey($priKey);
        }

        ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');

        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }

        if (!$this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            openssl_free_key($res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     * */
    protected function checkEmpty($value)
    {
        if (!isset($value)) {
            return true;
        }

        if ($value === null) {
            return true;
        }

        if (trim($value) === "") {
            return true;
        }

        return false;
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    protected function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //                $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }

    /**
     *
     * @param type $params
     * @param type $signType
     * @return type
     */
    public function generateSign($params, $signType = "RSA")
    {
        return $this->sign($this->getSignContent($params), $signType);
    }

    /**
     *
     * @param type $params
     * @param type $signType
     * @return type
     */
    public function rsaSign($params, $signType = "RSA")
    {
        return $this->sign($this->getSignContent($params), $signType);
    }

    /** rsaCheckV1 & rsaCheckV2
     *  验证签名
     *  在使用本方法前,必须初始化AopClient且传入公钥参数。
     *  公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
     * */
    public function rsaCheckV1($params, $rsaPublicKeyFilePath, $signType = 'RSA')
    {
        $sign                = $params['sign'];
        $params['sign_type'] = null;
        $params['sign']      = null;
        return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
    }

    public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType = 'RSA')
    {
        $sign           = $params['sign'];
        $params['sign'] = null;
        return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
    }

    /**
     * 验证
     * @param type $data
     * @param type $sign
     * @param type $rsaPublicKeyFilePath
     * @param type $signType
     * @return type
     */
    public function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA')
    {

        if ($this->checkEmpty($this->rsaPrivateKeyFilePath)) {

            $pubKey = $this->rsaPublicKey;
            $res    = "-----BEGIN PUBLIC KEY-----\n" .
                    wordwrap($pubKey, 64, "\n", true) .
                    "\n-----END PUBLIC KEY-----";
        } else {
            //读取公钥文件
            $pubKey = file_get_contents($rsaPublicKeyFilePath);
            //转换为openssl格式密钥
            $res    = openssl_get_publickey($pubKey);
        }

        ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');

        //调用openssl内置方法验签,返回bool值

        if ("RSA2" == $signType) {
            $result = (bool) openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
        } else {
            $result = (bool) openssl_verify($data, base64_decode($sign), $res);
        }

        if (!$this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            //释放资源
            openssl_free_key($res);
        }

        return $result;
    }

}

 

posted on 2019-10-30 09:37  飞离地平线  阅读(610)  评论(0编辑  收藏  举报