weixin.class.php 39.8 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 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
<?php
/**
 * tpshop 微信支付插件
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: IT宇宙人
 * Date: 2015-09-09
 */

use think\Model; 
/**
 * 支付 逻辑定义
 * Class 
 * @package Home\Payment
 */

class weixin extends Model
{    
    public $tableName = 'plugin'; // 插件表        
    public $alipay_config = array();// 支付宝支付配置参数


    public $appid="";
    public $mchid="";
    public $key="";
    public $appsecret="";

    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();
        require_once("lib/WxPay.Api.php"); // 微信扫码支付demo 中的文件         
        require_once("example/WxPay.NativePay.php");
        require_once("example/WxPay.JsApiPay.php");
        //$paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find(); // 找到微信支付插件的配置
        //$config_value = unserialize($paymentPlugin['config_value']); // 配置反序列化
        $config_value=M("wx_user")->where('store_id',getMobileStoId())->find();

        $this->appid = $config_value['appid']; // * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
        $this->mchid = $config_value['mchid']; // * MCHID:商户号(必须配置,开户邮件中可查看)
        $this->key = $config_value['mchkey']; // KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)
        $this->appsecret = $config_value['appsecret']; // 公众帐号secert(仅JSAPI支付的时候需要配置),

        mlog( $this->appid.$this->mchid.$this->key.$this->appsecret,'recharge');
    }    
    /**
     * 生成支付代码
     * @param   array   $orderno      订单信
     * @param   array   $config_value    支付方式信息
     */
    function get_code($orderno, $config_value)
    {       
            $notify_url = SITE_URL.'/index.php/Home/Payment/notifyUrl/pay_code/weixin'; // 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
            //$notify_url = C('site_url').U('Home/Payment/notifyUrl',array('pay_code'=>'weixin')); // 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
            //$notify_url = C('site_url')."/index.php?m=Home&c=Payment&a=notifyUrl&pay_code=weixin";

            $order_amount=M("order")->where("parent_sn",$orderno)->sum("order_amount");
            $input = new WxPayUnifiedOrder();
            $input->SetBody("TPshop商品"); // 商品描述
            $input->SetAttach("weixin"); // 附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
            $input->SetOut_trade_no($orderno); // 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号

            //$input->SetTotal_fee($order_amount*100); // 订单总金额,单位为分,详见支付金额
            $input->SetTotal_fee(0.01*100); // 订单总金额,单位为分,详见支付金额

            $input->SetNotify_url($notify_url); // 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
            $input->SetTrade_type("NATIVE"); // 交易类型   取值如下:JSAPI,NATIVE,APP,详细说明见参数规定    NATIVE--原生扫码支付
            $input->SetProduct_id("123456789"); // 商品ID trade_type=NATIVE,此参数必传。此id为二维码中包含的商品ID,商户自行定义。
            $notify = new NativePay();
            $result = $notify->GetPayUrl($input); // 获取生成二维码的地址
            $url2 = $result["code_url"];
            return '<img alt="模式二扫码支付" src="/index.php?m=Home&c=Index&a=qr_code&data='.urlencode($url2).'" style="width:110px;height:110px;"/>';        
    }    
    /**
     * 服务器点对点响应操作给支付接口方调用
     * 
     */
    function response()
    {
        try {
            mlog("开始","backorder");
            require_once("example/notify.php");
            $notify = new PayNotifyCallBack();
            $notify->Handle(false);
        }catch(Exception $e){
            mlog($e->getMessage(),"backorder");
        }
    }
    
    /**
     * 页面跳转响应操作给支付接口方调用
     */
    function respond2()
    {
        // 微信扫码支付这里没有页面返回
    }

    //余额充值
    function getJSAPI_VOP($orderno)
    {
        $ord = M('recharge')->where(array('order_sn'=>$orderno,'recharge_type'=>0))->find();
        $go_url = U('Mobile/payment/recharge_success', array('stoid' => $ord['store_id'], 'order_id' => $ord['order_id']));
        $back_url = U('Mobile/User/index', array('stoid' => $ord['store_id']));
        $order_amount = $ord['account'];
        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid, $this->key, $this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("余额充值:" . $orderno);
        $input->SetAttach("weixin_vop");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        $input->SetNotify_url(curHostURL() . '/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            mlog(json_encode($jsApiParameters), "getJSAPI/" . $ord['store_id']);
            if ($jsApiParameters == -999) {
                return ['code' => -1, 'msg' => '支付参数错误'];
            }
        } catch (Exception $e) {
            mlog('error:' . $e->getMessage(), "getJSAPI/" . $ord['store_id']);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;


        return $html;
    }

    //积分充值
    function getJSAPI_VOI($orderno)
    {
        $ord = M('recharge')->where(array('order_sn'=>$orderno,'recharge_type'=>1))->find();
        $go_url = U('Mobile/payment/recharge_success', array('stoid' => $ord['store_id'], 'order_id' => $ord['order_id']));
        $back_url = U('Mobile/User/index', array('stoid' => $ord['store_id']));
        $order_amount = $ord['account'];
        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid, $this->key, $this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("余额充值:" . $orderno);
        $input->SetAttach("weixin_voi");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        $input->SetNotify_url(curHostURL() . '/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            mlog(json_encode($jsApiParameters), "getJSAPI/" . $ord['store_id']);
            if ($jsApiParameters == -999) {
                return ['code' => -1, 'msg' => '支付参数错误'];
            }
        } catch (Exception $e) {
            mlog('error:' . $e->getMessage(), "getJSAPI/" . $ord['store_id']);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;


        return $html;
    }




    //购买服务卡
    function getJSAPI_SER($orderno)
    {
        $ord = M('recharge')->where(array('order_sn'=>$orderno,'recharge_type'=>2))->find();
        $go_url = U('Mobile/payment/recharge_success', array('stoid' => $ord['store_id'], 'order_id' => $ord['order_id']));
        $back_url = U('Mobile/User/shopping_card', array('stoid' => $ord['store_id']));
        $order_amount = $ord['account'];
        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid, $this->key, $this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("购买服务卡:" . $orderno);
        $input->SetAttach("weixin_ser");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        $input->SetNotify_url(curHostURL() . '/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            mlog(json_encode($jsApiParameters), "getJSAPI/" . $ord['store_id']);
            if ($jsApiParameters == -999) {
                return ['code' => -1, 'msg' => '支付参数错误'];
            }
        } catch (Exception $e) {
            mlog('error:' . $e->getMessage(), "getJSAPI/" . $ord['store_id']);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;


        return $html;
    }

    //等级卡 3:购买  4:续费
    function getJSAPI_VLC($orderno)
    {
        $ord = M('recharge')->where(array('order_sn'=>$orderno,'recharge_type'=>array('in','3,4')))->find();
        $go_url = U('Mobile/payment/recharge_success', array('stoid' => $ord['store_id'], 'order_id' => $ord['order_id']));
        $back_url = U('Mobile/User/userinfo', array('stoid' => $ord['store_id']));
        $order_amount = $ord['account'];
        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid, $this->key, $this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("购买等级卡:" . $orderno);
        $input->SetAttach("weixin_vlc");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        $input->SetNotify_url(curHostURL() . '/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            mlog(json_encode($jsApiParameters), "getJSAPI/" . $ord['store_id']);
            if ($jsApiParameters == -999) {
                return ['code' => -1, 'msg' => '支付参数错误'];
            }
        } catch (Exception $e) {
            mlog('error:' . $e->getMessage(), "getJSAPI/" . $ord['store_id']);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;


        return $html;
    }

    //购买礼包
    function getJSAPI_LB($orderno)
    {
        $ord = M('libao_formvip')
            ->alias("a")
            ->join("libao_form b", "a.lbid=b.id", "left")
            ->where("a.number='" . $orderno . "'")
            ->field("a.*,b.lbprice")
            ->order("a.id desc")
            ->find();


        $go_url = U('Mobile/payment/payment_success', array('stoid' => $ord['store_id'], 'ptype' => 2));
        $back_url = U('Mobile/Libao/index', array('stoid' => $ord['store_id']));

        $order_amount = $ord['lbprice'];
        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid, $this->key, $this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("购买礼包:" . $orderno);
        $input->SetAttach("weixin_lb");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        $input->SetNotify_url(curHostURL() . '/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            mlog(json_encode($jsApiParameters), "getJSAPI/" . $ord['store_id']);
            if ($jsApiParameters == -999) {
                return ['code' => -1, 'msg' => '支付参数错误'];
            }
        } catch (Exception $e) {
            mlog('error:' . $e->getMessage(), "getJSAPI/" . $ord['store_id']);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;


        return $html;
    }

    //普通订单
    function getJSAPI($orderno)
    {

        $ord = M('Order')->where("parent_sn", $orderno)->select();
        $go_url = U('Mobile/payment/payment_success', array('stoid' => $ord[0]['store_id'],"orderno"=>$ord[0]['order_sn']));
        //$back_url = U('/Mobile/User/order_detail',array('id'=>$ord[0]['order_id'],'stoid'=>$ord[0]['store_id']));
        $back_url = U('/Mobile/payment/pay_error', array('ordno' => $ord[0]['order_sn'], 'stoid' => $ord[0]['store_id'], '支付失败'));
        $order_amount = M('Order')->where("parent_sn", $orderno)->sum('order_amount');


        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid, $this->key, $this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("支付订单:" . $orderno);
        $input->SetAttach("weixin");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        //$input->SetNotify_url(SITE_URL.'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetNotify_url(curHostURL() . '/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        mlog("支付订单:" . $orderno, "getJSAPI/" . $ord['store_id']);

        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);

            $getreturn_msg="支付参数错误";
            if ($order2['return_code']=="FAIL")
            {
                $getreturn_msg=$order2['return_msg'];
            }

            $jsApiParameters = $tools->GetJsApiParameters($order2);
            mlog(json_encode($jsApiParameters), "getJSAPI/" . $ord[0]['store_id']);
            if ($jsApiParameters == -999) {
                return ['code' => -1, 'msg' => $getreturn_msg];
            }
        } catch (Exception $e) {
            mlog('error:' . $e->getMessage(), "getJSAPI/" . $ord['store_id']);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;


        return $html;

    }

    //送礼神器使用
    function getJSAPI2($orderno){
        $go_url="";
        $ord=M('giftuser_order')->where("parent_sn", $orderno)->select();
        if($ord[0]['state']==1){
            //开始赠送
            $go_url = U('Mobile/Giftuser/to_send',array('stoid'=>$ord[0]['store_id'],'ordno'=>$orderno));
        }else{
            //购物车购买要进入已购列表
            $go_url = U('Mobile/payment/payment_success2',array('stoid'=>$ord[0]['store_id']));
        }
        $back_url = U('/Mobile/payment/pay_error2',array('ordno'=>$ord[0]['order_sn'],'stoid'=>$ord[0]['store_id'],'支付失败'));
        $order_amount = M('giftuser_order')->where("parent_sn", $orderno)->sum('order_amount');

        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid,$this->key,$this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("支付订单:".$orderno);
        $input->SetAttach("weixin");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        //$input->SetNotify_url(SITE_URL.'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetNotify_url(curHostURL().'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            //dump($order2); exit();
            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            //printf_info($order);exit;
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            if ($jsApiParameters == -999) {
                return ['code'=>-1,'msg'=>'支付参数错误'];
            }
        }catch(Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;

        return $html;

    }

    //天天拼单使用
    function getJSAPI3($orderno){
        $go_url="";
        $ord=M('order')->where("order_sn", $orderno)->select();
        //支付成功
        $go_url = U('Mobile/team/team_success',
            array('stoid'=>$ord[0]['store_id'],'orderno'=>$ord[0]['order_sn'],'wxok'=>1));
         //支付失败
        $back_url = U('/Mobile/team/team_error',array('orderno'=>$ord[0]['order_sn'],'stoid'=>$ord[0]['store_id']));
        $order_amount = M('order')->where("order_sn", $orderno)->sum('order_amount');

        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid,$this->key,$this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("支付订单:".$orderno);
        $input->SetAttach("weixin");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        //$input->SetNotify_url(SITE_URL.'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetNotify_url(curHostURL().'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            //dump($order2); exit();
            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            //printf_info($order);exit;
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            if ($jsApiParameters == -999) {
                return ['code'=>-1,'msg'=>'支付参数错误'];
            }
        }catch(Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;

        return $html;

    }

    //天天拼单使用
    function getJSAPI_pt_wk($orderno){
        $go_url="";
        $ord=M('order')->where("order_sn", $orderno)->find();
        //支付成功
        $go_url = U('Mobile/team/team_success',array('stoid'=>$ord['store_id'],'orderno'=>$ord['order_sn']));
        //支付失败
        $back_url = U('/Mobile/team/team_error',array('orderno'=>$ord['order_sn'],'stoid'=>$ord['store_id'],'payfail'=>1));
        $order_amount = M('order')->where("order_sn", $orderno)->sum('pt_tail_money');

        mlog('333-'.$order_amount,'getCode_pt/'.$ord['store_id']);

        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid,$this->key,$this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //$orderno.='_wk';
        $orderno.='_'.date("s").rand(10, 99);
        mlog("1:".$orderno,"getJSAPI_pt_wk/".$ord['store_id']);

        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("支付订单:".$orderno);
        $input->SetAttach("weixin");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        //$input->SetNotify_url(SITE_URL.'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetNotify_url(curHostURL().'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            //dump($order2); exit();
            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            //printf_info($order);exit;
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            if ($jsApiParameters == -999) {
                return ['code'=>-1,'msg'=>'支付参数错误'];
            }
        }catch(Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;

        return $html;

    }


    /**
     * 微信退款,传入微信parent_sn,$total_fee总额,$refund_fee退款金额,$path路径
     */
    function refund($ordno,$total_fee,$refund_fee,$path,$appid="",$mchid="",$key=""){
            $out_trade_no = $ordno;
            $input = new WxPayRefund();
            $input->SetOut_trade_no($out_trade_no);
            $input->SetTotal_fee($total_fee*100);
            $input->SetRefund_fee($refund_fee*100);
            $input->SetOut_refund_no(date("YmdHis"));

            if(empty($appid)) $appid=$this->appid;
            if(empty($mchid)) $mchid=$this->mchid;
            if(empty($key)) $key=$this->key;

            $input->SetOp_user_id($mchid);
            $rs=WxPayApi::refund($input,6,$path,$appid,$mchid,$key);
            return $rs;
    }

    //设置
    function setCong($stoid){
        $config_value=M("wx_user")->where('store_id',$stoid)->find();
        $this->appid = $config_value['appid']; // * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
        $this->mchid = $config_value['mchid']; // * MCHID:商户号(必须配置,开户邮件中可查看)
        $this->key = $config_value['mchkey']; // KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)
        $this->appsecret = $config_value['appsecret']; // 公众帐号secert(仅JSAPI支付的时候需要配置),
    }

    //查询订单
    public function query_odr($odrno,$stoid){
            $config_value=M("wx_user")->where('store_id',$stoid)->field('appid,mchid,mchkey')->find();
            $this->appid = $config_value['appid']; // * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
            $this->mchid = $config_value['mchid']; // * MCHID:商户号(必须配置,开户邮件中可查看)
            $this->key = $config_value['mchkey']; // KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)

            $input = new WxPayOrderQuery();
            $input->SetOut_trade_no($odrno);
            $result = WxPayApi::orderQuery($input,$this->appid,$this->mchid,$this->key);
            mlog("pro查询订单".json_encode($result),'query_odr/'.$stoid);
            if(array_key_exists("return_code", $result)
                && array_key_exists("result_code", $result)
                && $result["return_code"] == "SUCCESS"
                && $result["result_code"] == "SUCCESS")
            {
                return true;
            }
            return false;
    }

    //查询退款订单
    public function query_refund_odr($odrno,$stoid,$rf_no=null){
        $config_value=M("wx_user")->where('store_id',$stoid)->field('appid,mchid,mchkey')->find();

        $this->appid = $config_value['appid']; // * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
        $this->mchid = $config_value['mchid']; // * MCHID:商户号(必须配置,开户邮件中可查看)
        $this->key = $config_value['mchkey']; // KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)

        $input = new WxPayRefundQuery();
        $input->SetOut_trade_no($odrno);
        if($rf_no)$input->SetOut_refund_no($rf_no);

        $result = WxPayApi::refundQuery($input,12, $this->appid, $this->mchid,$this->key);
        mlog("pro查询订单".json_encode($result),'query_odr/'.$stoid);
        return $result;
    }

    /**
     * 微信退款,传入微信parent_sn,$total_fee总额,$refund_fee退款金额,$path路径
     */
    function refund2($ordno,$total_fee,$refund_fee,$path,$stoid,$rf_no="",$order_source_type=0){

        $config_value=M("wx_user")->where('store_id',$stoid)->field('appid,mchid,mchkey')->find();
        //---如果订单的来源是小程序的时候---
        if($order_source_type){
            $path_wxapp= BASE_PATH . 'public/cert/' . $stoid . '/weapp/';
            $conf_app_value = M("weapp")->where('store_id', $stoid)->field('appid,mchid,mchkey')->find();

            if($config_value['mchid']!=$conf_app_value['mchid']){
                $config_value=$conf_app_value;
                $path=$path_wxapp;
            }
        }


        $appid = $config_value['appid']; // * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
        $mchid = $config_value['mchid']; // * MCHID:商户号(必须配置,开户邮件中可查看)
        $key = $config_value['mchkey']; // KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)

        $out_trade_no = $ordno;
        $input = new WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee*100);
        $input->SetRefund_fee($refund_fee*100);

        if(empty($rf_no)) $rf_no='t'.date("YmdHis").get_total_millisecond().rand(1000, 9999).$stoid;
        $input->SetOut_refund_no($rf_no);

        $input->SetOp_user_id($mchid);
        $rs=WxPayApi::refund($input,12,$path,$appid,$mchid,$key);
        mlog('退款结果:'.json_encode($rs),'refund/'.$stoid);
        return $rs;
    }

    function refund_wk($pay_sn,$total_fee,$refund_fee,$path,$stoid,$rf_no="",$order_source_type=0){

        $config_value=M("wx_user")->where('store_id',$stoid)->field('appid,mchid,mchkey')->find();
        //---如果订单的来源是小程序的时候---
        if($order_source_type){
            $path_wxapp= BASE_PATH . 'public/cert/' . $stoid . '/weapp/';
            $conf_app_value = M("weapp")->where('store_id', $stoid)->field('appid,mchid,mchkey')->find();

            if($config_value['mchid']!=$conf_app_value['mchid']){
                $config_value=$conf_app_value;
                $path=$path_wxapp;
            }
        }

        $appid = $config_value['appid']; // * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
        $mchid = $config_value['mchid']; // * MCHID:商户号(必须配置,开户邮件中可查看)
        $key = $config_value['mchkey']; // KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)

        //$out_trade_no = $ordno;
        $input = new WxPayRefund();
        $input->SetTransaction_id($pay_sn);
        $input->SetTotal_fee($total_fee*100);
        $input->SetRefund_fee($refund_fee*100);

        if(empty($rf_no)) $rf_no='t'.date("YmdHis").get_total_millisecond().rand(1000, 9999).$stoid;
        $input->SetOut_refund_no($rf_no);

        $input->SetOp_user_id($mchid);
        $rs=WxPayApi::refund($input,12,$path,$appid,$mchid,$key);
        mlog('退款结果:'.json_encode($rs),'refund/'.$stoid);
        return $rs;
    }


    /*------购买礼包等参数的入参------*/
    function getJSAPI_new_lb($ord){
        $go_url="";
        //支付成功
        $go_url = U('Mobile/Payment/pay_lb_success',array('stoid'=>$ord['store_id'],'orderno'=>$ord['order_sn']));
        //支付失败
        $back_url = U('/Mobile/Payment/pay_lb_error',array('orderno'=>$ord['order_sn'],'stoid'=>$ord['store_id']));

        $order_amount =$ord['pay_money'];
        mlog('333-'.$order_amount,'getJSAPI_new_lb/'.$ord['store_id']);

        //①、获取用户openid
        $tools = new JsApiPay();
        $tools->setConf($this->appid,$this->key,$this->appsecret);
        //$openId = $tools->GetOpenid();
        $openId = $_SESSION['openid'];
        //$orderno.='_wk';
        $orderno=$ord['order_sn'];
        mlog("1:".$orderno,"getJSAPI_new_lb/".$ord['store_id']);


        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("支付订单:".$orderno);
        $input->SetAttach("weixin_new_lb");
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($order_amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("tp_wx_pay");
        //$input->SetNotify_url(SITE_URL.'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetNotify_url(curHostURL().'/index.php/Home/Payment/notifyUrl/pay_code/weixin');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        try {
            $order2 = WxPayApi::unifiedOrder($input, $this->appid, $this->mchid, $this->key);
            //dump($order2); exit();
            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            //printf_info($order);exit;
            $jsApiParameters = $tools->GetJsApiParameters($order2);
            if ($jsApiParameters == -999) {
                return ['code'=>-1,'msg'=>'支付参数错误'];
            }
        }catch(Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        $html = <<<EOF
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',$jsApiParameters,
			function(res){
				//WeixinJSBridge.log(res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") {
				    location.href='$go_url';
				 }else{
                    //alert(res.err_code+res.err_desc+res.err_msg);
				    location.href='$back_url';
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	callpay();
	</script>
EOF;

        return $html;

    }
}