Payment.php 23 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
<?php

namespace Shopping;

use LibModels\Web\Home\OrderData;
use LibModels\Web\Product\PayData;
use WebPlugin\Helpers;
use WebPlugin\Cache;
use WebPlugin\Pay\Banks;
use WebPlugin\Pay\PayFactory;
use WebPlugin\Pay\Reqparams;
use WebPlugin\Pay\Rspparams;
use WebPlugin\Pay\weixin\lib\WxPayApi;
use WebPlugin\Pay\weixin\lib\WxPayConfig;
use WebPlugin\Pay\weixin\lib\WxPayNativePay;
use WebPlugin\Pay\weixin\lib\WxPayOrderQuery;
use WebPlugin\Pay\weixin\lib\WxPayUnifiedOrder;
use WebPlugin\UdpLog;

/**
 * 支付有关方法 改版
 * @copyright 2016/5/22 14:19 xiaoxiao<xiaoxiao.hao@yoho.cn>
 */
class PaymentModel
{
    protected static $code = array(
            'code' => 500,
            'message' => '支付失败'
        );
    // 存储的UID键名
    const SESSION_UID_KEY = 'payUserid';
    // 是否老用户订单数判断值
    const OLD_USER_LIMIT = 1;
    /**
     * 获取支付方式选择页面有关信息
     *
     * @param int $uid 用户ID
     * @param string $orderCode 订单号
     * @return array
     */
    public static function getPayTypeData($uid, $orderCode)
    {
        $result = array('orderNum' => 0, 'count' => 0, 'pinyouGoods' => '', 'orderNum' => 0, 'orderGoods' => '');

        do {
            // 订单详情
            $orderDetail = OrderData::getOrderDetail($uid, $orderCode);
            if (!$orderDetail || empty($orderDetail['data'])) {
                $result['noOrder'] = true;
                break;
            }

            $order = $orderDetail['data'];
            $result['orderNum'] = $orderCode;
            $result['count'] = $order['payment_amount'];
            $result['paymentType'] = ($order['payment_type'] == 1 ? '在线支付' : '货到付款');
            // 订单商品(用于订单统计)
            $result['orderGoods'] = $order['order_goods'];

            //统计成交的skn
            $sknList = array();
            $skuList = array();
            $goodsData = array();
            $pinyouGoodsArr = array();
            foreach ($order['order_goods'] as $val) {
                $sknList[] = $val['product_skn'];
                $skuList[] = $val['product_sku'];
                $goodsData[] = array(
                    'goods_name' => $val['product_name'],
                    'product_sku' => $val['product_sku'],
                    'price' => $val['goods_price'],
                    'number' => $val['buy_number']
                );
                $pinyouGoodsArr[] = $val['product_skn'] . ',' . $val['buy_number'];
            }
            $result['goodsData'] = $goodsData;
            // skn列表
            $result['sknList'] = implode(',', $sknList);
            // sku列表
            $result['skuList'] = implode(',', $skuList);
            // 品友统计需要的商品数据
            $result['pinyouGoods'] = implode(';', $pinyouGoodsArr);

            // 货到付款的情况
            if ($order['payment_type'] == 2) {
                $result['finish'] = true;
                // 有货币
                $result['yohoCoin'] = $order['yoho_give_coin'];
                // 订单详情链接地址
                $result['checkOrderUrl'] = Helpers::url('/home/orders/detail', array('orderCode' => $orderCode));
                // 有货币地址
                $result['yohoCoinUrl'] = Helpers::url('/help', array('category_id' => 87));
                // vip地址
                $result['vipUrl'] = Helpers::url('/help', array('category_id' => 91));
                // 订单中心地址
                $result['ordersUrl'] = Helpers::url('/home/orders');
                // 退换货地址
                $result['backGoodsUrl'] = Helpers::url('/help', array('category_id' => 121));
                // 返回首页地址
                $result['returnHomeUrl'] = Helpers::url('/');
                break;
            }

            if (isset($order['attribute']) && $order['attribute'] * 1 === 3) {
                //虚拟商品
                $result['deliveryType'] = '自动发货 - 在您支付成功后,系统将立即为您发放二维码,您可以在您的订单中查看。';
            } else {
                $result['deliveryType'] = empty($order['delivery_time']) ? '': $order['delivery_time'];
            }

            

            // 用户ID
            $result['uid'] = $uid;
            // 获取支付途径列表
            $payTypes = PayData::getPaymentList();

            $defaultPayType = 0;
            $types = array();
            if (isset($payTypes['data']) && !empty($payTypes['data'])) {
                $oneType = array();

                foreach ($payTypes['data'] as $key => $payType) {
                    if (empty($payType['payIcon']) || $payType['id'] * 1 === 33) { // 排除图标不存在的支付方式
                        //33为blk支付方式
                        continue;
                    }

                    // 获取第一个支付方式
                    if ($key === 0) {
                        $defaultPayType = $payType['id'];
                    }

                    $oneType = array();
                    $oneType['name'] = $payType['payName'];
                    $oneType['ico'] = $payType['payIcon'];

                    $types[$payType['id']] = $oneType;
                }
                $result['list'] = self::procPayType($types);
            }

            // 获取银行列表
            $result['entry'] = self::procPayType(Banks::getList(), true);

            // 无需付款
            if (isset($order["payment_amount"]) && $order["payment_amount"] == 0) {
                UdpLog::info("【零元订单】,orderCode:{$orderCode},订单详情,", $order);
                $result['notNeedPay'] = true;
                break;
            }

            // 记录支付方式
            $bankRecord = PayData::getBankByOrder($orderCode);

            if (isset($bankRecord['data']['bankCode']) && !empty($bankRecord['data']['bankCode'])) {
                //银行的记录方式
                $payRecord = $bankRecord['data']['bankCode'];
            } elseif (isset($bankRecord['data']['payment']) && !empty($bankRecord['data']['payment'])) {
                //支付宝等平台的记录方式
                $payRecord = $bankRecord['data']['payment'];
            } else {
                //记录app上的支付方式
                $payCode = empty($order['payment']) ? $defaultPayType : $order['payment'];
                $changeCodes = array(
                    19 => 21,// app上微信支付
                    22 => 21,// h5微信支付
                    18 => 2// h5支付宝支付
                );
                $payRecord = empty($changeCodes[$payCode]) ? $defaultPayType : $changeCodes[$payCode];
            }
            $result['payRecord'] = $payRecord;

            // 已完成付款的链接地址
            $result['ordersUrl'] = Helpers::url('/home/orders');
            // 支付地址
            $result['payUrl'] = Helpers::url('/pay/index/index');

            // 是否是老用户(用于订单统计)
            $orderCount = 0;
            //查询用户订单数接口
            $orders = PayData::getOrderCountByUid($uid);

            if (!empty($orders['data']['count'])) {
                $orderCount = $orders['data']['count'];
            }

            $result['isOldUser'] = (intval($orderCount) > self::OLD_USER_LIMIT) ? true : false;
            // 订单数(用于订单统计)
            $result['orderCount'] = $orderCount;
            $result['is_advance'] = $order['attribute'] == 5 ? 'Y' : 'N';
            // 订单商品数(用于订单统计)
            $result['ordersGoodsNums'] = count($order['order_goods']);

        } while (false);

        return $result;
    }
    /**
     * 处理支付类型数据
     *
     * @param array $pays 支付方式数据
     * @param bool $isBank 是否是银行数据
     * @return array
     */
    private static function procPayType($pays, $isBank = false)
    {
        $result = array();
        $onePay = array();
        
        foreach ($pays as $code => $pay) {
            $onePay = array();
            $onePay['dataId'] = $isBank ? 12 : $code;//支付宝支联为12
            $onePay['dataVal'] = $isBank ? '12_' . $code : $code . '_platform';
            $onePay['idNum'] = $code;
            $onePay['ico'] = $pay['ico'];
            $onePay['name'] = $pay['name'];
            $onePay['imgId'] = $onePay['dataVal'];
            $result[] = $onePay;
        }
        return $result;
    }

