国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 微信小程式 小程式開發(fā) 重新對(duì)百度支付進(jìn)行編寫封裝(百度智慧小程式支付)

重新對(duì)百度支付進(jìn)行編寫封裝(百度智慧小程式支付)

Jul 17, 2021 pm 03:38 PM

最近因?yàn)閷0钢貥?gòu)的原因,對(duì)百度支付重新進(jìn)行了編寫封裝,本次重寫,添加了對(duì)簽名的處理、添加用戶退款,方便之後開發(fā)的使用。

因?yàn)榘俣入娚涕_放平臺(tái)的升級(jí),支付功能已移至智慧小程式內(nèi)部,具體申請(qǐng)流程:百度收銀臺(tái)支付開通指引,(https://smartprogram.baidu.com/docs/operations /transform/pay/)

(註:在支付服務(wù)中,服務(wù)電話應(yīng)填寫銀行預(yù)留手機(jī)號(hào),如填寫錯(cuò)誤報(bào)【銀行預(yù)留手機(jī)號(hào)碼格式校驗(yàn)不通過】)

百度付款文件:百度收銀臺(tái)介面2.0(https://smartprogram.baidu.com/docs/develop/function/tune_up_2.0/)

#一、申請(qǐng)通過後,填寫百度付款相關(guān)配置:

$config = array(
    'deal_id'       => '', // 百度收銀臺(tái)的財(cái)務(wù)結(jié)算憑證
    'app_key'       => '', // 表示應(yīng)用身份的唯一ID
    'private_key'   => '', // 私鑰原始字符串
    'public_key'    => '', // 平臺(tái)公鑰
    'notify_url'    => '', // 支付回調(diào)地址
);

二、呼叫封裝的支付方法,將回傳訊息,傳遞到百度小程式

<?php
include &#39;./BaiduPay.php&#39;;
$baidupay = new \feng\BaiduPay($config);
$order_sn = time().rand(1000,9999);
$order = array(
    &#39;body&#39;          => &#39;測(cè)試商品&#39;, // 產(chǎn)品描述
    &#39;total_amount&#39;  => &#39;1&#39;, // 訂單金額(分)
    &#39;order_sn&#39;      => $order_sn, // 訂單編號(hào)
);
$re = $baidupay->xcxPay($order);
die(json_encode($re)); // JSON化直接返回小程序客戶端
PHP

小程式支付類別xcxPay:

/**
 * [xcxPay 百度小程序支付]
 * @param  [type]  $order [訂單信息數(shù)組]
 * @return [type]         [description]
 * $order = array(
 *      &#39;body&#39;          => &#39;&#39;, // 產(chǎn)品描述
 *      &#39;total_amount&#39;  => &#39;&#39;, // 訂單金額(分)
 *      &#39;order_sn&#39;      => &#39;&#39;, // 訂單編號(hào)
 * );
 */
public static function xcxPay($order)
{
    if(!is_array($order) || count($order) < 3)
        die("數(shù)組數(shù)據(jù)信息缺失!");
    $config = self::$config;
    $requestParamsArr = array(
        &#39;appKey&#39;    => $config[&#39;app_key&#39;],
        &#39;dealId&#39;    => $config[&#39;deal_id&#39;],
        &#39;tpOrderId&#39; => $order[&#39;order_sn&#39;],
        &#39;totalAmount&#39; => $order[&#39;total_amount&#39;],
    );
    $rsaSign = self::makeSign($requestParamsArr, $config[&#39;private_key&#39;]);  // 聲稱百度支付簽名
    $bizInfo = array(
        &#39;tpData&#39; => array(
            "appKey"        => $config[&#39;app_key&#39;],
            "dealId"        => $config[&#39;deal_id&#39;],
            "tpOrderId"     => $order[&#39;order_sn&#39;],
            "rsaSign"       => $rsaSign,
            "totalAmount"   => $order[&#39;total_amount&#39;],
            "returnData"    => &#39;&#39;,
            "displayData"   => array(
                "cashierTopBlock" => array(
                    array(
                        [ "leftCol" => "訂單名稱", "rightCol"   => $order[&#39;body&#39;] ],
                        [ "leftCol" => "數(shù)量", "rightCol" => "1" ],
                        [ "leftCol" => "訂單金額", "rightCol"   => $order[&#39;total_amount&#39;] ]
                    ),
                    array(
                        [ "leftCol" => "服務(wù)地址", "rightCol" => "北京市海淀區(qū)上地十街10號(hào)百度大廈" ],
                        [ "leftCol" => "服務(wù)時(shí)間", "rightCol" => "2018/10/29 14:51" ],
                        [ "leftCol" => "服務(wù)人員", "rightCol" => "百度App" ]
                    )
                )
            ),
            "dealTitle"     => $order[&#39;body&#39;],
            "dealSubTitle"  => $order[&#39;body&#39;],
            "dealThumbView" => "https://b.bdstatic.com/searchbox/icms/searchbox/img/swan-logo.png",
        ),
        "orderDetailData"   => &#39;&#39;
    );
    $bdOrder = array(
        &#39;dealId&#39;        => $config[&#39;deal_id&#39;],
        &#39;appKey&#39;        => $config[&#39;app_key&#39;],
        &#39;totalAmount&#39;   => $order[&#39;total_amount&#39;],
        &#39;tpOrderId&#39;     => $order[&#39;order_sn&#39;],
        &#39;dealTitle&#39;     => $order[&#39;body&#39;],
        &#39;signFieldsRange&#39; => 1,
        &#39;rsaSign&#39;       => $rsaSign,
        &#39;bizInfo&#39;       => json_encode($bizInfo),
    );
    return $bdOrder;
}

三、百度智能小程式端的使用

SWAN

<view class="wrap">
    <view class="card-area">
        <button bind:tap="requestPolymerPayment" type="primary" hover-stop-propagation="true">支付0.01元</button>
    </view>
</view>
HTML

JS

Page({
    requestPolymerPayment(e) {
        swan.request({
            url: &#39;https://mbd.baidu.com/xxx&#39;, // 僅為示例,并非真實(shí)的接口地址,開發(fā)者從真實(shí)接口獲取orderInfo的值
            success: res => {
                res.data.data.dealTitle = &#39;百度小程序Demo支付測(cè)試&#39;;
                let data = res.data;
                if (data.errno !== 0) {
                    console.log(&#39;create order err&#39;, data);
                    return;
                }
                swan.requestPolymerPayment({
                    orderInfo: data.data,
                    success: res => {
                        swan.showToast({
                            title: &#39;支付成功&#39;,
                            icon: &#39;success&#39;
                        });
                        console.log(&#39;pay success&#39;, res);
                    },
                    fail: err => {
                        swan.showToast({
                            title: err.errMsg,
                            icon: &#39;none&#39;
                        });
                        console.log(&#39;pay fail&#39;, err);
                    }
                });
            },
            fail: err => {
                swan.showToast({
                    title: &#39;訂單創(chuàng)建失敗&#39;,
                    icon: &#39;none&#39;
                });
                console.log(&#39;create order fail&#39;, err);
            }
        });
    }
});

四、支付回呼

<?php
include &#39;./BaiduPay.php&#39;;
$baidupay = new \feng\BaiduPay($config);
$re = $baidupay->notify();
if ($re) {
    // 這里回調(diào)處理訂單操作
    // 以驗(yàn)證返回支付成功后的信息,可直接對(duì)訂單進(jìn)行操作,已通知微信支付成功
    $baidupay->success(); // 支付返還成功,通知結(jié)果
} else {
    // 支付失敗
    $baidupay->error(); // 支付失敗,返回狀態(tài)(無論支付成功與否都需要通知百度)
}

百度完整支付類別(BaiduPay.php),包含小程式支付、驗(yàn)簽、回呼、退款:

<?php
/**
 * @Author: [FENG] <1161634940@qq.com>
 * @Date:   2020-09-27T16:28:31+08:00
 * @Last Modified by:   [FENG] <1161634940@qq.com>
 * @Last Modified time: 2020-10-15T10:23:07+08:00
 */
namespace feng;
class BaiduPay
{
    private static $config = array(
        &#39;deal_id&#39;       => &#39;&#39;, // 百度收銀臺(tái)的財(cái)務(wù)結(jié)算憑證
        &#39;app_key&#39;       => &#39;&#39;, // 表示應(yīng)用身份的唯一ID
        &#39;private_key&#39;   => &#39;&#39;, // 私鑰原始字符串
        &#39;public_key&#39;    => &#39;&#39;, // 平臺(tái)公鑰
        &#39;notify_url&#39;    => &#39;&#39;, // 支付回調(diào)地址
    );
    /**
     * [__construct 構(gòu)造函數(shù)]
     * @param [type] $config [傳遞支付相關(guān)配置]
     */
    public function __construct($config=NULL){
        $config && self::$config = $config;
    }
    /**
     * [xcxPay 百度小程序支付]
     * @param  [type]  $order [訂單信息數(shù)組]
     * @return [type]         [description]
     * $order = array(
     *      &#39;body&#39;          => &#39;&#39;, // 產(chǎn)品描述
     *      &#39;total_amount&#39;  => &#39;&#39;, // 訂單金額(分)
     *      &#39;order_sn&#39;      => &#39;&#39;, // 訂單編號(hào)
     * );
     */
    public static function xcxPay($order)
    {
        if(!is_array($order) || count($order) < 3)
            die("數(shù)組數(shù)據(jù)信息缺失!");
        $config = self::$config;
        $requestParamsArr = array(
            &#39;appKey&#39;    => $config[&#39;app_key&#39;],
            &#39;dealId&#39;    => $config[&#39;deal_id&#39;],
            &#39;tpOrderId&#39; => $order[&#39;order_sn&#39;],
            &#39;totalAmount&#39; => $order[&#39;total_amount&#39;],
        );
        $rsaSign = self::makeSign($requestParamsArr, $config[&#39;private_key&#39;]);  // 聲稱百度支付簽名
        $bizInfo = array(
            &#39;tpData&#39; => array(
                "appKey"        => $config[&#39;app_key&#39;],
                "dealId"        => $config[&#39;deal_id&#39;],
                "tpOrderId"     => $order[&#39;order_sn&#39;],
                "rsaSign"       => $rsaSign,
                "totalAmount"   => $order[&#39;total_amount&#39;],
                "returnData"    => &#39;&#39;,
                "displayData"   => array(
                    "cashierTopBlock" => array(
                        array(
                            [ "leftCol" => "訂單名稱", "rightCol"   => $order[&#39;body&#39;] ],
                            [ "leftCol" => "數(shù)量", "rightCol" => "1" ],
                            [ "leftCol" => "訂單金額", "rightCol"   => $order[&#39;total_amount&#39;] ]
                        ),
                        array(
                            [ "leftCol" => "服務(wù)地址", "rightCol" => "北京市海淀區(qū)上地十街10號(hào)百度大廈" ],
                            [ "leftCol" => "服務(wù)時(shí)間", "rightCol" => "2018/10/29 14:51" ],
                            [ "leftCol" => "服務(wù)人員", "rightCol" => "百度App" ]
                        )
                    )
                ),
                "dealTitle"     => $order[&#39;body&#39;],
                "dealSubTitle"  => $order[&#39;body&#39;],
                "dealThumbView" => "https://b.bdstatic.com/searchbox/icms/searchbox/img/swan-logo.png",
            ),
            "orderDetailData"   => &#39;&#39;
        );
        $bdOrder = array(
            &#39;dealId&#39;        => $config[&#39;deal_id&#39;],
            &#39;appKey&#39;        => $config[&#39;app_key&#39;],
            &#39;totalAmount&#39;   => $order[&#39;total_amount&#39;],
            &#39;tpOrderId&#39;     => $order[&#39;order_sn&#39;],
            &#39;dealTitle&#39;     => $order[&#39;body&#39;],
            &#39;signFieldsRange&#39; => 1,
            &#39;rsaSign&#39;       => $rsaSign,
            &#39;bizInfo&#39;       => json_encode($bizInfo),
        );
        return $bdOrder;
    }
    /**
     * [refund baidu支付退款]
     * @param  [type] $order [訂單信息]
     * @param  [type] $type  [退款類型]
     * $order = array(
     *      &#39;body&#39;          => &#39;&#39;, // 退款原因
     *      &#39;total_amount&#39;  => &#39;&#39;, // 退款金額(分)
     *      &#39;order_sn&#39;      => &#39;&#39;, // 訂單編號(hào)
     *      &#39;access_token&#39;  => &#39;&#39;, // 獲取開發(fā)者服務(wù)權(quán)限說明
     *      &#39;order_id&#39;      => &#39;&#39;, // 百度收銀臺(tái)訂單 ID
     *      &#39;user_id&#39;       => &#39;&#39;, // 百度收銀臺(tái)用戶 id
     * );
     */
    public static function refund($order=[], $type=1)
    {
        $config = self::$config;
        $data = array(
            &#39;access_token&#39;      => $order[&#39;access_token&#39;], // 獲取開發(fā)者服務(wù)權(quán)限說明
            &#39;applyRefundMoney&#39;  => $order[&#39;total_amount&#39;], // 退款金額,單位:分。
            &#39;bizRefundBatchId&#39;  => $order[&#39;order_sn&#39;], // 開發(fā)者退款批次
            &#39;isSkipAudit&#39;       => 1, // 是否跳過審核,不需要百度請(qǐng)求開發(fā)者退款審核請(qǐng)傳 1,默認(rèn)為0; 0:不跳過開發(fā)者業(yè)務(wù)方審核;1:跳過開發(fā)者業(yè)務(wù)方審核。
            &#39;orderId&#39;           => $order[&#39;order_id&#39;], // 百度收銀臺(tái)訂單 ID
            &#39;refundReason&#39;      => $order[&#39;body&#39;], // 退款原因
            &#39;refundType&#39;        => $type, // 退款類型 1:用戶發(fā)起退款;2:開發(fā)者業(yè)務(wù)方客服退款;3:開發(fā)者服務(wù)異常退款。
            &#39;tpOrderId&#39;         => $order[&#39;order_sn&#39;], // 開發(fā)者訂單 ID
            &#39;userId&#39;            => $order[&#39;user_id&#39;], // 百度收銀臺(tái)用戶 id
        );
        $array = [&#39;errno&#39;=>0, &#39;msg&#39;=>&#39;success&#39;, &#39;data&#39;=> [&#39;isConsumed&#39;=>2] ];
        $url = &#39;https://openapi.baidu.com/rest/2.0/smartapp/pay/paymentservice/applyOrderRefund&#39;;
        $response = self::post_curl($url, $data);
        $result = json_decode($response, true);
        // // 顯示錯(cuò)誤信息
        // if ($result[&#39;msg&#39;]!=&#39;success&#39;) {
        //     return false;
        //     // die($result[&#39;msg&#39;]);
        // }
        return $result;
    }
    /**
     * [notify 回調(diào)驗(yàn)證]
     * @return [array] [返回?cái)?shù)組格式的notify數(shù)據(jù)]
     */
    public static function notify()
    {
        $data = $_POST; // 獲取xml
        $config = self::$config;
        if (!$data || empty($data[&#39;rsaSign&#39;]))
            die(&#39;暫無回調(diào)信息&#39;);
        $result = self::checkSign($data, $config[&#39;public_key&#39;]); // 進(jìn)行簽名驗(yàn)證
        // 判斷簽名是否正確  判斷支付狀態(tài)
        if ($result && $data[&#39;status&#39;]==2) {
            return $data;
        } else {
            return false;
        }
    }
    /**
     * [success 通知支付狀態(tài)]
     */
    public static function success()
    {
        $array = [&#39;errno&#39;=>0, &#39;msg&#39;=>&#39;success&#39;, &#39;data&#39;=> [&#39;isConsumed&#39;=>2] ];
        die(json_encode($array));
    }
    /**
     * [error 通知支付狀態(tài)]
     */
    public static function error()
    {
        $array = [&#39;errno&#39;=>0, &#39;msg&#39;=>&#39;success&#39;, &#39;data&#39;=> [&#39;isErrorOrder&#39;=>1, &#39;isConsumed&#39;=>2] ];
        die(json_encode($array));
    }
    /**
     * [makeSign 使用私鑰生成簽名字符串]
     * @param  array  $assocArr     [入?yún)?shù)組]
     * @param  [type] $rsaPriKeyStr [私鑰原始字符串,不含PEM格式前后綴]
     * @return [type]               [簽名結(jié)果字符串]
     */
    public static function makeSign(array $assocArr, $rsaPriKeyStr)
    {
        $sign = &#39;&#39;;
        if (empty($rsaPriKeyStr) || empty($assocArr)) {
            return $sign;
        }
        if (!function_exists(&#39;openssl_pkey_get_private&#39;) || !function_exists(&#39;openssl_sign&#39;)) {
            throw new Exception("openssl擴(kuò)展不存在");
        }
        $rsaPriKeyPem = self::convertRSAKeyStr2Pem($rsaPriKeyStr, 1);
        $priKey = openssl_pkey_get_private($rsaPriKeyPem);
        if (isset($assocArr[&#39;sign&#39;])) {
            unset($assocArr[&#39;sign&#39;]);
        }
        ksort($assocArr); // 參數(shù)按字典順序排序
        $parts = array();
        foreach ($assocArr as $k => $v) {
            $parts[] = $k . &#39;=&#39; . $v;
        }
        $str = implode(&#39;&&#39;, $parts);
        openssl_sign($str, $sign, $priKey);
        openssl_free_key($priKey);
        return base64_encode($sign);
    }
    /**
     * [checkSign 使用公鑰校驗(yàn)簽名]
     * @param  array  $assocArr     [入?yún)?shù)據(jù),簽名屬性名固定為rsaSign]
     * @param  [type] $rsaPubKeyStr [公鑰原始字符串,不含PEM格式前后綴]
     * @return [type]               [驗(yàn)簽通過|false 驗(yàn)簽不通過]
     */
    public static function checkSign(array $assocArr, $rsaPubKeyStr)
    {
        if (!isset($assocArr[&#39;rsaSign&#39;]) || empty($assocArr) || empty($rsaPubKeyStr)) {
            return false;
        }
        if (!function_exists(&#39;openssl_pkey_get_public&#39;) || !function_exists(&#39;openssl_verify&#39;)) {
            throw new Exception("openssl擴(kuò)展不存在");
        }
        $sign = $assocArr[&#39;rsaSign&#39;];
        unset($assocArr[&#39;rsaSign&#39;]);
        if (empty($assocArr)) {
            return false;
        }
        ksort($assocArr); // 參數(shù)按字典順序排序
        $parts = array();
        foreach ($assocArr as $k => $v) {
            $parts[] = $k . &#39;=&#39; . $v;
        }
        $str = implode(&#39;&&#39;, $parts);
        $sign = base64_decode($sign);
        $rsaPubKeyPem = self::convertRSAKeyStr2Pem($rsaPubKeyStr);
        $pubKey = openssl_pkey_get_public($rsaPubKeyPem);
        $result = (bool)openssl_verify($str, $sign, $pubKey);
        openssl_free_key($pubKey);
        return $result;
    }
    /**
     * [convertRSAKeyStr2Pem 將密鑰由字符串(不換行)轉(zhuǎn)為PEM格式]
     * @param  [type]  $rsaKeyStr [原始密鑰字符串]
     * @param  integer $keyType   [0 公鑰|1 私鑰,默認(rèn)0]
     * @return [type]             [PEM格式密鑰]
     */
    public static function convertRSAKeyStr2Pem($rsaKeyStr, $keyType = 0)
    {
        $pemWidth = 64;
        $rsaKeyPem = &#39;&#39;;
        $begin = &#39;-----BEGIN &#39;;
        $end = &#39;-----END &#39;;
        $key = &#39; KEY-----&#39;;
        $type = $keyType ? &#39;RSA PRIVATE&#39; : &#39;PUBLIC&#39;;
        $keyPrefix = $begin . $type . $key;
        $keySuffix = $end . $type . $key;
        $rsaKeyPem .= $keyPrefix . "\n";
        $rsaKeyPem .= wordwrap($rsaKeyStr, $pemWidth, "\n", true) . "\n";
        $rsaKeyPem .= $keySuffix;
        if (!function_exists(&#39;openssl_pkey_get_public&#39;) || !function_exists(&#39;openssl_pkey_get_private&#39;)) {
            return false;
        }
        if ($keyType == 0 && false == openssl_pkey_get_public($rsaKeyPem)) {
            return false;
        }
        if ($keyType == 1 && false == openssl_pkey_get_private($rsaKeyPem)) {
            return false;
        }
        return $rsaKeyPem;
    }
    /**
     * curl post請(qǐng)求
     * @param string $url 地址
     * @param string $postData 數(shù)據(jù)
     * @param array $header 頭部
     * @return bool|string
     * @Date 2020/9/17 17:12
     * @Author wzb
     */
    public static function post_curl($url=&#39;&#39;,$postData=&#39;&#39;,$header=[]){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5000);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
        if($header){
            curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErrNo = curl_errno($ch);
        $curlErr = curl_error($ch);
        curl_close($ch);
        return $result;
    }
}

以上是重新對(duì)百度支付進(jìn)行編寫封裝(百度智慧小程式支付)的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1600
29
PHP教程
1502
276