Weixin.php 29.8 KB
Newer Older
D
devil_gong 已提交
1 2 3 4
<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
D
2.0  
Devil 已提交
5
// | Copyright (c) 2011~2099 http://shopxo.net All rights reserved.
D
devil_gong 已提交
6
// +----------------------------------------------------------------------
D
2.0  
Devil 已提交
7
// | Licensed ( https://opensource.org/licenses/mit-license.php )
D
devil_gong 已提交
8 9 10 11 12 13
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace payment;

/**
14
 * 微信支付
D
devil_gong 已提交
15 16 17 18 19 20
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-09-19
 * @desc    description
 */
21
class Weixin
D
devil_gong 已提交
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
{
    // 插件配置参数
    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'          => '微信',  // 插件名称
53
            'version'       => '1.1.4',  // 插件版本
D
devil_gong 已提交
54
            'apply_version' => '不限',  // 适用系统版本描述
D
Devil 已提交
55 56
            'apply_terminal'=> ['pc', 'h5', 'ios', 'android', 'weixin', 'qq'], // 适用终端 默认全部 ['pc', 'h5', 'app', 'alipay', 'weixin', 'baidu']
            'desc'          => '适用公众号+PC+H5+APP+微信小程序,即时到帐支付方式,买家的交易资金直接打入卖家账户,快速回笼交易资金。 <a href="https://pay.weixin.qq.com/" target="_blank">立即申请</a>',  // 插件描述(支持html)
D
devil_gong 已提交
57 58 59 60 61 62
            'author'        => 'Devil',  // 开发者
            'author_url'    => 'http://shopxo.net/',  // 开发者主页
        ];

        // 配置信息
        $element = [
D
Devil 已提交
63 64 65 66 67 68 69 70 71 72
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'app_appid',
                'placeholder'   => '开放平台AppID',
                'title'         => '开放平台AppID',
                'is_required'   => 0,
                'message'       => '请填写微信开放平台APP支付分配的AppID',
            ],
D
devil_gong 已提交
73 74 75 76 77
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'appid',
G
wx pay  
gongfuxiang 已提交
78 79
                'placeholder'   => '公众号/服务号AppID',
                'title'         => '公众号/服务号AppID',
D
devil_gong 已提交
80
                'is_required'   => 0,
G
wx pay  
gongfuxiang 已提交
81
                'message'       => '请填写微信分配的AppID',
D
devil_gong 已提交
82 83 84 85 86 87
            ],
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'mini_appid',
D
devil_gong 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
                'placeholder'   => '小程序ID',
                'title'         => '小程序ID',
                'is_required'   => 0,
                'message'       => '请填写微信分配的小程序ID',
            ],
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'mch_id',
                'placeholder'   => '微信支付商户号',
                'title'         => '微信支付商户号',
                'is_required'   => 0,
                'message'       => '请填写微信支付分配的商户号',
            ],
            [
                'element'       => 'input',
                'type'          => 'text',
                'default'       => '',
                'name'          => 'key',
                'placeholder'   => '密钥',
                'title'         => '密钥',
G
gongfuxiang 已提交
110
                'desc'          => '微信支付商户平台API配置的密钥',
D
devil_gong 已提交
111 112 113
                'is_required'   => 0,
                'message'       => '请填写密钥',
            ],
D
devil_gong 已提交
114 115 116 117
            [
                'element'       => 'textarea',
                'name'          => 'apiclient_cert',
                'placeholder'   => '证书(apiclient_cert.pem)',
D
Devil 已提交
118
                'title'         => '证书(apiclient_cert.pem)(退款操作必填项)',
D
devil_gong 已提交
119 120 121 122 123 124 125 126
                'is_required'   => 0,
                'rows'          => 6,
                'message'       => '请填写证书(apiclient_cert.pem)',
            ],
            [
                'element'       => 'textarea',
                'name'          => 'apiclient_key',
                'placeholder'   => '证书密钥(apiclient_key.pem)',
D
Devil 已提交
127
                'title'         => '证书密钥(apiclient_key.pem)(退款操作必填项)',
D
devil_gong 已提交
128 129 130 131
                'is_required'   => 0,
                'rows'          => 6,
                'message'       => '请填写证书密钥(apiclient_key.pem)',
            ],