    /**
     * 支付成功处理方法
     * @param type object $payResult 支付成功返回对象
     * @return type []
     */
    public static function procOrderData($payResult)
    {
        do {
            if (empty($payResult->orderCode)) {
                self::$code['message'] = '未查到订单信息,订单状态更新失败!';
                break;
            }
            $orderCode = $payResult->orderCode;
            $uid = self::getUid($orderCode);
            $orderInfo = OrderData::getOrderDetail($uid, $orderCode);
            if (empty($orderInfo['data'])) {
                self::$code['message'] = '未查到订单信息,订单状态更新失败!';
                break;
            }

            $orderData = $orderInfo['data'];
            $amount = $orderData['payment_amount'];

            if ($orderData['is_cancel'] === 'Y') {
                UdpLog::warn(
                    "【支付成功】,但订单已取消,orderCode:{$orderData},参数",
                    array('payResult' => $payResult, 'orderData' => $orderData)
                );
                // 给用户发送短信
                PayData::sendMessage($orderData['mobile'], 'error_sms', '支付成功,但订单已取消,订单号为' . $orderCode);
                self::$code['code'] = 417;
                self::$code['message'] = '支付成功,但订单已取消,需联系客服!';
                break;
            }

            if ($orderData['payment_status'] === 'N') {
                UdpLog::warn(
                    "【支付成功,同步地址返回】,查询订单状态为未付款,有可能异步地址还未即时更新状态,orderCode:{$orderCode},参数",
                    array('payResult' => $payResult, 'orderData' => $orderData)
                );
            }

            // 支付金额与订单金额不一致
            if (round($amount, 2) !== round($payResult->totalFee, 2)) {
                UdpLog::warn(
                    "【支付成功】,支付金额与订单金额不一致,orderCode:{$orderCode},参数",
                    array('payResult' => $payResult, 'orderData' => $orderData)
                );
                self::$code['code'] = 415;
                self::$code['message'] = '支付金额与订单金额不一致,订单状态更新失败!';
                break;
            }

            self::$code['code'] = 200;
            self::$code['message'] = '支付成功,请等待发货';
            self::$code['data'] = array(
                'pay' => $amount,
                'orderNum' => $orderData['order_code'],
                'checkOrderUrl' => Helpers::url('/home/orders/detail', array('orderCode' => $orderData['order_code'])),
                'payMode' => ($orderData['payment_type'] == 1 ? '在线支付' : '货到付款'),
                'currency' => $orderData['yoho_give_coin'],
                'yohoCoinUrl' => Helpers::url('/help', array('category_id' => 87)),
                'ordersUrl' => Helpers::url('/home/orders'),
                'returnGoodsUrl' => Helpers::url('/help', array('category_id' => 121)),
                'vipSum' => $amount,
                'vipUrl' => Helpers::url('/help', array('category_id' => 91)),
                'returnHomeUrl' => Helpers::url('/')
            );

        } while (false);

        return self::$code;
    }
    /**
     * 处理微信支付
     *
     * @param int $uid 用户ID
     * @param string $orderCode 订单号
     * @return array
     */
    public static function weixinQrcode($orderCode)
    {

        do {
            if (empty($orderCode)) {
                self::$code['message'] = '订单号不能为空';
                break;
            }
            $uid = self::getUid($orderCode);
            /* 判断订单信息是否存在 */
            $orderDetail = OrderData::getOrderDetail($uid, $orderCode);

            if (empty($orderDetail['data'])) {
                self::$code['message'] = '没有找到该订单';
                break;
            }

            if ($orderDetail['data']['is_cancel'] === 'Y') {
                self::$code['message'] = '该订单已被取消';
                break;
            }

            if ($orderDetail['data']['payment_status'] === 'Y') {
                self::$code['message'] = '该订单已付款,不需要再次付款';
                break;
            }
            //统一下单
            $totalFee = strval($orderDetail['data']['payment_amount'] * 100);
            $input = new WxPayUnifiedOrder();
            $input->SetBody('有货订单号:' . $orderCode);
            $input->SetOut_trade_no('YOHOBuy_' . $orderCode); // 商户订单号
            $input->SetTotal_fee($totalFee);
            //到期时间
            if (!empty($orderDetail['data']['pay_expire'])  && ($payExpireTime = strtotime($orderDetail['data']['pay_expire']))) {
                $payExpireTime = $payExpireTime;
            } else {
                $payExpireTime = time();
            }

            $input->SetTime_start(date("YmdHis", strtotime('-2 hours', $payExpireTime)));
            //最短失效时间间隔必须大于5分钟 [https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1]
            $input->SetTime_expire(date("YmdHis", $payExpireTime + 300));
            $input->SetTrade_type("NATIVE");
            $input->SetProduct_id($orderCode);
            $notify = new WxPayNativePay();
            $payResult = $notify->GetPayUrl($input);
            //错误信息,EQ:超时
            if (!empty($payResult['return_code']) && $payResult['return_code'] === 'FAIL') {
                self::$code['message'] = $payResult['return_msg'];
                break;
            }

            //错误信息,EQ:多次涮新
            if (!empty($payResult['result_code']) && $payResult['result_code'] === 'FAIL') {
                self::$code['message'] = $payResult['err_code_des'];
                break;
            }

            $orderData = $orderDetail['data'];
            $firstGoods = current($orderData['order_goods']);
            self::$code = array(
                'code' => 200,
                'orderNum' => $orderData['order_code'],
                'amount' => $orderData['payment_amount'],
                'address' => $orderData['address'],
                'name' => $orderData['user_name'],
                'tellphoneNum' => $orderData['mobile'],
                'tradeName' => $firstGoods['product_name'],
                'choosePayUrl' => Helpers::url('/shopping/pay', array('order_code' => $orderData['order_code'])),
                'qrcodeUrl' => isset($payResult['code_url']) ? $payResult['code_url'] : '' // '//paysdk.weixin.qq.com/example/qrcode.php?data=' . $result['code_url']
            );

        } while (false);

        return self::$code;
    }
    
