QQ.php 22.2 KB
Newer Older
D
Devil 已提交
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
<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2019 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace payment;

/**
 * QQ支付
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-09-19
 * @desc    description
 */
class QQ
{
    // 插件配置参数
    private $config;

    /**
     * 构造方法
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-17
     * @desc    description
     * @param   [array]           $params [输入参数(支付配置参数)]
     */
    public function __construct($params = [])
    {
        $this->config = $params;
    }

    /**
     * 配置信息
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-19
     * @desc    description
     */
    public function Config()
    {
        // 基础信息
        $base = [
            'name'          => 'QQ支付',  // 插件名称
            'version'       => '1.0.0',  // 插件版本
            'apply_version' => '不限',  // 适用系统版本描述
D
Devil 已提交
55 56
            'apply_terminal'=> ['pc', 'h5', 'qq'], // 适用终端 默认全部 ['pc', 'h5', 'app', 'alipay', 'weixin', 'baidu']
            'desc'          => '适用PC+H5+QQ小程序,即时到帐支付方式,买家的交易资金直接打入卖家账户,快速回笼交易资金。 <a href="https://qpay.qq.com/" target="_blank">立即申请</a>',  // 插件描述(支持html)
D
Devil 已提交
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
            'author'        => 'Devil',  // 开发者
            'author_url'    => 'http://shopxo.net/',  // 开发者主页
        ];

        // 配置信息
        $element = [
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'appid',
                'placeholder'   => 'QQ小程序ID',
                'title'         => 'QQ小程序ID',
                'is_required'   => 0,
                'message'       => '请填写QQ分配的小程序ID',
            ],
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'mch_id',
                'placeholder'   => 'QQ支付商户号',
                'title'         => 'QQ支付商户号',
                'is_required'   => 0,
                'message'       => '请填写QQ支付分配的商户号',
            ],
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'key',
                'placeholder'   => '密钥',
                'title'         => '密钥',
                'desc'          => 'QQ支付商户平台API配置的密钥',
                'is_required'   => 0,
                'message'       => '请填写密钥',
            ],
D
Devil 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'op_user_id',
                'placeholder'   => '操作员帐号',
                'title'         => '操作员帐号(退款操作必填项)',
                'desc'          => '也可以是商户号,操作员工创建参考:https://kf.qq.com/faq/170112AZ7Fzm170112VNz6zE.html',
                'is_required'   => 0,
                'message'       => '请填写操作员帐号',
            ],
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'op_user_passwd',
                'placeholder'   => '操作员密码',
                'title'         => '操作员密码(退款操作必填项)',
D
Devil 已提交
113
                'desc'          => '如果操作员帐号填写的是商户号,那这里就是商户号登录密码',
D
Devil 已提交
114 115 116
                'is_required'   => 0,
                'message'       => '请填写操作员密码',
            ],