G
wx pay  
gongfuxiang 已提交
132 133 134 135 136 137 138
            [
                'element'       => 'select',
                'title'         => '异步通知协议',
                'message'       => '请选择协议类型',
                'name'          => 'agreement',
                'is_multiple'   => 0,
                'element_data'  => [
D
devil_gong 已提交
139
                    ['value'=>1, 'name'=>'默认当前协议'],
G
wx pay  
gongfuxiang 已提交
140 141 142
                    ['value'=>2, 'name'=>'强制https转http协议'],
                ],
            ],
143 144 145 146 147 148 149 150 151 152 153
            [
                'element'       => 'select',
                'title'         => 'h5跳转地址urlencode',
                'message'       => '请选择h5跳转地址urlencode',
                'name'          => 'is_h5_url_encode',
                'is_multiple'   => 0,
                'element_data'  => [
                    ['value'=>1, 'name'=>'是'],
                    ['value'=>2, 'name'=>'否'],
                ],
            ],
D
devil_gong 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        ];

        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 = [])
    {
173
        // 参数
D
devil_gong 已提交
174 175 176 177 178
        if(empty($params))
        {
            return DataReturn('参数不能为空', -1);
        }

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

D
devil 已提交
185 186 187
        // 平台
        $client_type = ApplicationClientType();

G
wx pay  
gongfuxiang 已提交
188
        // 微信中打开
D
devil 已提交
189
        if($client_type == 'h5' && IsWeixinEnv() && (empty($params['user']) || empty($params['user']['weixin_web_openid'])))
G
wx pay  
gongfuxiang 已提交
190
        {
D
devil 已提交
191
            exit(header('location:'.PluginsHomeUrl('weixinwebauthorization', 'pay', 'index', input())));
G
wx pay  
gongfuxiang 已提交
192
        }
G
wx pay  
gongfuxiang 已提交
193

D
devil_gong 已提交
194
        // 获取支付参数
D
devil_gong 已提交
195 196
        $ret = $this->GetPayParams($params);
        if($ret['code'] != 0)
D
devil_gong 已提交
197
        {
D
devil_gong 已提交
198
            return $ret;
D
devil_gong 已提交
199 200
        }

D
devil 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        // QQ小程序使用微信支付
        if($client_type == 'qq')
        {
            // 获取QQ access_token
            $qq_appid = MyC('common_app_mini_qq_appid');
            $qq_appsecret = MyC('common_app_mini_qq_appsecret');
            $access_token = (new \base\QQ($qq_appid, $qq_appsecret))->GetAccessToken();
            if($access_token === false)
            {
                return DataReturn('QQ凭证AccessToken获取失败', -1);
            }

            // QQ小程序代理下单地址
            $request_url = 'https://api.q.qq.com/wxpay/unifiedorder?appid='.$qq_appid.'&access_token='.$access_token.'&real_notify_url='.urlencode($this->GetNotifyUrl($params));
        } else {
            $request_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        }

D
debug  
devil_gong 已提交
219
        // 请求接口处理
D
devil 已提交
220
        $result = $this->XmlToArray($this->HttpRequest($request_url, $this->ArrayToXml($ret['data'])));
D
devil_gong 已提交
221 222
        if(!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['prepay_id']))
        {
D
devil_gong 已提交
223
            return $this->PayHandleReturn($ret['data'], $result, $params);
D
devil_gong 已提交
224
        }
D
Devil 已提交
225
        $msg = is_string($result) ? $result : (empty($result['return_msg']) ? '支付接口异常' : $result['return_msg']);
D
devil_gong 已提交
226 227 228 229 230
        if(!empty($result['err_code_des']))
        {
            $msg .= '-'.$result['err_code_des'];
        }
        return DataReturn($msg, -1);
D
devil_gong 已提交
231 232
    }

D
devil_gong 已提交
233 234 235 236 237 238 239 240 241
    /**
     * 支付返回处理
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-08
     * @desc    description
     * @param   [array]           $pay_params   [支付参数]
     * @param   [array]           $data         [支付返回数据]
D
devil_gong 已提交
242
     * @param   [array]           $params       [输入参数]
D
devil_gong 已提交
243
     */
D
devil_gong 已提交
244
    private function PayHandleReturn($pay_params = [], $data = [], $params = [])