    /**
     * 轮询查询--检查微信扫码支付结果
     *
     * @param int $uid 用户ID
     * @param int $orderCode 订单号
     * @return array 订单支付结果
     */
    public static function checkWechatPayStatus($orderCode)
    {
        do {
            if (empty($orderCode)) {
                self::$code['message'] = '未查询到订单号';
                break;
            }

            // 组装微信支付的订单号
            $tradeNo = 'YOHOBuy_' . $orderCode;
            $input = new WxPayOrderQuery();
            $input->SetOut_trade_no($tradeNo);
            $payResult = WxPayApi::orderQuery($input);

            if (isset($payResult['trade_state']) && $payResult['trade_state'] === 'SUCCESS') {
                self::$code = array(
                    'code' => '200',
                    'message' => 'success'
                );
            }
        } while (false);

        return self::$code;
    }
    /**
     * 根据支付ID获取支付相关参数
     *
     * @param int $payId 支付ID
     * @return array
     */
    public static function getPaymentById($payId)
    {
        $result = array();

        $paymentParams = PayData::getPaymentById($payId);
        if (isset($paymentParams['data']) && !empty($paymentParams['data'])) {
            $result = array(
                'id' => $payId,
                'pay_code' => $paymentParams['data']['payCode'],
                'payName' => $paymentParams['data']['payName'],
                'pay_params' => isset($paymentParams['data']['payParams']) ? $paymentParams['data']['payParams'] : ''
            );
        }

        return $result;
    }
    /**
     * 通过订单号,从缓存记录中获取uid
     * @param type string $orderCode 订单号
     * @return type int
     */
    private static function getUid($orderCode)
    {
        $uid = '';
        if (USE_CACHE) {
            // 通过订单号,从缓存记录中获取uid
            $uid = Cache::get(self::SESSION_UID_KEY . $orderCode);
        }
        return $uid;
    }
    /**
     * 支付成功后--发送支付确认接口
     * @param type object $orderCode 订单号
     * @param type int $paymentId 支付方式id
     * @param type int $uid 用户ID
     * @return type []
     */
    public static function sendPayConfirm($orderCode, $paymentId, $uid)
    {
        UdpLog::info(
            "【支付成功-发送确认接口】,function:sendPayConfirm,支付方式ID:{$paymentId},参数",
            array('orderCode' => $orderCode, 'paymentId' => $paymentId, 'uid' => $uid)
        );
        if (empty($orderCode)) {
            return self::$code;
        }

        //如果uid,为空,则从缓存中取uid,但还是不排除uid为空的情况下。
        $uid = empty($uid) ? self::getUid($orderCode) : $uid;
        $confirm = PayData::payConfirm($orderCode, $paymentId, $uid);
        
        UdpLog::info(
            "【支付成功-发送确认接口】,function:sendPayConfirm,orderCode:{$orderCode},支付方式ID:{$paymentId},接口返回",
            array('orderCode' => $orderCode, 'paymentId' => $paymentId, 'uid' => $uid, 'confirm' => $confirm)
        );
        return $confirm;
    }
    
