微信小程序支付-PHP后端

一、前端代码:

1.先写一个可以点击支付的按钮

<view class="chongzhi_button" bindtap="pay">支付</view>

2.开始js代码

pay: function(){
    //下订单并唤起微信支付
    var price = '0.01'; //支付金额
    var openid = ''; //这里传用户openid,怎么获取用户的openid这里就不详细的说了
    var that = this;
    wx.request({
      url: '这里写后端接口地址',
      data: {
        price: price,
	openid: openid
      },
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        //客户单发起微信请求
        wx.requestPayment({
            'appId': '这里写小程序的appId',
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': 'MD5',
            'paySign': res.data.paySign,
            'success': function (res) {
              wx.showToast({
                title: '支付成功',
                duration: 1200
              })
              console.log('支付成功');
              setTimeout(function () {
                wx.redirectTo({
                  url: '../pay/payok?paymoney=' + that.data.paymoney + '&body=' + that.data.contents
                })
              }, 1000);
              //这里完成跳转
            },
            'fail': function (res) {
              if (res.errMsg == "requestPayment:fail cancel") {
                wx.showToast({
                  title: '支付取消',
                  duration: 1200
                })
              } else {
                wx.showToast({
                  title: '支付失败',
                  image: '../../images/error.png',
                  duration: 1200
                })
              }
              //支付失败
              console.log(res);
            },
            'complete': function (res) { }
          })
      }
    })

二、然后开始后端代码(这里用PHP代码作为示例,没办法,只会PHP,这里直接用easywechat开源的SDK开发,SDK下载及支付配置请看https://www.easywechat.com/

代码开始

public function __construct()
{
$this->app = Factory::payment(config(“wechat.payment.default”));
}

public function doPay(Request $request)
{
    $where = [
        ['id','=',$order_id],
    ];
    $info = Db::name('order')->where($where)->field('id,order_no,real_money,total_num,title,pay_status,order_status,unique_number')->find();
    $order_data['source'] = $order_source_type;
    $order_data['order_no'] = createOrderNo();
    if (empty($info)) {
        return $this->apiReturn(ERROR, [], '订单信息不存在');
    }
    if ($info['order_status'] != 1) {
        return $this->apiReturn(ERROR, [], '订单已支付');
    }
    if ($info['pay_status'] == 1) {
        return $this->apiReturn(ERROR, [], '订单已支付');
    }
    if ($payment_type == 'wx_pay') {
        $userinfo = Db::name('user')->where("unique_number",$info['unique_number'])->field('xcx_open_id')->find();
        $order_data['pay_time'] = time();
        $order_data['payment_type'] = 'jsapi';
        $order_data['trade_type'] = 'jsapi';
        Db::name('order')->where('id', $order_id)->update($order_data);
        $order_data['openid'] = $userinfo['xcx_open_id'];

        $order_data['total_fee'] = APP_STATUS == 'localhost' ? 1 : $info['real_money'];
        $result = $this->unifiedOrderXcx($order_data);
        $con = $this->jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
        return $this->apiReturn(SUCCESS,$con,'成功');
    }else{
        return $this->apiReturn(ERROR,[],'未知错误');
    }
}
/*
 * 统一下单
 */
public function unifiedOrder($params)
{
    return $this->xcx->order->unify([
        'body' => '测试',
        'out_trade_no' => $params['order_no'],
        'total_fee' => $params['total_fee'],
        'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
        'openid' => $params['openid'],
        'notify_url' => $this->request->domain() . '/api/Apinotfy/wx_page_payment_notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
    ]);
}
/**
 * 支付回调通知
 */
public function wx_page_payment_notify()
{
    $response = $this->app->handlePaidNotify(function ($message, $fail) {
        if ($message['return_code'] === 'SUCCESS') {
            // 取出订单,检测是否存在
            $order = Db::name("order")->where("order_no", $message['out_trade_no'])->find();
            logs(json_encode($order), 'wx_page_refund');

            if (!$order) { // 如果订单不存在
                logs('无效的订单信息', 'wx_page_refund_log');
                return $fail("无效的订单信息");
            }

            if ($order['pay_status'] == 1) {
                logs('请勿重复支付', 'wx_page_refund_log');
                return $fail("请勿重复支付");
            }

            if ($order['order_status'] != 1) {
                logs('请勿重复支付', 'wx_page_refund_log');
                return $fail("请勿重复支付");
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付 /////////////
            $check = $this->app->order->queryByOutTradeNumber($message['out_trade_no']);

            //未支付
            if ($check['trade_state'] != 'SUCCESS') {
                return $fail("支付失败");
            }

            //支付金额
            $money = bcdiv($message['total_fee'], 100, 2); //通知信息里的金额是分,需换成元
            $money = $message['total_fee']; //通知信息里的金额是分,需换成元
            if (APP_STATUS != 'localhost') {
                if ($order['real_money'] != $money) {
                    return $fail('支付金额不匹配');
                }
            }

            // 用户是否支付成功
            if ($message['result_code'] == 'SUCCESS') {
                //更新订单状态等信息
                $data = [
                    "transaction_id" => $message['transaction_id'],
                    "order_status" => 2,
                    "pay_status" => 1,
                    "update_time" => time(),
                ];
                if ($order['source_type'] == 2) {
                    $data['check_status'] = 1;
                }

                $bool = Db::name("order")->where("order_no", $message['out_trade_no'])->update($data);
                if (!$bool) {
                    return $fail("更新订单信息失败");
                }
                // 用户支付失败
            } elseif ($message['result_code'] == 'FAIL') {
                return $fail("支付失败");
            }
            return true; // 返回处理完成
        } else {
            return $fail('通信失败,请稍后再通知我');
        }
    });
    $response->send();
    //return $response;
}

三、最后,一定会支付成功

标签

发表评论