D
devil_gong 已提交
245
    {
D
devil 已提交
246
        $redirect_url = empty($params['redirect_url']) ? __MY_URL__ : $params['redirect_url'];
D
devil_gong 已提交
247
        $result = DataReturn('支付接口异常', -1);
D
devil_gong 已提交
248
        switch($pay_params['trade_type'])
D
devil_gong 已提交
249 250 251
        {
            // web支付
            case 'NATIVE' :
G
gongfuxiang 已提交
252
                if(empty($params['check_url']))
D
devil_gong 已提交
253 254 255
                {
                    return DataReturn('支付状态校验地址不能为空', -50);
                }
G
gongfuxiang 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
                if(APPLICATION == 'app')
                {
                    $data = [
                        'qrcode_url'    => MyUrl('index/qrcode/index', ['content'=>urlencode(base64_encode($data['code_url']))]),
                        'order_no'      => $params['order_no'],
                        'name'          => '微信支付',
                        'msg'           => '打开微信APP扫一扫进行支付',
                        'check_url'     => $params['check_url'],
                    ];
                } else {
                    $pay_params = [
                        'url'       => urlencode(base64_encode($data['code_url'])),
                        'order_no'  => $params['order_no'],
                        'name'      => urlencode('微信支付'),
                        'msg'       => urlencode('打开微信APP扫一扫进行支付'),
                        'check_url' => urlencode(base64_encode($params['check_url'])),
                    ];
                    $data = MyUrl('index/pay/qrcode', $pay_params);
                }
                $result = DataReturn('success', 0, $data);
D
devil_gong 已提交
276 277 278 279
                break;

            // h5支付
            case 'MWEB' :
280 281
                if(!empty($params['order_id']))
                {
282 283 284
                    // 是否需要urlencode
                    $redirect_url = (isset($this->config['is_h5_url_encode']) && $this->config['is_h5_url_encode'] == 1) ? urlencode($redirect_url) : $redirect_url;
                    $data['mweb_url'] .= '&redirect_url='.$redirect_url;
285
                }
D
devil_gong 已提交
286
                $result = DataReturn('success', 0, $data['mweb_url']);
D
devil_gong 已提交
287 288 289 290
                break;

            // 微信中/小程序支付
            case 'JSAPI' :
G
gongfuxiang 已提交
291
                $pay_data = [
D
devil_gong 已提交
292
                    'appId'         => $pay_params['appid'],
D
devil_gong 已提交
293 294 295 296
                    'package'       => 'prepay_id='.$data['prepay_id'],
                    'nonceStr'      => md5(time().rand()),
                    'signType'      => $pay_params['sign_type'],
                    'timeStamp'     => (string) time(),
G
gongfuxiang 已提交
297
                ];
D
devil_gong 已提交
298
                $pay_data['paySign'] = $this->GetSign($pay_data);
D
devil_gong 已提交
299 300

                // 微信中
301
                if(APPLICATION == 'web' && IsWeixinEnv())
D
devil_gong 已提交
302
                {
G
gongfuxiang 已提交
303 304
                    $html = $this->PayHtml($pay_data, $redirect_url);
                    die($pay_data['html']);
D
devil_gong 已提交
305 306
                } else {
                    $result = DataReturn('success', 0, $pay_data);
D
devil_gong 已提交
307
                }
D
devil_gong 已提交
308 309 310 311
                break;

            // APP支付
            case 'APP' :
D
devil_gong 已提交
312
                $pay_data = array(
313 314
                    'appid'         => $pay_params['appid'],
                    'partnerid'     => $pay_params['mch_id'],
D
devil_gong 已提交
315 316 317 318 319 320 321
                    '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);
D
devil_gong 已提交
322 323 324 325 326
                break;
        }
        return $result;
    }

G
wx pay  
gongfuxiang 已提交
327 328 329 330 331 332 333
    /**
     * 支付代码
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2019-05-25T00:07:52+0800
     * @param    [array]                   $pay_data     [支付信息]
D
devil 已提交
334
     * @param    [string]                  $redirect_url [支付结束后跳转url]
G
wx pay  
gongfuxiang 已提交
335 336 337
     */
    private function PayHtml($pay_data, $redirect_url)
    {
G
wx pay  
gongfuxiang 已提交
338
        // 支付代码
G
gongfuxiang 已提交
339
        return '<html>
G
wx pay  
gongfuxiang 已提交
340 341 342
            <head>
                <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
                <title>微信安全支付</title>
G
gongfuxiang 已提交
343 344 345 346 347 348
                <meta name="apple-mobile-web-app-capable" content="yes">
                <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1">
                <body style="text-align:center;padding-top:10%;">
                    <p style="color:#999;">正在支付中...</p>
                    <p style="color:#f00;margin-top:20px;">请不要关闭页面!</p>
                </body>
G
wx pay  
gongfuxiang 已提交
349 350 351 352
                <script type="text/javascript">
                    function onBridgeReady()
                    {
                       WeixinJSBridge.invoke(
G
wx pay  
gongfuxiang 已提交
353 354 355 356 357 358 359 360 361
                            \'getBrandWCPayRequest\', {
                                "appId":"'.$pay_data['appId'].'",
                                "timeStamp":"'.$pay_data['timeStamp'].'",
                                "nonceStr":"'.$pay_data['nonceStr'].'",
                                "package":"'.$pay_data['package'].'",     
                                "signType":"'.$pay_data['signType'].'",
                                "paySign":"'.$pay_data['paySign'].'"
                            },
                            function(res) {
D
devil 已提交
362
                                window.location.href = "'.$redirect_url.'";
G
wx pay  
gongfuxiang 已提交
363 364
                            }
                        ); 
G
wx pay  
gongfuxiang 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
                    }
                    if(typeof WeixinJSBridge == "undefined")
                    {
                       if( document.addEventListener )
                       {
                           document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
                       } else if (document.attachEvent)
                       {
                           document.attachEvent("WeixinJSBridgeReady", onBridgeReady); 
                           document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
                       }
                    } else {
                       onBridgeReady();
                    }
                </script>
G
gongfuxiang 已提交
380 381
            </head>
        </html>';
G
wx pay  
gongfuxiang 已提交
382 383
    }