    /**
     * 获取支付有关信息
     *
     * @param int $uid 用户ID
     * @param string $orderCode 订单号
     * @param string $paymentType 支付方式
     * @param string $userName 用户名
     * @param string $alipayToken 支付宝用户token
     * @return array
     */
    public static function getPayData($uid, $orderCode, $paymentType, $userName, $alipayToken)
    {
        $result = array();

        do {
            /* 判断是否有订单号参数 */
            if (empty($orderCode)) {
                $result['error'] = true;
                $result['message'] = '订单号不能为空';
                break;
            }

            /* 判断支付方式是否选择 */
            $paymentPars = explode('_', $paymentType);
            if (count($paymentPars) != 2) {
                $result['error'] = true;
                $result['message'] = '请选择一个支付方式';
                break;
            }

            /* 判断订单信息是否存在 */
            $orderDetail = OrderData::getOrderDetail($uid, $orderCode);
            if (empty($orderDetail['data'])) {
                $result['error'] = true;
                $result['message'] = '没有找到该订单';
                break;
            }

            /* 判断订单是否已取消 */
            if (isset($orderDetail['data']['is_cancel']) && $orderDetail['data']['is_cancel'] === 'Y') {
                $result['error'] = true;
                $result['message'] = '订单已经取消';
                $result['location'] = 'window.location="' . Helpers::url('/home/orders/detail', array('order_code' => $orderCode)) . '";';
                break;
            }

            // 获取支付有关参数
            $payId = $paymentPars[0];
            $paymentParams = self::getPaymentById($payId);
            if (empty($paymentParams)) {
                $result['error'] = true;
                $result['message'] = '支付系统繁忙,请稍后再试';
                break;
            }

            $payService = PayFactory::factory($paymentParams);
            if ($payService == false) { // 没找到支付方式时
                $result['error'] = true;
                $result['message'] = '请选择一个支付方式';
                break;
            }

            $totalFee = $orderDetail['data']['payment_amount'] * 100;
            $isTest = (APPLICATION_ENV === 'developer' || APPLICATION_ENV === 'testing');
            $paymentParameter = $paymentPars[1];
            // 判断是否传入支付宝token
            if ($paymentType == 2 && !empty($alipayToken)) {

                $paymentParameter = $alipayToken;
            }

            $reqParams = new Reqparams(
                $orderCode, $totalFee, '有货订单号:' . $orderCode, '', $orderDetail['data']['create_time'],
                $paymentParameter, $isTest, $uid, $userName, $orderDetail['data']['pay_expire']
            );
            $reqPars = $payService->getPayRequestPars($reqParams);
            UdpLog::info(
                "【支付-参数】,function:getPayData,orderCode:{$orderCode},接口返回",
                array('$reqPars' => $reqPars)
            );
            if (empty($reqPars)) {
                $result['error'] = true;
                $result['message'] = '支付系统繁忙,请稍后再试';
                break;
            }

            // 记录并更新订单支付方式
            $paymentRecod = OrderData::updateOrderPayment($orderCode, $payId, $uid);
            if (empty($paymentRecod) || $paymentRecod['code'] != 200) {
                $result['error'] = true;
                $result['message'] = isset($paymentRecod['message']) ? $paymentRecod['message'] : '系统繁忙,请稍后再试';
                break;
            }
            $bankRecord = PayData::getBankByOrder($orderCode);
            $bankCode = ($paymentParameter != 'platform' ? $paymentParameter : '');
            if (isset($bankRecord['data']['bankCode']) && !empty($bankRecord['data']['bankCode'])) {
                $bankPayRecord = PayData::updateOrderPayBank($orderCode, $payId, $bankCode);
            } else {
                $bankPayRecord = PayData::setOrderPayBank($orderCode, $payId, $bankCode);
            }
            if (!isset($bankPayRecord['code']) || $bankPayRecord['code'] != 200) {
                $result['error'] = true;
                $result['message'] = '支付方式记录失败';
                break;
            }

            if ($reqPars['reqType'] == 'get') {
                //直接跳转到支付界面
                $result['go'] = true;
                $result['payUrl'] = $reqPars['pay_url'] . '?' . $reqPars['pars'];
            } else {
                //如果是post,去form提交
                $result = array('reqPars' => $reqPars);
            }
        } while (false);

        return $result;
    }
}