D
Devil 已提交
117 118 119 120
            [
                'element'       => 'textarea',
                'name'          => 'apiclient_cert',
                'placeholder'   => '证书(apiclient_cert.pem)',
D
Devil 已提交
121
                'title'         => '证书(apiclient_cert.pem)(退款操作必填项)',
D
Devil 已提交
122 123 124 125 126 127 128 129
                'is_required'   => 0,
                'rows'          => 6,
                'message'       => '请填写证书(apiclient_cert.pem)',
            ],
            [
                'element'       => 'textarea',
                'name'          => 'apiclient_key',
                'placeholder'   => '证书密钥(apiclient_key.pem)',
D
Devil 已提交
130
                'title'         => '证书密钥(apiclient_key.pem)(退款操作必填项)',
D
Devil 已提交
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
                'is_required'   => 0,
                'rows'          => 6,
                'message'       => '请填写证书密钥(apiclient_key.pem)',
            ],
            [
                'element'       => 'select',
                'title'         => '异步通知协议',
                'message'       => '请选择协议类型',
                'name'          => 'agreement',
                'is_multiple'   => 0,
                'element_data'  => [
                    ['value'=>1, 'name'=>'默认当前协议'],
                    ['value'=>2, 'name'=>'强制https转http协议'],
                ],
            ],
        ];

        return [
            'base'      => $base,
            'element'   => $element,
        ];
    }

    /**
     * 支付入口
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-19
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    public function Pay($params = [])
    {
        // 参数
        if(empty($params))
        {
            return DataReturn('参数不能为空', -1);
        }

        // 配置信息
        if(empty($this->config))
        {
            return DataReturn('支付缺少配置', -1);
        }

        // 获取支付参数
        $ret = $this->GetPayParams($params);
        if($ret['code'] != 0)
        {
            return $ret;
        }

        // 请求接口处理
        $result = $this->XmlToArray($this->HttpRequest('https://qpay.qq.com/cgi-bin/pay/qpay_unified_order.cgi', $this->ArrayToXml($ret['data'])));
        if(!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['prepay_id']))
        {
            return $this->PayHandleReturn($ret['data'], $result, $params);
        }
        $msg = is_string($result) ? $result : (empty($result['return_msg']) ? '支付接口异常' : $result['return_msg']);
        if(!empty($result['err_code_des']))
        {
            $msg .= '-'.$result['err_code_des'];
        }
        return DataReturn($msg, -1);
    }

    /**
     * 支付返回处理
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-08
     * @desc    description
     * @param   [array]           $pay_params   [支付参数]
     * @param   [array]           $data         [支付返回数据]
     * @param   [array]           $params       [输入参数]
     */
    private function PayHandleReturn($pay_params = [], $data = [], $params = [])
    {
        $redirect_url = empty($params['order_id']) ? '' : urlencode(MyUrl('index/order/detail', ['id'=>$params['order_id']]));
        $result = DataReturn('支付接口异常', -1);
        switch($pay_params['trade_type'])
        {
            // web支付
            case 'NATIVE' :
D
Devil 已提交
217 218 219
                // 手机模式下直接返回微信的支付url地址,打开支付(缺点是支付后会直接关闭站点)
                // QQ支付本身没有提供H5支付方案,这种方式也可以直接支付(缺点是支付后不能回调到原来浏览器)
                // 公众号后续再采用公众号的方式支付,体验会更好一些,只是可以不关闭站点
D
Devil 已提交
220
                if(APPLICATION_CLIENT_TYPE == 'h5' || IsMobile())
D
Devil 已提交
221
                {
D
Devil 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                    $result = DataReturn('success', 0, $data['code_url']);
                } else {
                    if(empty($params['ajax_url']))
                    {
                        return DataReturn('支付状态校验地址不能为空', -50);
                    }
                    $pay_params = [
                        'url'       => urlencode(base64_encode($data['code_url'])),
                        'order_no'  => $params['order_no'],
                        'name'      => urlencode('QQ支付'),
                        'msg'       => urlencode('打开QQAPP扫一扫进行支付'),
                        'ajax_url'  => urlencode(base64_encode($params['ajax_url'])),
                    ];
                    $url = MyUrl('index/pay/qrcode', $pay_params);
                    $result = DataReturn('success', 0, $url);
D
Devil 已提交
237 238 239 240 241
                }
                break;

            // QQ中公众号支付
            case 'JSAPI' :
D
Devil 已提交
242
                $result = DataReturn('公众号暂不支持', -1);
D
Devil 已提交
243 244 245 246
                break;

            // QQ小程序支付
            case 'MINIAPP' :
D
Devil 已提交
247
                $result = DataReturn('success', 0, 'prepay_id='.$data['prepay_id']);
D
Devil 已提交
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
                break;

            // APP支付
            case 'APP' :
                $pay_data = array(
                    'appid'         => $this->pay_params['appid'],
                    'partnerid'     => $this->pay_params['mch_id'],
                    'prepayid'      => $data['prepay_id'],
                    'package'       => 'Sign=WXPay',
                    'noncestr'      => md5(time().rand()),
                    'timestamp'     => (string) time(),
                );
                $pay_data['sign'] = $this->GetSign($pay_data);
                $result = DataReturn('success', 0, $pay_data);
                break;
        }
        return $result;
    }

    /**
     * 获取支付参数
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-07
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    private function GetPayParams($params = [])
    {
        $trade_type = empty($params['trade_type']) ? $this->GetTradeType() : $params['trade_type'];
        if(empty($trade_type))
        {
            return DataReturn('支付类型不匹配', -1);
        }

        // 异步地址处理
        $notify_url = (__MY_HTTP__ == 'https' && isset($this->config['agreement']) && $this->config['agreement'] == 1) ? 'http'.mb_substr($params['notify_url'], 5, null, 'utf-8') : $params['notify_url'];

        // 请求参数
        $data = [
            'appid'             => $this->config['appid'],
            'mch_id'            => $this->config['mch_id'],
            'nonce_str'         => md5(time().rand().$params['order_no']),
            'body'              => $params['site_name'].'-'.$params['name'],
            'notify_url'        => $notify_url,
            'out_trade_no'      => $params['order_no'].GetNumberCode(6),
            'fee_type'          => 'CNY',
            'total_fee'         => intval($params['total_price']*100),
            'spbill_create_ip'  => GetClientIP(),
            'trade_type'        => $trade_type,
D
Devil 已提交
299
            'attach'            => empty($params['attach']) ? '订单号:'.$params['order_no'] : $params['attach'],
D
Devil 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        ];
        $data['sign'] = $this->GetSign($data);
        return DataReturn('success', 0, $data);
    }

    /**
     * 获取支付交易类型
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-08
     * @desc    description
     */
    private function GetTradeType()
    {
        $type_all = [
            'pc'        => 'NATIVE',
D
Devil 已提交
317
            'h5'        => 'NATIVE',
D
Devil 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
            'qq'        => 'MINIAPP',
            'app'       => 'APP',
            'ios'       => 'APP',
            'android'   => 'APP',
        ];

        return isset($type_all[APPLICATION_CLIENT_TYPE]) ? $type_all[APPLICATION_CLIENT_TYPE] : '';
    }

    /**
     * 支付回调处理
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-19
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    public function Respond($params = [])
    {
        $result = empty($GLOBALS['HTTP_RAW_POST_DATA']) ? $this->XmlToArray(file_get_contents('php://input')) : $this->XmlToArray($GLOBALS['HTTP_RAW_POST_DATA']);

D
Devil 已提交
340
        if(isset($result['trade_state']) && $result['trade_state'] == 'SUCCESS' && $result['sign'] == $this->GetSign($result))
D
Devil 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        {
            return DataReturn('支付成功', 0, $this->ReturnData($result));
        }
        $error_msg = empty($result['return_msg']) ? '' : '['.$result['return_msg'].']';
        return DataReturn('处理异常错误'.$error_msg, -100);
    }

    /**
     * [ReturnData 返回数据统一格式]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-10-06T16:54:24+0800
     * @param    [array]                   $data [返回数据]
     */
    private function ReturnData($data)
    {
        // 参数处理
        $out_trade_no = substr($data['out_trade_no'], 0, strlen($data['out_trade_no'])-6);

        // 返回数据固定基础参数
        $data['trade_no']       = $data['transaction_id'];  // 支付平台 - 订单号
        $data['buyer_user']     = isset($data['openid']) ? $data['openid'] : '';  // 支付平台 - 用户
        $data['out_trade_no']   = $out_trade_no;            // 本系统发起支付的 - 订单号
D
Devil 已提交
365
        $data['subject']        = isset($data['attach']) ? $data['attach'] : '';  // 本系统发起支付的 - 商品名称
D
Devil 已提交
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
        $data['pay_price']      = $data['total_fee']/100;   // 本系统发起支付的 - 总价
        return $data;
    }

    /**
     * 退款处理
     * @author  Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-05-28
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    public function Refund($params = [])
    {
        // 参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'order_no',
                'error_msg'         => '订单号不能为空',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'trade_no',
                'error_msg'         => '交易平台订单号不能为空',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'pay_price',
                'error_msg'         => '支付金额不能为空',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'refund_price',
                'error_msg'         => '退款金额不能为空',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        // 请求参数
        $data = [
D
Devil 已提交
412
            'appid'             => $this->config['appid'],
D
Devil 已提交
413 414 415 416 417
            'mch_id'            => $this->config['mch_id'],
            'nonce_str'         => md5(time().rand().$params['order_no']),
            'transaction_id'    => $params['trade_no'],
            'out_refund_no'     => $params['order_no'].GetNumberCode(6),
            'refund_fee'        => intval($params['refund_price']*100),
D
Devil 已提交
418 419
            'op_user_id'        => $this->config['op_user_id'],
            'op_user_passwd'    => md5($this->config['op_user_passwd']),
D
Devil 已提交
420 421 422 423
        ];
        $data['sign'] = $this->GetSign($data);

        // 请求接口处理
D
Devil 已提交
424
        $result = $this->XmlToArray($this->HttpRequest('https://api.qpay.qq.com/cgi-bin/pay/qpay_refund.cgi', $this->ArrayToXml($data), true));
D
Devil 已提交
425
        if(!empty($result['return_code']) && $result['return_code'] == 'SUCCESS')
D
Devil 已提交
426 427 428 429
        {
            // 统一返回格式
            $data = [
                'out_trade_no'  => isset($result['out_trade_no']) ? $result['out_trade_no'] : '',
D
Devil 已提交
430
                'trade_no'      => isset($result['refund_id']) ? $result['refund_id'] : '',
D
Devil 已提交
431
                'buyer_user'    => isset($result['openid']) ? $result['openid'] : '',
D
Devil 已提交
432 433 434 435 436
                'refund_price'  => isset($result['refund_fee']) ? $result['refund_fee']/100 : 0.00,
                'return_params' => $result,
            ];
            return DataReturn('退款成功', 0, $data);
        }
D
Devil 已提交
437
        $msg = is_string($result) ? $result : (empty($result['err_code']) ? '退款接口异常' : $result['err_code']);
D
Devil 已提交
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
        if(!empty($result['err_code_des']))
        {
            $msg .= '-'.$result['err_code_des'];
        }
        return DataReturn($msg, -1);
    }

    /**
     * 签名生成
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-07
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    private function GetSign($params = [])
    {
        ksort($params);
        $sign  = '';
        foreach($params as $k=>$v)
        {
            if($k != 'sign' && $v != '' && $v != null)
            {
                $sign .= "$k=$v&";
            }
        }
        return strtoupper(md5($sign.'key='.$this->config['key']));
    }

    /**
     * 数组转xml
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-07
     * @desc    description
     * @param   [array]          $data [数组]
     */
    private function ArrayToXml($data)
    {
        $xml = '<xml>';
        foreach($data as $k=>$v)
        {
            $xml .= '<'.$k.'>'.$v.'</'.$k.'>';
        }
        $xml .= '</xml>';
        return $xml;
    }

    /**
     * xml转数组
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-07
     * @desc    description
     * @param   [string]          $xml [xm数据]
     */
    private function XmlToArray($xml)
    {
        if(!$this->XmlParser($xml))
        {
            return is_string($xml) ? $xml : '接口返回数据有误';
        }

        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }


    /**
     * 判断字符串是否为xml格式
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-07
     * @desc    description
     * @param   [string]          $string [字符串]
     */
    function XmlParser($string)
    {
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser, $string, true))
        {
          xml_parser_free($xml_parser);
          return false;
        } else {
          return (json_decode(json_encode(simplexml_load_string($string)),true));
        }
    }

    /**
     * [HttpRequest 网络请求]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-09-25T09:10:46+0800
     * @param    [string]          $url         [请求url]
     * @param    [array]           $data        [发送数据]
     * @param    [boolean]         $use_cert    [是否需要使用证书]
     * @param    [int]             $second      [超时]
     * @return   [mixed]                        [请求返回数据]
     */
    private function HttpRequest($url, $data, $use_cert = false, $second = 30)
    {
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_POST           => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_POSTFIELDS     => $data,
            CURLOPT_TIMEOUT        => $second,
        );

        if($use_cert == true)
        {
            //设置证书
            //使用证书:cert 与 key 分别属于两个.pem文件
            $apiclient = $this->GetApiclientFile();
            $options[CURLOPT_SSLCERTTYPE] = 'PEM';
            $options[CURLOPT_SSLCERT] = $apiclient['cert'];
            $options[CURLOPT_SSLKEYTYPE] = 'PEM';
            $options[CURLOPT_SSLKEY] = $apiclient['key'];
        }
 
        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        //返回结果
        if($result)
        {
            curl_close($ch);
            return $result;
        } else { 
            $error = curl_errno($ch);
            curl_close($ch);
            return "curl出错,错误码:$error";
        }
    }

    /**
     * 获取证书文件路径
     * @author  Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-05-29
     * @desc    description
     */
    private function GetApiclientFile()
    {
        // 证书位置
D
Devil 已提交
590 591
        $apiclient_cert_file = ROOT.'runtime'.DS.'temp'.DS.'payment_qq_pay_apiclient_cert.pem';
        $apiclient_key_file = ROOT.'runtime'.DS.'temp'.DS.'payment_qq_pay_apiclient_key.pem';
D
Devil 已提交
592

D
devil_gong 已提交
593 594 595 596 597 598 599 600 601
        // 证书处理
        if(stripos($this->config['apiclient_cert'], '-----') === false)
        {
            $apiclient_cert = "-----BEGIN CERTIFICATE-----\n";
            $apiclient_cert .= wordwrap($this->config['apiclient_cert'], 64, "\n", true);
            $apiclient_cert .= "\n-----END CERTIFICATE-----";
        } else {
            $apiclient_cert = $this->config['apiclient_cert'];
        }
D
Devil 已提交
602
        file_put_contents($apiclient_cert_file, $apiclient_cert);
D
devil_gong 已提交
603 604 605 606 607 608 609 610 611

        if(stripos($this->config['apiclient_key'], '-----') === false)
        {
            $apiclient_key = "-----BEGIN PRIVATE KEY-----\n";
            $apiclient_key .= wordwrap($this->config['apiclient_key'], 64, "\n", true);
            $apiclient_key .= "\n-----END PRIVATE KEY-----";
        } else {
            $apiclient_key = $this->config['apiclient_key'];
        }
D
Devil 已提交
612 613
        file_put_contents($apiclient_key_file, $apiclient_key);

D
Devil 已提交
614 615 616 617
        return ['cert' => $apiclient_cert_file, 'key' => $apiclient_key_file];
    }
}
?>