D
devil_gong 已提交
384 385 386 387 388 389 390 391 392 393 394
    /**
     * 获取支付参数
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-07
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    private function GetPayParams($params = [])
    {
D
devil_gong 已提交
395 396 397 398 399 400
        $trade_type = empty($params['trade_type']) ? $this->GetTradeType() : $params['trade_type'];
        if(empty($trade_type))
        {
            return DataReturn('支付类型不匹配', -1);
        }

D
devil 已提交
401 402 403
        // 平台
        $client_type = ApplicationClientType();

D
devil_gong 已提交
404
        // openid
D
devil 已提交
405
        if($client_type == 'weixin')
D
devil_gong 已提交
406 407 408
        {
            $openid = isset($params['user']['weixin_openid']) ? $params['user']['weixin_openid'] : '';
        } else {
G
wx pay  
gongfuxiang 已提交
409
            $openid = isset($params['user']['weixin_web_openid']) ? $params['user']['weixin_web_openid'] : '';
D
devil_gong 已提交
410 411
        }

D
devil_gong 已提交
412
        // appid
D
Devil 已提交
413
        $appid = $this->PayAppID($client_type);
D
devil_gong 已提交
414

G
wx pay  
gongfuxiang 已提交
415
        // 异步地址处理
D
devil 已提交
416
        $notify_url = ($client_type == 'qq') ? 'https://api.q.qq.com/wxpay/notify' : $this->GetNotifyUrl($params);
G
wx pay  
gongfuxiang 已提交
417

D
devil_gong 已提交
418
        // 请求参数
D
devil_gong 已提交
419
        $data = [
D
devil_gong 已提交
420
            'appid'             => $appid,
D
devil_gong 已提交
421
            'mch_id'            => $this->config['mch_id'],
D
devil_gong 已提交
422
            'body'              => $params['site_name'].'-'.$params['name'],
D
devil 已提交
423
            'nonce_str'         => md5(time().$params['order_no']),
G
wx pay  
gongfuxiang 已提交
424
            'notify_url'        => $notify_url,
D
devil_gong 已提交
425
            'openid'            => ($trade_type == 'JSAPI') ? $openid : '',
D
devil 已提交
426
            'out_trade_no'      => $params['order_no'],
D
devil_gong 已提交
427
            'spbill_create_ip'  => GetClientIP(),
D
devil 已提交
428
            'total_fee'         => (int) (($params['total_price']*1000)/10),
D
devil_gong 已提交
429
            'trade_type'        => $trade_type,
G
debug  
gongfuxiang 已提交
430
            'attach'            => empty($params['attach']) ? $params['site_name'].'-'.$params['name'] : $params['attach'],
D
devil_gong 已提交
431
            'sign_type'         => 'MD5',
432
            'time_expire'       => $this->OrderAutoCloseTime(),
D
devil_gong 已提交
433
        ];
D
devil_gong 已提交
434
        $data['sign'] = $this->GetSign($data);
D
devil_gong 已提交
435 436 437
        return DataReturn('success', 0, $data);
    }

D
Devil 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450
    /**
     * appid获取
     * @author  Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2021-04-25
     * @desc    description
     * @param   [string]          $client_type [客户端类型]
     */
    public function PayAppID($client_type)
    {
        $arr = [
            'weixin'    => $this->config['mini_appid'],
D
v2.0.2  
Devil 已提交
451 452
            'ios'       => $this->config['app_appid'],
            'android'   => $this->config['app_appid'],
D
Devil 已提交
453 454 455 456
        ];
        return array_key_exists($client_type, $arr) ? $arr[$client_type] : $this->config['appid'];
    }

