tp5 快速接入扫码支付

前提是申请好微信支付,同时配置好key,以及支付回调地址

1.composer

composer require yansongda/pay

2.引入

use Yansongda\Pay\Pay; // 引入支付

3.获取支付二维码字符串

/**
     * @param $order_num
     * @param $price
     * @param string $pinfo
     * @return object
     */
    public function _get_wx_pay_code($order_num,$price,$pinfo = '')
    {
        $order_code_url = Cache::store('redis')->get($order_num);
        if ($order_code_url){
            return $order_code_url;
        }
        $config = [
            'wechat' => [
                'app_id' => config('wechat.app_id'),
                'mch_id' => config('wechat.mch_id'),
                'notify_url' => config('wechat.notice_uri'),
                'key' => config('wechat.key'),
                'cert_client' => './apiclient_cert.pem',
                'cert_key' => './apiclient_key.pem',
            ],
        ];

        $config_biz = [
            'out_trade_no' => $order_num,           // 订单号
            'total_fee' => $price,              // 订单金额,**单位:分**
            'body' => $pinfo,                   // 订单描述
            'spbill_create_ip' => Func::get_ip(),       // 调用 API 服务器的 IP
            'product_id' => 'pid',             // 订单商品 ID
        ];

        $pay = new Pay($config);
        $code_url = $pay->driver('wechat')->gateway('scan')->pay($config_biz); // 扫码支付,返回支付码
        Cache::store('redis')->set($order_num,$code_url,3600);
        return $code_url;
}

4.回调出,进行订单处理

// 微信支付回调
    public function index()
    {
        Clog::setLog('pay_success','wx_pay');
        $str = $GLOBALS['HTTP_RAW_POST_DATA'];

        $arr = array();
        $xmlTag = array(
            'appid','bank_type','cash_fee','fee_type','is_subscribe','mch_id',
            'nonce_str','openid','out_trade_no','result_code','return_code','sign',
            'time_end','total_fee','trade_type','transaction_id'
        );
        foreach($xmlTag as $x){
            preg_match_all("/<".$x.">.*<\/".$x.">/",$str,$temp);
            $arr[$x] = $temp[0][0];
        }
        //去除XML标签并组装数据
        $data = array();
        foreach($arr as $key => &$value) {
            if ($key == 'total_fee'){
                $temp_a = explode('<'.$key.'>', $value);
                $last_str = "</".$key.">";
                $str_len = strlen($last_str);//  该字符串长度;?????????
                $v = substr($temp_a[1],0,-$str_len);
                $value = $v;
            }else{
                $temp_a = explode('<'.$key.'>'.'<![CDATA[', $value);
                $last_str = "]]</".$key.">";
                $str_len = strlen($last_str);//  该字符串长度;
                $v = substr($temp_a[1],0,-$str_len-1);
                $value = $v;
            }
        }

        Clog::setLog(var_export($arr, true),'wx_pay_arr');

        $param = $arr;

        Clog::setLog($param);
        Clog::setLog($param['appid']);
        Clog::setLog($param['out_trade_no']);
        Clog::setLog($param['return_code']);

        if(!$param['out_trade_no']){
            echo "FAIL";
            Clog::setLog('111111');
            Clog::setLog($param['out_trade_no'].' 10001','wx_pay');
            return;
        } else {
            Clog::setLog('22222');
            if ($param['return_code'] == 'SUCCESS') { // 支付成功
                $order_num = $param['out_trade_no'];
                $transaction_id = $param['transaction_id'];

                Clog::setLog('33333');
                // 处理订单状态
                $order_info = Db::name('order')
                    ->where('order_num',$order_num)
                    ->find();

                if ($order_info['status'] != self::ORDER_CREATE) {
                    Clog::setLog($param['out_trade_no'].' Has Payed','wx_pay');
                    return;
                }

                $order_data['pay_time'] = time();
                $order_data['status'] =   self::ORDER_PAY;
                $order_data['transaction_id'] =   $transaction_id;

                Db::startTrans();
                $error = 0;

                $r = Db::name('order')
                    ->where('order_num',$order_num)
                    ->data($order_data)
                    ->update();

                if (!$r && $r !==0) {
                    $error ++;
                }

                // 处理优惠券
                if ($order_info['user_coupon_id'] > 0) {
                    Clog::setLog('44444');
                    $coupon_data['is_use'] = 1;
                    $coupon_data['update_time'] = time();
                    $r = Db::name('user_coupon')
                        ->where('id',$order_info['user_coupon_id'])
                        ->data($order_data)
                        ->update();
                    if (!$r && $r !==0) {
                        $error ++;
                    }

                    $coupon_id = Db::name('user_coupon')
                        ->where('id',$order_info['user_coupon_id'])
                        ->value('coupon_id');

                    $r = Db::name('coupon')
                        ->where('id',$coupon_id)
                        ->inc('used_number',1)
                        ->update();

                    if (!$r && $r !==0) {
                        $error ++;
                    }

                }


                if ($order_info['from'] == 1) { // 购物车
                    // 清空购物车
                    $r = Db::name('shopping_car')
                        ->where('user_id', $order_info['user_id'])
                        ->delete();

                    if (!$r && $r !==0) {
                        $error ++;
                    }
                }

                if ($error == 0) {
                    Db::commit();
                    Clog::setLog($param['out_trade_no'].' 0','wx_pay');
                    echo "SUCCESS";
                    return;
                } else {
                    Db::rollback();
                    Clog::setLog($param['out_trade_no'].' 10099','wx_pay');
                    return;
                }

            } else {
                Clog::setLog($param['out_trade_no'].' 10002','wx_pay');
                return;
            }
        }
    }

5.前端写个定时器,查看订单状态是否变更

public function check_pay(){
        $order_id = trim($_REQUEST['order_id']);
        $is_pay = Db::name('order')->where(['id' => $order_id,'status' => 2])->find();
        if ($is_pay){
            $this->json->setErr('0',lang('tips_is_pay'));
        } else {
            $this->json->setErr('10023',lang('tips_not_pay'));
        }
        $this->json->Send();
}

6.支付成功,进行跳转处理。

posted @ 2018-09-19 18:42  TBHacker  阅读(3403)  评论(0编辑  收藏  举报