一個PHP文件搞定支付寶現金紅包

B2C現金紅包流程:

1.調用統一轉賬接口(alipay.fund.trans.uni.transfer)將資金從發起請求的商戶支付寶賬戶餘額打款給領取紅包的人。
2.可以通過轉賬業務單據查詢接口(aalipay.fund.trans.common.query)查詢紅包轉發送狀態。
B2C現金紅包代碼:

<?php
$appid = 'xxxxx';  //https://open.alipay.com 賬戶中心->密鑰管理->開放平臺密鑰,填寫添加了現金紅包的應用的APPID
$alipayRootCertSn = 'xxxxx';     //支付寶根證書sn
$appCertSn = 'xxxxx';     //應用證書sn
$outTradeNo = uniqid();     //商戶訂單號,不能重複
$payAmount = 0.01;          //紅包金額,單位:元
$orderName = '公益';          //紅包標題
$signType = 'RSA2';			//簽名算法類型,支持RSA2和RSA,推薦使用RSA2
$userid = '2088xxx'; //接收紅包的支付寶用戶id(2088開頭的16位數字)
//商戶私鑰
$rsaPrivateKey='xxxxx';
$aliPay = new AlipayService();
$aliPay->setAppid($appid);
$aliPay->setAlipayRootCertSn($alipayRootCertSn);
$aliPay->setAppCertSn($appCertSn);
$aliPay->setRsaPrivateKey($rsaPrivateKey);
$aliPay->setNotifyUrl($notifyUrl);
$aliPay->setTotalFee($payAmount);
$aliPay->setOutTradeNo($outTradeNo);
$aliPay->setOrderName($orderName);
$aliPay->setUserId($userid);
$result = $aliPay->sendRedPacket();
if($result['alipay_fund_trans_uni_transfer_response']['code']==10000){
    echo '紅包發送成功';
}else{
    echo '紅包發送失敗,原因:'.$result['alipay_fund_trans_uni_transfer_response']['msg'];
}

class AlipayService
{
    protected $appId;
    protected $alipayRootCertSn;
    protected $appCertSn;
    protected $notifyUrl;
    protected $charset;
    //私鑰值
    protected $rsaPrivateKey;
    protected $totalFee;
    protected $outTradeNo;
    protected $orderName;
    protected $userid;
    public function __construct()
    {
        $this->charset = 'utf-8';
    }
    public function setAppid($appid)
    {
        $this->appId = $appid;
    }
    public function setAlipayRootCertSn($alipayRootCertSn)
    {
        $this->alipayRootCertSn = $alipayRootCertSn;
    }
    public function setAppCertSn($appCertSn)
    {
        $this->appCertSn = $appCertSn;
    }
    public function setNotifyUrl($notifyUrl)
    {
        $this->notifyUrl = $notifyUrl;
    }
    public function setRsaPrivateKey($saPrivateKey)
    {
        $this->rsaPrivateKey = $saPrivateKey;
    }
    public function setTotalFee($payAmount)
    {
        $this->totalFee = $payAmount;
    }
    public function setOutTradeNo($outTradeNo)
    {
        $this->outTradeNo = $outTradeNo;
    }
    public function setOrderName($orderName)
    {
        $this->orderName = $orderName;
    }
    public function setUserId($userid)
    {
        $this->userid = $userid;
    }
    /**
     * 發紅包
     * @return array
     */
    public function sendRedPacket()
    {
        //請求參數
        $requestConfigs = array(
            'out_biz_no'=>$this->outTradeNo,
            'trans_amount'=>$this->totalFee, //單位 元
            'product_code'=>'STD_RED_PACKET',
            'biz_scene'=>'DIRECT_TRANSFER',
            'remark'=>$this->orderName,
            'order_title'=>$this->orderName,  //訂單標題
            'payee_info'=>array(
                'identity'=>$this->userid,     //接受紅包的用戶id
                'identity_type'=>'ALIPAY_USER_ID',     //參與方的標識類型
            ),
            'business_params'=>array(
                'sub_biz_scene'=>'REDPACKET',       //子場景
            )
        );
        $commonConfigs = array(
            //公共參數
            'alipay_root_cert_sn' => $this->alipayRootCertSn,
            'app_cert_sn' => $this->appCertSn,
            'app_id' => $this->appId,
            'method' => 'alipay.fund.trans.uni.transfer',             //接口名稱
            'format' => 'JSON',
            'charset'=>'utf-8',
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );

        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do',$commonConfigs);
        return json_decode($result,true);
    }

    public function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }
    protected function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私鑰格式錯誤,請檢查RSA私鑰配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $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;
    }
    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->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    /**
     * 轉換字符集編碼
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //設置cURL允許執行的最長秒數
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https請求 不驗證證書和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}

C2C現金紅包流程:

1.調用發紅包接口(alipay.fund.trans.app.pay)將用戶付款的資金轉入支付寶中間戶,完成發送紅包環節。
2.調用紅包打款接口(alipay.fund.trans.uni.transfer)將資金從支付寶中間戶打款給領取紅包的人。
3.如果第2步未完成,到指定超時時間(目前設置的30分鐘,可以修改)後,資金會原路退回。
支付寶現金紅包接口文檔:https://docs.open.alipay.com/20190111144811460526/api/

C2C紅包演示地址:
https://www.dedemao.com/alipay/red_packet.html

更多支付寶DEMO演示:
https://www.dedemao.com/alipay/demo.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章