457 458 459 460 461 462 463 464 465 466 467 468 469 470
    /**
     * 订单自动关闭的时间
     * @author  Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2021-03-24
     * @desc    description
     */
    public function OrderAutoCloseTime()
    {
        $time = intval(MyC('common_order_close_limit_time', 30, true))*60;
        return date('YmdHis', time()+$time);
    }

D
devil 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484
    /**
     * 获取异步通知地址
     * @author  Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2020-09-19
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    private function GetNotifyUrl($params)
    {
        return (__MY_HTTP__ == 'https' && isset($this->config['agreement']) && $this->config['agreement'] == 1) ? 'http'.mb_substr($params['notify_url'], 5, null, 'utf-8') : $params['notify_url'];
    }

D
devil_gong 已提交
485 486 487 488 489 490 491 492 493 494
    /**
     * 获取支付交易类型
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-08
     * @desc    description
     */
    private function GetTradeType()
    {
D
devil 已提交
495 496 497 498
        // 平台
        $client_type = ApplicationClientType();

        // 平台类型定义
D
devil_gong 已提交
499 500 501 502
        $type_all = [
            'pc'        => 'NATIVE',
            'weixin'    => 'JSAPI',
            'h5'        => 'MWEB',
D
devil_gong 已提交
503
            'toutiao'   => 'MWEB',
D
devil 已提交
504
            'qq'        => 'MWEB',
D
devil_gong 已提交
505 506 507
            'app'       => 'APP',
            'ios'       => 'APP',
            'android'   => 'APP',
D
devil_gong 已提交
508 509
        ];

G
gongfuxiang 已提交
510 511
        // h5
        if($client_type == 'h5')
D
devil_gong 已提交
512
        {
G
gongfuxiang 已提交
513
            // 微信中打开
G
gongfuxiang 已提交
514 515 516 517 518 519 520 521 522 523
            if(IsWeixinEnv())
            {
                $type_all['h5'] = $type_all['weixin'];
            } else {
                // 非手机访问h5则使用NATIVE二维码的方式
                if(!IsMobile())
                {
                    $type_all['h5'] = $type_all['pc'];
                }
            }
D
devil_gong 已提交
524
        }
D
devil_gong 已提交
525

D
devil 已提交
526
        return isset($type_all[$client_type]) ? $type_all[$client_type] : '';
D
devil_gong 已提交
527 528
    }

