Alipay 支付類

本版本參考網友php

<?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;
    }

}
相關文章
相關標籤/搜索