亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet Mini Program Development Re-write and encapsulate Baidu Payment (Baidu Smart Mini Program Payment)

Re-write and encapsulate Baidu Payment (Baidu Smart Mini Program Payment)

Jul 17, 2021 pm 03:38 PM

Recently due to project reconstruction, Baidu Payment has been rewritten and encapsulated. In this rewrite, signature processing and user refunds have been added to facilitate subsequent development and use.

Due to the upgrade of Baidu e-commerce open platform, the payment function has been moved to the smart mini program. The specific application process is: Baidu Cashier Payment Activation Guide, (https://smartprogram.baidu.com/docs/operations /transform/pay/)

(Note: In the payment service, the service phone number should be filled in with the mobile phone number reserved by the bank. If it is incorrectly filled in, [bank reserved mobile phone number format verification failed] will be reported)

Baidu Payment Document: Baidu Cashier Interface 2.0 (https://smartprogram.baidu.com/docs/develop/function/tune_up_2.0/)

1. After the application is approved, fill in the Baidu payment related information Configuration:

$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)地址
);

2. Call the encapsulated payment method and pass the returned information to Baidu Mini Program

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

Mini Program Payment Class 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;
}

3. Baidu Intelligence Use of mini program

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

4. Payment callback

<?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)(無論支付成功與否都需要通知百度)
}

Baidu complete payment class (BaiduPay.php), Including mini program payment, signature verification, callback, and refund:

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

The above is the detailed content of Re-write and encapsulate Baidu Payment (Baidu Smart Mini Program Payment). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72