Php微信小程序支付

9 篇文章 0 订阅
4 篇文章 1 订阅

官方参数

在这里插入图片描述

文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html

小程序中代码

如果说你的小程序中有其他登陆方式,比如手机登陆,那么支付的时候就要先去获取用户的openid

// 获取用户的openid
get_user_openid:function(){
  let that = this;
  let openid = app.globalData.openid;
  if (openid){
    run_pay(that);
  }else{ //  先获取用户openid
    app.get_user_openid(function (data) {
      run_pay(that);
    })
  }
},

下面看看发起支付

// 立即支付
function run_pay(that){
  let bookReadData = wx.getStorageSync('bookReadData');
  let channel = app.globalData.QRXS_CHANNEL;
  let bid = bookReadData.bid;
  app.httpRequest(config.payOrderBe, {}, function (data) {
    let product = '开通畅读卡';
    var postdata = {
      product: product,
      detail: product,
      fee: that.data.pay_price * 100,
      reward: that.data.reward,
      bid: bid,
      channel: channel,
      timestamp: data.timestamp,
      nonceStr: data.nonceStr,
      signature: data.signature,
    }
    postdata['openid'] = app.globalData.openid
    postdata['sign'] = md5.md5(postdata.product + postdata.detail + postdata.fee + postdata.timestamp + postdata.reward + config.APP_KEY);
    app.httpRequest(config.payOrder, postdata, function (data) {
      var res_data = data;
      var nonceStr = res_data.nonceStr;
      var outtradeno = res_data.OutTradeNo;
      var wxpackage = res_data.package;
      var paysign = res_data.paySign;
      var timestamp = res_data.timestamp;

      wx.requestPayment({
        'timeStamp': timestamp,
        'nonceStr': nonceStr,
        'package': wxpackage,
        'signType': 'MD5',
        'paySign': paysign,
        'success': function (res) {
          console.log(res)
          //成功应该要刷新用户信息,还有当前章节是否开通
          if (res.errMsg === "requestPayment:ok") {
            if (that.data.show_back === 1) {
              app.getUserData(); // 刷新用户信息
              wx.redirectTo({
                url: '/pages/buyCard/buyStatus/buyStatus?type=1',
              })
            } else {
              wx.switchTab({
                url: '/pages/my/my'
              })
            }
          }
        },
        'fail': function (res) {
          console.log(res)
          if (res.errMsg == "requestPayment:fail cancel") {
            wx.redirectTo({
              url: '/pages/buyCard/buyStatus/buyStatus?type=0',
            })
          }
        },
        'complete': function (res) {
          console.info('complete');
        }
      });
    });
  })
}

后端发起支付代码

发起支付第一步,获取支付所需信息,
跟网页端支付差不多

// 获取支付所需签名等
function wx_begin(){
     include_once "Application/Xcx4/ORG/WxPaySync/jssdk.php";
     $jssdk = new \JSSDK('wxabxxxxxb66bd', '647474836xxxxxxxxxxxxxxxx9221d724');
     $signPackage = $jssdk->GetSignPackage();
     return_json_data(1,'ok',$signPackage);
 }

发起支付

public function wx_pay(){
    $uid = $this->uid;
    if (!$uid){
        return_json_data(0,'请先登录');
    }
    $userInfo = $this->userInfo;

    $body = I('product','trim','购买书币');		//商品描述
    $detail = I('detail','trim','购买书币'); 	//商品详情
    $total_fee = I('fee','intval',0);					//第三方订单总金额 单位分
    $sign = I('sign','trim,addslashes','');			//APP与应用服务器之间的数据签名
    $month = I('month','trim,addslashes','');			//购买月份数
    $bid = I('bid','intval',0);					 
    $openid = I('openid','trim,addslashes','');		 // 用户openidd 
    $timestamp = $_REQUEST['timestamp'];   //时间戳
    $nonceStr = trim(strip_tags($_REQUEST['nonceStr']));
   
    // 写入订单 
    $out_trade_no = 'xcx'.$this->uid.date("mdHis").rand(2000,8000);
  
    if(!$out_trade_no ){
        return_json_data(0,'充值失败'.$insertId);
    }

    //使用jsapi接口
    $notify_url = $this->notify_host.'/Xcx4/notify/wx';	//通知地址
    include_once "Application/Xcx4/ORG/WxPaySync/WxPayPubHelper.php";
    $jsApi = new \JsApi_pub();
    //使用统一支付接口
    $unifiedOrder = new \UnifiedOrder_pub();
    $unifiedOrder->setParameter("openid",$openid);//商品描述
    $unifiedOrder->setParameter("body","$body");//商品描述
    //自定义订单号,此处仅作举例
    $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号
    cookie('pcode_trade_no',$out_trade_no,60*10);
    //转分
    //$total_fee = $total_fee*100;
    $unifiedOrder->setParameter("total_fee","$total_fee");//总金额
    $unifiedOrder->setParameter("notify_url",$notify_url);//通知地址
    $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型

    $prepay_id = $unifiedOrder->getPrepayId();

    //=========步骤3:使用jsapi调起支付============
    $jsApi->setPrepayId($prepay_id);
    $jsApiParameters = $jsApi->getNewParameters($timestamp,$nonceStr);

    $data = array(
        "timestamp"=>($jsApiParameters["timestamp"]),
        "nonceStr"=>$jsApiParameters['nonceStr'],
        "package"=>$jsApiParameters['package'],
        "signType"=>$jsApiParameters['signType'],
        "paySign"=>$jsApiParameters['paySign'],
        'OutTradeNo'=>$out_trade_no
    );

    return_json_data(1,'ok',$data);
}

支付回调


//v3.0版微信支付回调接口
public function wx(){
	include_once "Application/Xcx4/ORG/WxPaySync/WxPayPubHelper.php";
	//使用通用通知接口
	$notify = new \Notify_pub();

	//存储微信的回调
	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	$notify->saveData($xml);

	//验证签名,并回应微信。
	//对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,
	//微信会通过一定的策略(如30分钟共8次)定期重新发起通知,
	//尽可能提高通知的成功率,但微信不保证通知最终能成功。
	if($notify->checkSign() == FALSE){
		$notify->setReturnParameter("return_code","FAIL");//返回状态码
		$notify->setReturnParameter("return_msg","签名失败");//返回信息
	}else{
		$notify->setReturnParameter("return_code","SUCCESS");//设置返回码
	}

	if($notify->checkSign() == true){
           $out_trade_no = $notify->data["out_trade_no"];//订单号
           $trade_no = $notify->data["transaction_id"];//微信支付订单号
           $result_code = $notify->data["result_code"];//业务结果
           $bank_type = $notify->data["bank_type"];//付款银行
           $is_subscribe = $notify->data["is_subscribe"];//是否关注公众号
           $openid = $notify->data["openid"];

           ///支付成功 业务逻辑操作            
		echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
	}else{
		echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值