D
devil_gong 已提交
529 530 531 532 533 534 535 536 537 538 539
    /**
     * 支付回调处理
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-19
     * @desc    description
     * @param   [array]           $params [输入参数]
     */
    public function Respond($params = [])
    {
G
debug  
gongfuxiang 已提交
540
        $result = empty($GLOBALS['HTTP_RAW_POST_DATA']) ? $this->XmlToArray(file_get_contents('php://input')) : $this->XmlToArray($GLOBALS['HTTP_RAW_POST_DATA']);
D
devil_gong 已提交
541

G
debug  
gongfuxiang 已提交
542
        if(isset($result['result_code']) && $result['result_code'] == 'SUCCESS' && $result['sign'] == $this->GetSign($result))
G
debug  
gongfuxiang 已提交
543
        {
G
debug  
gongfuxiang 已提交
544
            return DataReturn('支付成功', 0, $this->ReturnData($result));
G
debug  
gongfuxiang 已提交
545
        }
G
debug  
gongfuxiang 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
        return DataReturn('处理异常错误', -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)
    {
        // 返回数据固定基础参数
        $data['trade_no']       = $data['transaction_id'];  // 支付平台 - 订单号
        $data['buyer_user']     = $data['openid'];          // 支付平台 - 用户
D
devil 已提交
562
        $data['out_trade_no']   = $data['out_trade_no'];    // 本系统发起支付的 - 订单号
G
debug  
gongfuxiang 已提交
563
        $data['subject']        = $data['attach'];          // 本系统发起支付的 - 商品名称
G
debug  
gongfuxiang 已提交
564
        $data['pay_price']      = $data['total_fee']/100;   // 本系统发起支付的 - 总价
G
debug  
gongfuxiang 已提交
565
        return $data;
D
devil_gong 已提交
566 567
    }

D
devil_gong 已提交
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 595 596 597 598 599 600 601 602 603 604 605 606 607
    /**
     * 退款处理
     * @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);
        }

D
devil_gong 已提交
608 609 610 611 612 613
        // 证书是否配置
        if(empty($this->config['apiclient_cert']) || empty($this->config['apiclient_key']))
        {
            return DataReturn('证书未配置', -1);
        }

D
devil_gong 已提交
614 615 616
        // 退款原因
        $refund_reason = empty($params['refund_reason']) ? $params['order_no'].'订单退款'.$params['refund_price'].'元' : $params['refund_reason'];

D
devil_gong 已提交
617
        // appid,默认使用公众号appid
D
Devil 已提交
618
        $appid = $this->PayAppID($params['client_type']);
D
devil_gong 已提交
619 620 621 622 623 624 625 626

        // 请求参数
        $data = [
            'appid'             => $appid,
            'mch_id'            => $this->config['mch_id'],
            'nonce_str'         => md5(time().rand().$params['order_no']),
            'sign_type'         => 'MD5',
            'transaction_id'    => $params['trade_no'],
D
Devil 已提交
627 628
            'out_trade_no'      => $params['order_no'],
            'out_refund_no'     => $params['order_no'].GetNumberCode(),
D
devil 已提交
629 630
            'total_fee'         => (int) (($params['pay_price']*1000)/10),
            'refund_fee'        => (int) (($params['refund_price']*1000)/10),
D
devil_gong 已提交
631
            'refund_desc'       => $refund_reason,            
D
devil_gong 已提交
632 633 634
        ];
        $data['sign'] = $this->GetSign($data);

D
debug  
devil_gong 已提交
635 636
        // 请求接口处理
        $result = $this->XmlToArray($this->HttpRequest('https://api.mch.weixin.qq.com/secapi/pay/refund', $this->ArrayToXml($data), true));
D
devil_gong 已提交
637
        if(isset($result['result_code']) && $result['result_code'] == 'SUCCESS' && isset($result['return_code']) && $result['return_code'] == 'SUCCESS')
D
devil_gong 已提交
638 639 640 641
        {
            // 统一返回格式
            $data = [
                'out_trade_no'  => isset($result['out_trade_no']) ? $result['out_trade_no'] : '',
G
gongfuxiang 已提交
642
                'trade_no'      => isset($result['transaction_id']) ? $result['transaction_id'] : (isset($result['err_code_des']) ? $result['err_code_des'] : ''),
D
devil_gong 已提交
643
                'buyer_user'    => isset($result['refund_id']) ? $result['refund_id'] : '',
G
gongfuxiang 已提交
644
                'refund_price'  => isset($result['refund_fee']) ? $result['refund_fee']/100 : 0.00,
D
devil_gong 已提交
645 646 647 648
                'return_params' => $result,
            ];
            return DataReturn('退款成功', 0, $data);
        }
D
devil_gong 已提交
649 650
        $msg = is_string($result) ? $result : (empty($result['err_code_des']) ? '退款接口异常' : $result['err_code_des']);
        if(!empty($result['return_msg']))
D
devil_gong 已提交
651
        {
D
devil_gong 已提交
652
            $msg .= '-'.$result['return_msg'];
D
devil_gong 已提交
653 654 655 656
        }
        return DataReturn($msg, -1);
    }

D
devil_gong 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    /**
     * 签名生成
     * @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)
        {
D
devil_gong 已提交
672 673 674 675
            if($k != 'sign' && $v != '' && $v != null)
            {
                $sign .= "$k=$v&";
            }
D
devil_gong 已提交
676 677 678 679
        }
        return strtoupper(md5($sign.'key='.$this->config['key']));
    }

D
devil_gong 已提交
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    /**
     * 数组转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;
    }

D
devil_gong 已提交
700 701 702 703 704 705 706 707 708 709 710
    /**
     * 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)
    {
D
devil_gong 已提交
711 712 713 714
        if(!$this->XmlParser($xml))
        {
            return is_string($xml) ? $xml : '接口返回数据有误';
        }
D
devil_gong 已提交
715 716 717 718

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

D
devil_gong 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

    /**
     * 判断字符串是否为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));
        }
    }

D
devil_gong 已提交
741 742 743 744 745 746 747 748 749
    /**
     * [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    [是否需要使用证书]
750
     * @param    [int]             $second      [超时]
D
devil_gong 已提交
751 752
     * @return   [mixed]                        [请求返回数据]
     */
D
devil_gong 已提交
753
    private function HttpRequest($url, $data, $use_cert = false, $second = 30)
D
devil_gong 已提交
754 755 756 757 758
    {
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_POST           => true,
D
debug  
devil_gong 已提交
759 760
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
D
devil_gong 已提交
761
            CURLOPT_POSTFIELDS     => $data,
762
            CURLOPT_TIMEOUT        => $second,
D
devil_gong 已提交
763 764 765 766
        );

        if($use_cert == true)
        {
D
devil_gong 已提交
767 768
            //设置证书
            //使用证书:cert 与 key 分别属于两个.pem文件
D
debug  
devil_gong 已提交
769
            $apiclient = $this->GetApiclientFile();
D
debug  
devil_gong 已提交
770
            $options[CURLOPT_SSLCERTTYPE] = 'PEM';
D
debug  
devil_gong 已提交
771
            $options[CURLOPT_SSLCERT] = $apiclient['cert'];
D
debug  
devil_gong 已提交
772
            $options[CURLOPT_SSLKEYTYPE] = 'PEM';
D
debug  
devil_gong 已提交
773
            $options[CURLOPT_SSLKEY] = $apiclient['key'];
D
devil_gong 已提交
774 775 776 777 778
        }
 
        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
D
devil_gong 已提交
779 780 781 782 783 784 785 786 787 788
        //返回结果
        if($result)
        {
            curl_close($ch);
            return $result;
        } else { 
            $error = curl_errno($ch);
            curl_close($ch);
            return "curl出错,错误码:$error";
        }
D
devil_gong 已提交
789
    }
D
debug  
devil_gong 已提交
790 791 792 793 794 795 796 797 798 799 800 801

    /**
     * 获取证书文件路径
     * @author  Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-05-29
     * @desc    description
     */
    private function GetApiclientFile()
    {
        // 证书位置
G
gongfuxiang 已提交
802 803
        $apiclient_cert_file = ROOT.'runtime'.DS.'cache'.DS.'payment_weixin_pay_apiclient_cert.pem';
        $apiclient_key_file = ROOT.'runtime'.DS.'cache'.DS.'payment_weixin_pay_apiclient_key.pem';
D
debug  
devil_gong 已提交
804

D
devil_gong 已提交
805
        // 证书处理
D
devil_gong 已提交
806 807 808 809 810 811 812 813
        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 已提交
814 815
        file_put_contents($apiclient_cert_file, $apiclient_cert);

D
devil_gong 已提交
816 817 818 819 820 821 822 823
        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 已提交
824 825
        file_put_contents($apiclient_key_file, $apiclient_key);

D
debug  
devil_gong 已提交
826 827
        return ['cert' => $apiclient_cert_file, 'key' => $apiclient_key_file];
    }
D
devil_gong 已提交
828 829
}
?>