微信小程序實現支付功能

小程序支付,沒有封裝支付代碼:直接上一段可用的流程代碼吧:
微信小程序支付官網文檔有詳細的說明,這裏我就再也不贅述啦:
客戶端js:php

wx.request({
url:'https://www.xxxx.com/order/store',//改爲你本身的連接
header:{
'Content-Type':'application/x-www-form-urlencoded'
},
method:'POST',
success:function(res){
console.log(res.data);
console.log('調起支付');
wx.requestPayment({
'timeStamp': res.data.timeStamp,
'nonceStr': res.data.nonceStr,
'package': res.data.package,
'signType':'MD5',
'paySign': res.data.paySign,
'success':function(res){
console.log('success');
wx.showToast({
title:'支付成功',
icon:'success',
duration:3000
});
},
'fail':function(res){
console.log('fail');
},
'complete':function(res){
console.log('complete');
}
});
},
fail:function(res){
console.log(res.data)
}
});

後端部分:laravel5:<?phplaravel

namespace App\Http\Controllers\Api\Order; use App\Models\Order; use App\Models\OrderGoods; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Member; use App\Models\MemberAddress; use App\Models\Product; use App\Http\Requests; use App\Http\Requests\Interfaces\MemberCheck; use Carbon\Carbon; class OrderController extends Controller { use MemberCheck; public function __construct() { $config = array( 'appid'         => env('WECHAT_APPID'),//小程序appid
            'pay_mchid'     => env('WECH_ID'),//商戶號
            'pay_apikey' =>env('WECHAT_KEY'),//可在微信商戶後臺生成支付祕鑰
 ); $this->config = $config; } /** * 生成訂單號 * @author lxhui<772932587@qq.com> * @since 1.0 * @return array */
    private static function trade_no() { list($usec, $sec) = explode(" ", microtime()); $usec = substr(str_replace('0.', '', $usec), 0 ,4); $str  = rand(10,99); return date("YmdHis").$usec.$str; } /** * order * @author lxhui<772932587@qq.com> * @since 1.0 * @return array */
    public function store(Request $request ) { \DB::beginTransaction(); try{ if( !$this->checkMember(['openid'=>$request->openid])) return response()->json(['code'=>200,'status'=>0,'message'=>'該openid未註冊']); $config = $this->config; $result =json_decode($request->apiParams,true); if( !$result['addressInfo']) return response()->json(['code'=>200,'status'=>0,'message'=>'收貨地址不能爲空']); if( !$result['orderInfo']) return response()->json(['code'=>200,'status'=>0,'message'=>'訂單商品不能爲空']); $address_data = [ 'openid'=>$request->openid,
                'realname'=>$result['addressInfo']['userName'],
                'mobile'=>$result['addressInfo']['telNumber'],
                'province'=>$result['addressInfo']['provinceName'],
                'city'=>$result['addressInfo']['cityName'],
                'area'=>$result['addressInfo']['countyName'],
                'address'=>$result['addressInfo']['detailInfo'],
                'zipcode'=>$result['addressInfo']['postalCode'], ]; $model = MemberAddress::firstOrCreate($address_data); $productArray =$result['orderInfo']; $products = []; $orderProducts = []; $productsFee = 0.0; //支付商品總價
            foreach ($productArray as $val) { $product = Product::find($val['goodsid']); $productsFee += $product->marketprice * $val['total']; } // 計算價格
            $shippingFee = 10.0; $totalFee = $productsFee + $shippingFee; // 建立訂單
            $ordersn = self::trade_no(); $order = new Order(); $order->ordersn = $ordersn; $order->openid = $request->openid; $order->price = $totalFee; $order->goodsprice = $totalFee; $order->createtime =time(); $order->addressid = $model->id; $order->storeid = $request->storeid; $order->save(); $orderid = $order->id; $order_goods = new OrderGoods(); foreach ($productArray as $val) { $product = Product::find($val['goodsid']); $product=['orderid'=>$orderid,'goodsid'=>$val['goodsid'],'price'=>$product->marketprice,'total'=>$val['total'],'openid'=>$request->openid]; array_push($products, $product); } /* 生產預訂單參數 */
            $openid = $request->openid; $body = '商城訂單'; $order_sn = $ordersn; $total_fee = $totalFee; //統一下單參數構造
            $unifiedorder = array( 'appid'            => $config['appid'],
                'mch_id'        => $config['pay_mchid'],
                'nonce_str'        => self::getNonceStr(),
                'body'            => $body,
                'out_trade_no'    => $order_sn,
                'total_fee'        => $total_fee * 100,
                'spbill_create_ip'    => $request->getClientIp(),
                'notify_url'    => 'https://'.$_SERVER['HTTP_HOST'].'/Api/Wxpay/notify',// 支付微信回調的url,可自定義,非必須
                'trade_type'    => 'JSAPI',
                'openid'        => $request->openid,//'oIXoL0ZpfG3NdSE8Qa-S1GcEHJGY'//測試openid
 ); $unifiedorder['sign'] = self::makeSign($unifiedorder); //請求數據
            $xmldata = self::array2xml($unifiedorder); $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; $res = self::curl_post_ssl($url, $xmldata); if(!$res){ return response()->json(['code'=>200,'status'=>0,'message'=>'沒法鏈接服務器']); //self::return_err("Can't connect the server");
 } //file_put_contents是用來查看服務器返回的結果 測試完能夠刪除了,能夠使用laravel自帶日誌功能 //file_put_contents('/public/log.txt',$res,FILE_APPEND);
        \Log::info(json_encode($res));
$content = self::xml2array($res); $result_code= isset($content['result_code']) ? $content['result_code'] : ''; $return_code = isset($content['return_code']) ? $content['return_code'] : ''; if(strval($result_code) == 'FAIL'){ return self::return_err(strval($content['err_code_des'])); } if(strval($return_code) == 'FAIL'){ return self::return_err(strval($content['return_msg'])); } $data = $this->pay($content['prepay_id']); \DB::table("eshop_order_goods")->insert($products); \DB::commit(); return response()->json(['code'=>200,'status'=>1,'message'=>'提交成功','data'=>$data]); } catch (\Exception $e){ \DB::rollback();//事務回滾 return response()->json(['code'=>200,'status'=>0,'message'=>$e->getMessage()]); } } /** * 進行支付接口簽名 * @param string $prepay_id 預支付ID(調用prepay()方法以後的返回數據中獲取) * @return json的數據 */ public function pay($prepay_id){ $config = $this->config; $data = array( 'appId' => $config['appid'], 'timeStamp' => time(), 'nonceStr' => self::getNonceStr(), 'package' => 'prepay_id='.$prepay_id, 'signType' => 'MD5' ); $data['paySign'] = self::makeSign($data); return $data; } //微信支付回調驗證 public function notify(){ $xml = $GLOBALS['HTTP_RAW_POST_DATA']; // 這句file_put_contents是用來查看服務器返回的XML數據 測試完能夠刪除了 //file_put_contents(APP_ROOT.'/Statics/log2.txt',$res,FILE_APPEND); //將服務器返回的XML數據轉化爲數組 $data = self::xml2array($xml); // 保存微信服務器返回的簽名sign $data_sign = $data['sign']; // sign不參與簽名算法 unset($data['sign']); $sign = self::makeSign($data); // 判斷簽名是否正確 判斷支付狀態 if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) { $result = $data; //獲取服務器返回的數據 $order_sn = $data['out_trade_no']; //訂單單號 $openid = $data['openid']; //付款人openID $total_fee = $data['total_fee']; //付款金額 $transaction_id = $data['transaction_id']; //微信支付流水號 //更新數據庫 $this->updateDB($order_sn,$openid,$total_fee,$transaction_id); }else{ $result = false; } // 返回狀態給微信服務器 if ($result) { $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'; }else{ $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[簽名失敗]]></return_msg></xml>'; } echo $str; return $result; } //---------------------------------------------------------------用到的函數------------------------------------------------------------ /** * 錯誤返回提示 * @param string $errMsg 錯誤信息 * @param string $status 錯誤碼 * @return json的數據 */ protected function return_err($errMsg='error',$status=0){ return response()->json(['code'=>200,'result'=>'fail','status'=>$status,'errmsg'=>$errMsg]); } /** * 正確返回 * @param array $data 要返回的數組 * @return json的數據 */ protected function return_data($data=array()){ return response()->json(['code'=>200,'result'=>'success','status'=>1,'data'=>$data]); } /** * 將一個數組轉換爲 XML 結構的字符串 * @param array $arr 要轉換的數組 * @param int $level 節點層級, 1 爲 Root. * @return string XML 結構的字符串 */ protected function array2xml($arr, $level = 1) { $s = $level == 1 ? "<xml>" : ''; foreach($arr as $tagname => $value) { if (is_numeric($tagname)) { $tagname = $value['TagName']; unset($value['TagName']); } if(!is_array($value)) { $s .= "<{$tagname}>".(!is_numeric($value) ? '<![CDATA[' : '').$value.(!is_numeric($value) ? ']]>' : '')."</{$tagname}>"; } else { $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."</{$tagname}>"; } } $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s); return $level == 1 ? $s."</xml>" : $s; } /** * 將xml轉爲array * @param string $xml xml字符串 * @return array 轉換獲得的數組 */ protected function xml2array($xml){ //禁止引用外部xml實體 libxml_disable_entity_loader(true); $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } /** * * 產生隨機字符串,不長於32位 * @param int $length * @return 產生的隨機字符串 */ protected 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; } /** * 生成簽名 * @return 簽名 */ protected function makeSign($data){ //獲取微信支付祕鑰 $key = $this->config['pay_apikey']; // 去空 $data=array_filter($data); //簽名步驟一:按字典序排序參數 ksort($data); $string_a=http_build_query($data); $string_a=urldecode($string_a); //簽名步驟二:在string後加入KEY //$config=$this->config; $string_sign_temp=$string_a."&key=".$key; //簽名步驟三:MD5加密 $sign = md5($string_sign_temp); // 簽名步驟四:全部字符轉爲大寫 $result=strtoupper($sign); return $result; } /** * 微信支付發起請求 */ protected function curl_post_ssl($url, $xmldata, $second=30,$aHeader=array()){ $ch = curl_init(); //超時時間 curl_setopt($ch,CURLOPT_TIMEOUT,$second); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); //這裏設置代理,若是有的話 //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98'); //curl_setopt($ch,CURLOPT_PROXYPORT, 8080); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); if( count($aHeader) >= 1 ){ curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader); } curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS,$xmldata); $data = curl_exec($ch); if($data){ curl_close($ch); return $data; } else { $error = curl_errno($ch); echo "call faild, errorCode:$error\n"; curl_close($ch); return false; } } }

返回結果:算法

{
    "code": 200,
    "status": 1,
    "message": "提交成功",
    "data": {
        "appId": "wxaxxxxxxxxxxxxx",
        "timeStamp": 1499497335,
        "nonceStr": "qqejagkybrh9rxmyfosze71qs49ppcub",
        "package": "prepay_id=wx2017070815022850d11adcb80558793405",
        "signType": "MD5",
        "paySign": "285BCE1F0B93701D927FA5F6CBE10E86"
    }
}

代碼沒有完美封裝,博友們若是有一套好的封裝,請留下共享地址哈啊數據庫

相關文章
相關標籤/搜索