溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

微信小程序如何實現支付功能

發布時間:2021-06-09 14:43:52 來源:億速云 閱讀:308 作者:小新 欄目:移動開發

這篇文章主要為大家展示了“微信小程序如何實現支付功能”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“微信小程序如何實現支付功能”這篇文章吧。

開發前必讀

主要流程

  • 小程序前端發送求參請求

  • 接受請求封裝 “統一下單” 獲取package

  • 小程序接受 “統一下單” 獲取的package值帶入wx.requestPayment發起支付請求

準備工具

  • 申請小程序微信支付

  • 拿到小程序微信支付的商戶號及設置秘鑰

注意:小程序就只需要這兩步,如果是web的話還需要設置支付目錄授權域名,文檔里面也有寫的:https://pay.weixin.qq.com/wik..

統一下單

官方文檔:https://pay.weixin.qq.com/wik...
/**
 * 統一訂單
 */
public function unifiedorder(){
    // 以下配置是必填項,如有其它需求請自行配置
    $config = array(
        'appid'         =>    'xxxxxxx',//這里是小程序appid
        'mch_id'        =>    'xxxxxxx',//商戶ID
        'nonce_str'     =>    $this->getNonceStr(),//隨機字符串
        'body'          =>    '這里是測試 - 測試',//請按照文檔要求填寫合格名稱
        'out_trade_no'  =>    time().$this->getNonceStr(2),//流水單號
        'total_fee'     =>    '20',//金額,分為單位,這里是0.2元
        'spbill_create_ip' => '123.123.123.123',//當前IP
        'notify_url'    =>    'http://xxxx.com',//請恕我愚昧,我沒搞懂他有什么用
        'trade_type'    =>    'JSAPI',//必須填寫JSAPI
        'openid'        =>    'xxxxxxxx'//當前用戶的openid,在trade_type=JSAPI的時候,此項就變成必填項了
    );
    $config['sign'] = $this->getSignPay($config);
    $xmlData = $this->ToXml($config);//轉成xml數據
    $postData = $this->http_post($xmlData);
    $arrayData = $this->FromXml($postData);
    if($arrayData['return_code'] == 'SUCCESS' || $arrayData['result_code'] == 'SUCCESS'){
        return $arrayData['prepay_id'];//重點來了:走了這么多路,就為了這個值。到這一步就證明成功一多半了。
    }else{
        return $arrayData;//返回錯誤
    }
}

/**
 * 獲取簽名
 */
public function getSignPay($config){
    $key = 'xxxxxxx';//商戶秘鑰,就是自己生成的32位密碼
    $strA = 'appid='.$config['appid'].'&body='.$config['body'].'&mch_id='.$config['mch_id'].'&nonce_str='.$config['nonce_str'].'&notify_url='.$config['notify_url'].'&spbill_create_ip'.$config['spbill_create_ip'].'&total_fee='.$config['total_fee'].'&trade_type='.$config['trade_type'];//ASCII 字典序
    $strB = $strA.'&key='.$key;
    $sign = strtoupper(md5($strB));//大寫MD5
    return $sign;
}

/**
 * 隨機字符串 32位
 */
public function getNonceStr($length = 32){
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {  
        $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
    } 
    return $str;
}

/**
 * array轉XML
 */
public function ToXml($data){
    if(!is_array($data) || count($data) <= 0){
        throw new WxPayException("數組數據異常!");
    }
    $xml = "<xml>";
    foreach ($data as $key=>$val){
        $xml.="<".$key.">".$val."</".$key.">";
    }
    $xml.="</xml>";
    return $xml; 
}

/**
 * xml轉array
 */
public function FromXml($xml){    
    if(!$xml){
        throw new WxPayException("xml數據異常!");
    }
    libxml_disable_entity_loader(true);
    $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $this->values;
}


/**
 * post 請求
 */
public function http_post($url,$param,$post_file=false){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
        $is_curlFile = true;
    } else {
        $is_curlFile = false;
        if (defined('CURLOPT_SAFE_UPLOAD')) {
            curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
        }
    }
    if (is_string($param)) {
        $strPOST = $param;
    }elseif($post_file) {
        if($is_curlFile) {
            foreach ($param as $key => $val) {
                if (substr($val, 0, 1) == '@') {

                }
            }
        }
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach($param as $key=>$val){
            $aPOST[] = $key."=".urlencode($val);
        }
        $strPOST =  join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST,true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

好了現在已經獲取到了 prepay_id 的值,我們的統一下單就算完成了,其實我更樂意叫他數據封

小程序微信支付

官方文檔:https://developers.weixin.qq....

先來一個插曲,首先我們小程序的前端需要去觸發pay,實現的功能肯定是要點擊小程序的一個觸發,然后才能支付對吧,

pay:function(e){
    //這里面使用post去請求。然后通過我接下來要寫的API支付代碼獲取小程序支付參數
    success:function(res){
         wx.requestPayment({
             'timeStamp':toString(res.timeStamp),//這里轉字符串,這里被坑過,不轉的話可能會出現total_fee為空
             'nonceStr':toString(res.nonceStr),
             'package':toString(res.package),
             'signType':'MD5',
             'paySign':toString(res.paySign),
             success:function(res){
                 console.log(res);//這里可以跳轉到帶參地址
             },
             fail:function(res){
                 console.info('支付失敗',res);
             },
             complete:function(){
                 console.info('支付觸發回調',res);
             }
         })  
    }
       
}

api支付

也就是上面小程序代碼的后端請求地址

/**
 * api組裝數據
 */
public function payApiBlack(){
    $appid = 'xxxxxx';//小程序appid,上面有重復,不過這樣比較直觀
    $timeStamp = time();
    $nonceStr = $this->getNonceStr();//這是調用統一下單里面的方法,為了直觀,我把這些代碼都寫在了一個類里
    $package = 'prepay_id='.$this->unifiedorder();
    $signType = 'MD5';
    $key = 'xxxxxx';//這里是商戶秘鑰,32位,同上面也有
    $strA = 'appId='.$appid.'&nonceStr='.$nonceStr.'package='.$package.'&= signType='.$signType.'&timeStamp='.$timeStamp.'&key='.$key;
    $paySign = strtoupper(md5($strA));
    $data = array(
        'appid'=>$appid,
        'timeStamp'=>$timeStamp,
        'nonceStr'=>$nonceStr,
        'package'=>$package,
        'signType'=>$signType
    );
    return $data;//返回給小程序
}

以上就是全部代碼,還有小程序的支付回調沒有什么信息,所以,我的思路判斷success后進行跳轉帶參

//此代碼為wx.requestPayment success,部分代碼省略
//res 回調參數包括用戶uid及其他重要傳遞
success:function(res){
    wx.redirect({
        url:'pages/pay/done?uid='+res.uid
    })
}

當然那個統一下單的 notify_url 好像與回調有關,至于怎么用,試了幾次回調的CURD都沒反應,所以有空再研究啦。

以上是“微信小程序如何實現支付功能”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女