主頁 > 知識庫 > php實現(xiàn)小程序支付完整版

php實現(xiàn)小程序支付完整版

熱門標簽:合肥企業(yè)外呼系統(tǒng)線路 萍鄉(xiāng)商鋪地圖標注 神龍斗士電話機器人 企業(yè)400電話辦理多少費用 代理打電話機器人 太原400電話申請流程 電信外呼系統(tǒng)多少錢一個月 宿州正規(guī)外呼系統(tǒng)軟件 桂陽公司如何做地圖標注

本文實例為大家分享了php實現(xiàn)小程序支付的具體代碼,供大家參考,具體內(nèi)容如下

環(huán)境: tp3.2  + 小程序 微信支付功能開通

Step1:  下載PHP 支付SDK(下載地址)  放到Library\Vendor下,取名Wxpay           

修改WxPay.Config.php 里的appid appsecret key MCHID

Step2: 小程序 js 代碼:

 var url = getApp().globalData.httpServer + 'api/buy/pay';
    var userId = getApp().globalData.userId;
    var totalMoney = this.data.totalMoney;
    var cart = this.data.goods;
    var param = {
      cart: JSON.stringify(cart),
      cartamount: totalMoney,
      userid: userId,
      payment: this.data.payment,
      addressid: defaultAddress.id
    };
    var that = this;
    util.http(url, param, function (ret) {
      if (ret.data.code == 1) {
        if (that.data.payment == 'balance') { // 余額支付
          that.afterPaySuccess(ret.data.data);
        } else {                // 微信支付
          wx.requestPayment({
            timeStamp: ret.data.data.timeStamp,
            nonceStr: ret.data.data.nonceStr,
            package: ret.data.data.package,
            signType: ret.data.data.signType,
            paySign: ret.data.data.paySign,
            'success': function (res) {
              that.afterPaySuccess(ret.data.data.orderid);
            },
            'fail': function (res) {
              console.log(res);
            }
          })          
 
 
        }
 
      } else {
        util.showTip(ret.data.msg, '提交訂單失敗');        
      }
    });
/**
 * 網(wǎng)絡請求
 */
function http(url, params, callback) {
  wx.request({
    url: url,
    data: params,
    success: function (res) {
      callback(res);
    },
 
    fail: function (err) {
      console.log(err);
    }
  });
}

Step3: 接口代碼:

  public function pay()
  {
    $cart = I('cart', '', 'trim');
    $cartAmount = I('cartamount');
    $addressId = I('addressid', 0, 'intval');
    $payment = I('payment', '', 'trim');
    $userId = $this->userid;
 
    $cart = json_decode($cart, true);
    if (empty($cart)) {
      $result['msg'] = '購物車獲取失敗';
      $result['code'] = 0;
      $this->ajaxReturn($result);
    }
 
    $totalMoney = 0;
    foreach ($cart as $goods) {
      $money = $goods['price'];  // price
      $selectCount = $goods['selectcount'];  // price
      $itemAmount = number_format($money * $selectCount, 2, '.', '');
      $totalMoney += $itemAmount;
    }
    // 檢查總金額是否一致
    if ($totalMoney != $cartAmount) {
      $result['msg'] = '總金額不匹配:' . $totalMoney;
      $result['code'] = 0;
      $this->ajaxReturn($result);
    }
 
    // 獲取用戶地址
    $address = M('MemberAddress')->where('userid=' . $userId . " and id=" . $addressId)->find();
    if (empty($address)) {
      $result['msg'] = '用戶地址不存在';
      $result['code'] = 0;
      $this->ajaxReturn($result);
    }
 
    // 用戶信息
    $user = M('Member')->where("id=" . $userId)->find();
    if ($payment == 'balance') {
      if ($user['amount']  $cartAmount) {
        $result['msg'] = '余額不足';
        $result['code'] = 0;
        $this->ajaxReturn($result);
      }
    }
 
    // 生成訂單
    $order['ordersn'] = $this->genOrdersn($user['id']);
    $order['price'] = $cartAmount;
    $order['addressid'] = $address['id'];
    $order['addressinfo'] = serialize($address); //json_encode($address);
    $order['longitude'] = $address['longitude'];
    $order['latitude'] = $address['latitude'];
    $order['addtime'] = time();
    $order['status'] = 0;
    $order['userid'] = $user['id'];
    $order['paytype'] = $payment;
    $order['paysn'] = '';
    $order['paytime'] = time();
    $orderId = M("Order")->add($order);
    if ($orderId == 0) {
      $result['msg'] = '創(chuàng)建訂單失敗';
      $result['code'] = 0;
      $this->ajaxReturn($result);
    }
    foreach ($cart as $goods) {
      $orderGoods['orderid'] = $orderId;
      $orderGoods['goodsid'] = $goods['id'];
      $orderGoods['title'] = $goods['title'];
      $orderGoods['price'] = $goods['price'];
      $orderGoods['attr'] = $goods['attr'];
      $orderGoods['pic'] = $goods['pic'];
      $orderGoods['num'] = $goods['selectcount'];
      M("OrderGoods")->add($orderGoods);
    }
 
    if ($payment == 'balance') {
      // 余額支付
      $this->balancePay($cartAmount, $user['wxopenid'], $orderId);
    } else if ($payment == 'weixin') {
      // 微信支付
      $this->weixinPay($cartAmount, $user['wxopenid'], $orderId, $order['ordersn']);
    }
  }
  /**
   * 微信支付
   * @author 大臉貓臉大
   * @param $cart
   * @param $cartAmount
   * @param $address
   * @param $user
   */
  private function weixinPay($cartAmount, $openId, $orderId, $orderSn)
  {
 
    import("Vendor.Wxpay.lib.WxPay#Api", "", ".php");
    //訂單號
    $money = $cartAmount * 100;
    $openid = $openId;
    $input = new \WxPayUnifiedOrder();
    $input->SetBody("迪克-商品");
    $input->SetOut_trade_no("$orderSn");
    $input->SetTotal_fee("$money");
    $input->SetNotify_url("https://" . $_SERVER['HTTP_HOST'] . "/api/buy/payNotify");
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openid);
    $unifiedOrder = \WxPayApi::unifiedOrder($input);
 
    if ($unifiedOrder['result_code'] == 'SUCCESS'  $unifiedOrder['return_code'] == 'SUCCESS') {
      $time = time();
      $data['timeStamp'] = "$time";              //時間戳
      $data['nonceStr'] = $unifiedOrder['nonce_str'];     //隨機字符串
      $data['signType'] = 'MD5';                //簽名算法,暫支持 MD5
      $data['package'] = 'prepay_id=' . $unifiedOrder['prepay_id'];  //統(tǒng)一下單接口返回的 prepay_id 參數(shù)值,提交格式如:prepay_id=*
      $data['paySign'] = $this->genPaySign($unifiedOrder, $time);// 之前以為是$unifiedOrder['sign']; 后來發(fā)現(xiàn)是調(diào)用的這種方法. 簽名方案參見微信公眾號支付幫助文檔;
 
      $data['out_trade_no'] = $orderSn; 
      $data['orderid'] = $orderId; 
      $return['code'] = 1; 
      $return['data'] = $data; 
    } else { 
        Log::write(var_export($unifiedOrder, true), Log::ERR, '', C('LOG_PATH')."wx_pay_".date('y_m_d').'.log'); 
        $return['code'] = 0; 
        $return['msg'] = '微信支付失敗';// $unifiedOrder['RETURN_MSG']; 
    } 
    $this->ajaxReturn($return); 
}
/* 生成支付簽名*/
private function genPaySign($unifiedOrder, $time)
{
  $appId = \WxPayConfig::APPID;
  $nonceStr = $unifiedOrder['nonce_str'];
  $package = 'prepay_id=' . $unifiedOrder['prepay_id'];
  $signType = "MD5";
  $timeStamp = $time;
  $key = \WxPayConfig::KEY;

  $sign = md5(sprintf("appId=%snonceStr=%spackage=%ssignType=%stimeStamp=%skey=%s", $appId, $nonceStr, $package, $signType, $timeStamp, $key));
}
 /**
   * 支付回調(diào)
   * @author:大臉貓臉大
   */
  public function payNotify()
  {
    import("Vendor.Wxpay.lib.WxPay#Data", "", ".php");
    $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
    $val = \WxPayResults::Init($xml);
 
    if ($val['result_code'] == 'SUCCESS'  $val['return_code'] == 'SUCCESS') {
 
      $orderSn = $val['out_trade_no'];
      $transactionId = $val['transaction_id'];
      $data = array('paytype' => 'weixin', 'status' => '1', 'paytime' => time(), 'paysn' => $transactionId);
 
      M("Order")->where("ordersn='$orderSn'")->setField($data);
      exit('xml>return_code>![CDATA[SUCCESS]]>/return_code>return_msg>![CDATA[OK]]>/return_msg>/xml>');
    }else {
      Log::write(var_export($val, true), Log::ERR, '', C('LOG_PATH')."wx_pay_notify_".date('y_m_d').'.log');
      exit('xml>return_code>![CDATA[FAIL]]>/return_code>return_msg>![CDATA[OK]]>/return_msg>/xml>');
    }
}

payNotify 回調(diào)方法里一定要注意返回

復制代碼 代碼如下:
xml>return_code>![CDATA[SUCCESS]]>/return_code>return_msg>![CDATA[OK]]>/return_msg>/xml>

如果不處理,你會發(fā)現(xiàn)payNotify  會被執(zhí)行很多次參見:官方文檔

總結一下:

注意二點,1.簽名的問題 2. 回調(diào)方法的返回處理。

歡迎大家指正。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • PHP:微信小程序 微信支付服務端集成實例詳解及源碼下載
  • 微信小程序 支付功能實現(xiàn)PHP實例詳解
  • 微信小程序與php 實現(xiàn)微信支付的簡單實例
  • 微信小程序支付功能 php后臺對接完整代碼分享
  • 微信小程序支付PHP代碼
  • 詳解PHP實現(xiàn)支付寶小程序用戶授權的工具類
  • 微信小程序 PHP后端form表單提交實例詳解
  • 微信小程序調(diào)用PHP后臺接口 解析純html文本
  • 微信小程序request請求后臺接口php的實例詳解
  • PHP小程序支付功能完整版【基于thinkPHP】

標簽:太原 崇左 鄂州 綏化 辛集 廊坊 白銀 衡陽

巨人網(wǎng)絡通訊聲明:本文標題《php實現(xiàn)小程序支付完整版》,本文關鍵詞  php,實現(xiàn),小,程序,支付,完,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《php實現(xiàn)小程序支付完整版》相關的同類信息!
  • 本頁收集關于php實現(xiàn)小程序支付完整版的相關信息資訊供網(wǎng)民參考!
  • 推薦文章