PHPSDK.php 52.2 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 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
<?php
namespace common\exts\wechat;


use common\exts\wechat\Log;
use common\exts\wechat\Http;
use common\exts\wechat\AccessToken;
use common\exts\wechat\Log as WxLog;

/**
 *
 *  @注意: 这里移除了支付相关的接口
 *
 *	微信公众平台PHP-SDK, 官方API部分
 *  @author  dodge <dodgepudding@gmail.com>
 *  @link https://github.com/dodgepudding/wechat-php-sdk
 *  @version 1.2
 *  usage:
 *   $options = array(
 *			'token'=>'tokenaccesskey', //填写你设定的key
 *			'appid'=>'wxdk1234567890', //填写高级调用功能的app id
 *			'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
 *		);
 *	 $weObj = new Wechat($options);
 *   $weObj->valid();
 *   $type = $weObj->getRev()->getRevType();
 *   switch($type) {
 *   		case Wechat::MSGTYPE_TEXT:
 *   			$weObj->text("hello, I'm wechat")->reply();
 *   			exit;
 *   			break;
 *   		case Wechat::MSGTYPE_EVENT:
 *   			....
 *   			break;
 *   		case Wechat::MSGTYPE_IMAGE:
 *   			...
 *   			break;
 *   		default:
 *   			$weObj->text("help info")->reply();
 *   }
 *   //获取菜单操作:
 *   $menu = $weObj->getMenu();
 *   //设置菜单
 *   $newmenu =  array(
 *   		"button"=>
 *   			array(
 *   				array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
 *   				array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
 *   				)
 *  		);
 *   $result = $weObj->createMenu($newmenu);
 *
 * Class PHPSDK
 * @package common\exts\wechat
 */
class PHPSDK
{
    const MSGTYPE_TEXT = 'text';
    const MSGTYPE_IMAGE = 'image';
    const MSGTYPE_LOCATION = 'location';
    const MSGTYPE_MINIPROGRAMPAGE = 'miniprogrampage';
    const MSGTYPE_USER_LOCATION = 'LOCATION';
    const MSGTYPE_LINK = 'link';
    const MSGTYPE_EVENT = 'event';
    const MSGTYPE_MUSIC = 'music';
    const MSGTYPE_NEWS = 'news';
    const MSGTYPE_VOICE = 'voice';
    const MSGTYPE_VIDEO = 'video';
    const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
    const AUTH_URL = '/token?grant_type=client_credential&';
    const MENU_CREATE_URL = '/menu/create?';
    const MENU_GET_URL = '/menu/get?';
    const MEDIA_FOREVER_UPLOAD_URL = '/material/add_material?';
    const MEDIA_UPLOAD_URL = '/media/upload?';
    const MEDIA_UPLOADIMG_URL = '/media/uploadimg?';//图片上传接口
    const MENU_DELETE_URL = '/menu/delete?';
    const MEDIA_GET_URL = '/media/get?';
    const QRCODE_CREATE_URL='/qrcode/create?';
    const QR_SCENE = 0;
    const QR_LIMIT_SCENE = 1;
    const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
    const USER_GET_URL='/user/get?';
    const USER_INFO_URL='/user/info?';
    const GROUP_GET_URL='/groups/get?';
    const GROUP_CREATE_URL='/groups/create?';
    const GROUP_UPDATE_URL='/groups/update?';
    const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
    const CUSTOM_SEND_URL='/message/custom/send?';
    const TEMPLATE_SEND_URL='/message/template/send?';
    const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
    const OAUTH_AUTHORIZE_URL = '/authorize?';
    const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
    const OAUTH_REFRESH_URL = '/refresh_token?';
    const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
    const CUSTOM_SERVICE = '/customservice/getrecord?';
    const GET_TEMPLATE_URL = '/template/api_add_template?'; // 添加模板
    const GET_TEMPLATE_LIST_URL = '/template/get_all_private_template?'; // 获取已添加模板列表
    const DEL_TEMPLATE_URL = '/template/del_private_template?'; // 删除指定ID的模板
    const GET_SHORT_URL = '/shorturl?'; // 长链接转成短链接

    const MINIAPP_TEMPLATE_SEND_URL = '/message/wxopen/template/send?'; // 小程序-发送模板消息
    const MINIAPP_JSCODE2SESSION_URL = 'https://api.weixin.qq.com/sns/jscode2session?';
    const FILE_API_URL='http://file.api.weixin.qq.com/cgi-bin';
    const SET_DYNAMIC_DATA = 'https://api.weixin.qq.com/wxa/setdynamicdata?';

    private $token;
    private $appid;
    private $appsecret;
    private $access_token;
    private $user_token;
    private $_msg;
    private $_funcflag = false;
    private $_receive;
    public  $debug =  false;
    public  $errCode = null;
    public  $errMsg = null;
    private $_logcallback;

    /**
     * @param $options
     */
    public function __construct($options)
    {
        $this->token = isset($options['token'])?$options['token']:'';
        $this->appid = isset($options['appid'])?$options['appid']:'';
        $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
        $this->debug = isset($options['debug'])?$options['debug']:false;
        $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
    }

    /**
     * For weixin server validation
     * @return bool
     */
    private function checkSignature()
    {
        $signature = isset($_GET["signature"])?$_GET["signature"]:'';
        $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
        $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';

        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * For weixin server validation
     *
     * @param bool|false $return
     * @return bool|string $return 是否返回
     */
    public function valid($return = false)
    {
        $echoStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
        if ($return) {
            if ($echoStr) {
                if ($this->checkSignature())
                    return $echoStr;
                else
                    return false;
            } else
                return $this->checkSignature();
        } else {
            if ($echoStr) {
                if ($this->checkSignature())
                    die($echoStr);
                //echo $echoStr;

                else
                    die('no access1');
            }  else {
                if ($this->checkSignature())
                    return true;
                else
                    die('no access2');
            }
        }
        return false;
    }

    /**
     *
     *
     * 设置发送消息
     * @param string|array $msg 消息数组
     * @param bool $append 是否在原消息数组追加
     * @return array
     */
    public function Message($msg = '', $append = false)
    {
        if (is_null($msg)) {
            $this->_msg =array();
        } elseif (is_array($msg)) {
            if ($append)
                $this->_msg = array_merge($this->_msg,$msg);
            else
                $this->_msg = $msg;
            return $this->_msg;
        } else {
            return $this->_msg;
        }
    }

    /**
     * @param $flag
     * @return $this
     */
    public function setFuncFlag($flag)
    {
        $this->_funcflag = $flag;
        return $this;
    }

    /**
     * @param $log
     * @return mixed
     */
    private function log($log)
    {
        if ($this->debug && function_exists($this->_logcallback)) {
            if (is_array($log))
                $log = print_r($log, true);
            return call_user_func($this->_logcallback,$log);
        }
    }

    /**
     * 获取微信服务器发来的信息
     */
    public function getRev()
    {
        if ($this->_receive) return $this;
        $postStr = file_get_contents("php://input");
        $this->log($postStr);
        if (!empty($postStr)) {
            $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        }
        return $this;
    }

    /**
     * 获取微信服务器发来的信息
     */
    public function getRevData()
    {
        return $this->_receive;
    }

    /**
     * 获取消息发送者
     */
    public function getRevFrom()
    {
        if (isset($this->_receive['FromUserName']))
            return $this->_receive['FromUserName'];
        else
            return false;
    }

    /**
     * 获取消息接受者
     */
    public function getRevTo()
    {
        if (isset($this->_receive['ToUserName']))
            return $this->_receive['ToUserName'];
        else
            return false;
    }

    /**
     * 获取接收消息的类型
     */
    public function getRevType()
    {
        if (isset($this->_receive['MsgType']))
            return $this->_receive['MsgType'];
        else
            return false;
    }

    /**
     * 获取消息ID
     */
    public function getRevID()
    {
        if (isset($this->_receive['MsgId']))
            return $this->_receive['MsgId'];
        else
            return false;
    }

    /**
     * 获取消息发送时间
     */
    public function getRevCtime()
    {
        if (isset($this->_receive['CreateTime']))
            return $this->_receive['CreateTime'];
        else
            return false;
    }

    /**
     * 获取接收消息内容正文
     */
    public function getRevContent()
    {
        if (isset($this->_receive['Content']))
            return $this->_receive['Content'];
        else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
            return $this->_receive['Recognition'];
        else
            return false;
    }

    /**
     * 获取接收消息图片
     */
    public function getRevPic()
    {
        if (isset($this->_receive['PicUrl']))
            return $this->_receive['PicUrl'];
        else
            return false;
    }

    /**
     * 获取接收消息链接
     */
    public function getRevLink()
    {
        if (isset($this->_receive['Url'])){
            return array(
                'url'=>$this->_receive['Url'],
                'title'=>$this->_receive['Title'],
                'description'=>$this->_receive['Description']
            );
        } else
            return false;
    }

    /**
     * 获取接收地理位置
     */
    public function getRevGeo()
    {
        if (isset($this->_receive['Location_X'])){
            return array(
                'x'=>$this->_receive['Location_X'],
                'y'=>$this->_receive['Location_Y'],
                'scale'=>$this->_receive['Scale'],
                'label'=>$this->_receive['Label']
            );
        } else
            return false;
    }

    /**
     * 获取上报地理位置事件
     */
    public function getRevEventGeo()
    {
        if (isset($this->_receive['Latitude'])){
            return array(
                'x'=>$this->_receive['Latitude'],
                'y'=>$this->_receive['Longitude'],
                'precision'=>$this->_receive['Precision'],
            );
        } else
            return false;
    }

    /**
     * 获取接收事件推送
     */
    public function getRevEvent()
    {
        if (isset($this->_receive['Event'])){
            return array(
                'event'=>$this->_receive['Event'],
                'key'=>isset($this->_receive['EventKey']) ? $this->_receive['EventKey'] : '#', // 判断是否存在
            );
        } else
            return false;
    }

    /**
     * 获取接收语言推送
     */
    public function getRevVoice()
    {
        if (isset($this->_receive['MediaId'])){
            return array(
                'mediaid'=>$this->_receive['MediaId'],
                'format'=>$this->_receive['Format'],
            );
        } else
            return false;
    }

    /**
     * 获取接收视频推送
     */
    public function getRevVideo()
    {
        if (isset($this->_receive['MediaId'])){
            return array(
                'mediaid'=>$this->_receive['MediaId'],
                'thumbmediaid'=>$this->_receive['ThumbMediaId']
            );
        } else
            return false;
    }

    /**
     * 获取接收TICKET
     */
    public function getRevTicket()
    {
        if (isset($this->_receive['Ticket'])){
            return $this->_receive['Ticket'];
        } else
            return false;
    }

    /**
     * 获取二维码的场景值
     */
    public function getRevSceneId ()
    {
        if (isset($this->_receive['EventKey'])){
            return str_replace('qrscene_','',$this->_receive['EventKey']);
        } else{
            return false;
        }
    }

    /**
     * @param $str
     * @return string
     */
    public static function xmlSafeStr($str)
    {
        return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
    }

    /**
     * 数据XML编码
     * @param mixed $data 数据
     * @return string
     */
    public static function data_to_xml($data) {
        $xml = '';
        foreach ($data as $key => $val) {
            is_numeric($key) && $key = "item id=\"$key\"";
            $xml    .=  "<$key>";
            $xml    .=  ( is_array($val) || is_object($val)) ? self::data_to_xml($val)  : self::xmlSafeStr($val);
            list($key, ) = explode(' ', $key);
            $xml    .=  "</$key>";
        }
        return $xml;
    }

    /**
     * XML编码
     * @param mixed $data 数据
     * @param string $root 根节点名
     * @param string $item 数字索引的子节点名
     * @param string $attr 根节点属性
     * @param string $id   数字索引子节点key转换的属性名
     * @param string $encoding 数据编码
     * @return string
     */
    public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8')
    {
        if(is_array($attr)){
            $_attr = array();
            foreach ($attr as $key => $value) {
                $_attr[] = "{$key}=\"{$value}\"";
            }
            $attr = implode(' ', $_attr);
        }
        $attr   = trim($attr);
        $attr   = empty($attr) ? '' : " {$attr}";
        $xml   = "<{$root}{$attr}>";
        $xml   .= self::data_to_xml($data, $item, $id);
        $xml   .= "</{$root}>";
        return $xml;
    }

    /**
     * 设置回复消息
     * Examle: $obj->text('hello')->reply();
     * @param string $text
     * @return $this
     */
    public function text($text='')
    {
        $FuncFlag = $this->_funcflag ? 1 : 0;
        $msg = array(
            'ToUserName' => $this->getRevFrom(),
            'FromUserName'=>$this->getRevTo(),
            'MsgType'=>self::MSGTYPE_TEXT,
            'Content'=>$text,
            'CreateTime'=>time(),
            'FuncFlag'=>$FuncFlag
        );
        $this->Message($msg);
        return $this;
    }

    /**
     * 设置回复消息
     * Example: $obj->image('media_id')->reply();
     * @param string $mediaid
     * @return $this
     */
    public function image($mediaid='')
    {
        $FuncFlag = $this->_funcflag ? 1 : 0;
        $msg = array(
            'ToUserName' => $this->getRevFrom(),
            'FromUserName'=>$this->getRevTo(),
            'MsgType'=>self::MSGTYPE_IMAGE,
            'Image'=>array('MediaId'=>$mediaid),
            'CreateTime'=>time(),
            'FuncFlag'=>$FuncFlag
        );
        $this->Message($msg);
        return $this;
    }

    /**
     *
     * 设置回复音乐
     * @param $title
     * @param $desc
     * @param $musicurl
     * @param string $hgmusicurl
     * @return $this
     */
    public function music($title,$desc,$musicurl,$hgmusicurl='') {
        $FuncFlag = $this->_funcflag ? 1 : 0;
        $msg = array(
            'ToUserName' => $this->getRevFrom(),
            'FromUserName'=>$this->getRevTo(),
            'CreateTime'=>time(),
            'MsgType'=>self::MSGTYPE_MUSIC,
            'Music'=>array(
                'Title'=>$title,
                'Description'=>$desc,
                'MusicUrl'=>$musicurl,
                'HQMusicUrl'=>$hgmusicurl
            ),
            'FuncFlag'=>$FuncFlag
        );
        $this->Message($msg);
        return $this;
    }

    /**
     * 设置回复图文
     * @param array $newsData
     * 数组结构:
     *  array(
     *  	"0"=>array(
     *  		'Title'=>'msg title',
     *  		'Description'=>'summary text',
     *  		'PicUrl'=>'http://www.domain.com/1.jpg',
     *  		'Url'=>'http://www.domain.com/1.html'
     *  	),
     *  	"1"=>....
     *  )
     * @param array $newsData
     * @return $this
     */
    public function news($newsData=array())
    {
        $FuncFlag = $this->_funcflag ? 1 : 0;
        $count = count($newsData);

        $msg = array(
            'ToUserName' => $this->getRevFrom(),
            'FromUserName'=>$this->getRevTo(),
            'MsgType'=>self::MSGTYPE_NEWS,
            'CreateTime'=>time(),
            'ArticleCount'=>$count,
            'Articles'=>$newsData,
            'FuncFlag'=>$FuncFlag
        );
        $this->Message($msg);
        return $this;
    }

    /**
     *
     * 回复微信服务器, 此函数支持链式操作
     * @example $this->text('msg tips')->reply();
     *
     * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
     * @param string|array $msg 要发送的信息, 默认取$this->_msg
     * @param bool|false $return
     * @return string
     */
    public function reply($msg=array(),$return = false)
    {
        if (empty($msg))
            $msg = $this->_msg;
        $xmldata=  $this->xml_encode($msg);
        $this->log($xmldata);
        if ($return)
            return $xmldata;
        else
            echo $xmldata;
    }


    /**
     * 删除验证数据
     * @param string $appid
     * @return bool
     */
    public function resetAuth($appid=''){
        $this->access_token = '';
        //TODO: remove cache
        return true;
    }

    /**
     * 微信api不支持中文转义的json结构
     * @param array $arr
     * @return string
     */
    static function json_encode($arr)
    {
        $parts = array ();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys ( $arr );

        $max_length = count ( $arr ) - 1;
        if (($keys[0] === 0)
            && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ( $arr as $key => $value ) {
            if (is_array ( $value )) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = self::json_encode ( $value ); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
            } else {
                $str = '';
                if (! $is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (is_numeric ( $value ) && $value<2000000000)
                    $str .= $value; //Numbers
                elseif ($value === false)
                    $str .= 'false'; //The booleans
                elseif ($value === true)
                    $str .= 'true';
                else
                    $str .= '"' . addslashes ( $value ) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts [] = $str;
            }
        }
        $json = implode ( ',', $parts );
        if ($is_list)
            return '[' . $json . ']'; //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }

    /**
     * 创建菜单
     * @param array $data 菜单数组数据
     * example:
     * {
     * "button":[
     * {
     * "type":"click",
     * "name":"今日歌曲",
     * "key":"MENU_KEY_MUSIC"
     * },
     * {
     * "type":"view",
     * "name":"歌手简介",
     * "url":"http://www.qq.com/"
     * },
     * {
     * "name":"菜单",
     * "sub_button":[
     * {
     * "type":"click",
     * "name":"hello word",
     * "key":"MENU_KEY_MENU"
     * },
     * {
     * "type":"click",
     * "name":"赞一下我们",
     * "key":"MENU_KEY_GOOD"
     * }]
     * }]
     * }
     * @param $data
     * @return bool
     */
    public function createMenu($data)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        //$result = Http::post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token, self::json_encode($data));
        $result = $this->safeHttpPost(self::API_URL_PREFIX.self::MENU_CREATE_URL, self::json_encode($data));

        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 获取菜单
     * @return array('menu'=>array(....s))
     */
    public function getMenu()
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        //$result = Http::get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
        $result = $this->safeHttpGet(self::API_URL_PREFIX.self::MENU_GET_URL);
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || isset($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 删除菜单
     * @return boolean
     */
    public function deleteMenu()
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        //$result = Http::get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
        $result = $this->safeHttpGet(self::API_URL_PREFIX.self::MENU_DELETE_URL);
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 根据媒体文件ID获取媒体文件
     * @param string $media_id 媒体文件id
     * @return raw data
     */
    public function getMedia($media_id,$version=0)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        if($version==0){
            $apipre=self::API_URL_PREFIX;
        }else{
            $apipre=self::FILE_API_URL;
        }
        $result = Http::getImageStream($apipre.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
        if ($result)
        {
            //if (is_string($result)) {
                $json = json_decode($result['body'], true);
                //$json = json_decode($result, true);
                if (isset($json['errcode'])) {
                    $this->errCode = $json['errcode'];
                    $this->errMsg = $json['errmsg'];
                    return false;
                }
            //}
            return $result;
        }
        return false;
    }

    /**
     * 创建临时二维码ticket
     * @param int $scene_id 自定义追踪id
     * @param int $expire 临时二维码有效期,最大为1800秒
     * @param bool $isStrScene 是否使用字符串参数值
     * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800)
     */
    public function getQRCode($sceneId, $expire = 2592000, $isStrScene = false)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array(
            'action_name' => $isStrScene ? "QR_STR_SCENE" : "QR_SCENE",
            'expire_seconds'=>$expire,
            'action_info' => $isStrScene ? array('scene'=>array('scene_str'=>$sceneId)) : array('scene'=>array('scene_id'=>$sceneId))
        );
        //$result = Http::post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::QRCODE_CREATE_URL, self::json_encode($data));
        if ($result)
        {
            WxLog::init();
            WxLog::DEBUG("getQRCode: result=>" . $result);
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 创建永久二维码ticket
     * @param $scene_id 场景值ID
     * @param int $type
     * @param bool $isStrScene 是否使用字符串参数值
     * 0:  场景值ID为32位非0整型;
     * 1:  场景值ID为字符串形式,长度限制为1到64(仅永久二维码支持此字段)
     * @return array('ticket'=>'qrcode字串','url'=>'二维码图片解析后的地址')
     */
    public function getLimitQRCode($scene_id, $isStrScene = false)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array(
            'action_name' => $isStrScene ? "QR_LIMIT_STR_SCENE" : "QR_LIMIT_SCENE",
            'action_info' => $isStrScene ? array('scene'=>array('scene_str'=>$scene_id)) : array('scene'=>array('scene_id'=>$scene_id))
        );
        //$result = Http::post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::QRCODE_CREATE_URL, self::json_encode($data));
        if ($result)
        {
            WxLog::init();
            WxLog::DEBUG("getLimitQRCode: result=>" . $result);
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 获取二维码图片
     * @param string $ticket 传入由getQRCode方法生成的ticket参数
     * @return string url 返回http地址
     */
    public function getQRUrl($ticket)
    {
        return self::QRCODE_IMG_URL . $ticket;
    }

    /**
     * 批量获取关注用户列表
     * @param string $next_openid
     * @return bool|mixed
     */
    public function getUserList($next_openid=''){
        if (!$this->access_token && !$this->checkAuth()) return false;
        $result = Http::get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
        if ($result)
        {
            $json = json_decode($result,true);
            if (isset($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 通用auth验证方法,暂时仅用于菜单更新操作
     * @return bool|mixed
     */
    public function checkAuth($forceRefresh = false)
    {
        $result = $this->getAccessToken($forceRefresh);

        if($result){
            $this->access_token = $result;
            return  $this->access_token;
        }
        return false;
    }

    /**
     * 获取文件中的AccessToken
     * @return mixed
     */
    private function getAccessToken($forceRefresh = false)
    {
        $this->access_token = AccessToken::get($this->appid, $this->appsecret, $forceRefresh);
        return $this->access_token;
    }

    /**
     *
     * 获取关注者详细信息
     * 已关注:
     * {
     *     "subscribe":1
     *     "openid":"oicCewkZUxj7tv92z57TiX7ehN28",
     *     "nickname":"\u534e\u5347@\u6d41\u5149\u6620\u753b",
     *     "sex":1,"language":"zh_CN",
     *     "city":"\u5357\u5b81",
     *     "province":"\u5e7f\u897f",
     *     "country":"\u4e2d\u56fd",
     *     "headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/hiamn2bFGxrN76Kq21WD5Tm9Cr91p68h52bWr2rEr9iaUCIib63jsibxDQvNsjPBtxD9HKZwiaAvNfPTpibYQxmefNQw\/0",
     *     "subscribe_time":1462272994,
     *     "remark":"",
     *     "groupid":0,
     *     "tagid_list":[]
     * }
     *
     * 未关注:
     * {
     *     "subscribe":0,
     *     "openid":"oicCewi22xTYCclqDOVEP-g-uawY",
     *     "tagid_list":[]
     * }
     *
     * @param $openid
     * @return bool|mixed
     */
    public function getUserInfo($openid)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        $result = Http::get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
        $json = json_decode($result);
        if(isset($json->errcode) && $json->errcode == 40001) {
            WxLog::init();
            WxLog::WARN("getUserInfo: result=>" . $result . "  access_token无效错误, 自动恢复!");
            if ($this->checkAuth(true)) {
                $result = Http::get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
            }
        }

        if ($result) {
            $json = json_decode($result,true);
            if (isset($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return $json;
            }
            return $json;
        }
        return false;
    }

    /**
     * 获取用户分组列表
     * @return boolean|array
     */
    public function getGroup()
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        $result = Http::get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);

        if ($result)
        {
            $json = json_decode($result,true);
            if (isset($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 新增自定分组
     * @param string $name 分组名称
     * @return boolean|array
     */
    public function createGroup($name)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array(
            'group'=>array('name'=>$name)
        );
        $result = Http::post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 更改分组名称
     * @param int $groupid 分组id
     * @param string $name 分组名称
     * @return boolean|array
     */
    public function updateGroup($groupid, $name)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array(
            'group'=>array('id'=>$groupid,'name'=>$name)
        );
        $result = Http::post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 移动用户分组
     * @param int $groupid 分组id
     * @param string $openid 用户openid
     * @return boolean|array
     */
    public function updateGroupMembers($groupid, $openid)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array(
            'openid'=>$openid,
            'to_groupid'=>$groupid
        );
        $result = Http::post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 发送客服消息
     * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
     * @return boolean|array
     */
    public function sendCustomMessage($data)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        //$result = Http::post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
        $result = $this->safeHttpPost(self::API_URL_PREFIX.self::CUSTOM_SEND_URL, self::json_encode($data));

        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return $json;
            }

            return true;
        }
        return false;
    }

    /**
     * 发送模板消息
     * @param $data
     * @return bool|mixed
     */
    public function sendTemplateMessage($data)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::TEMPLATE_SEND_URL, json_encode($data));
        if ($result)
        {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                WxLog::init();
                WxLog::ERROR("sendTemplateMessage: errCode=[" .  $json['errcode'] . "],errMsg=[" .  $json['errmsg'] . "]");
                return $json;
            }

            return true;
        }
        return false;
    }

    /**
     * 获取access_token
     * @param $data
     * @return bool|mixed
     */
    public function sendWxTemplateMessage()
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;
        return $this->access_token;
    }

    /**
     * 根据模板库中模板的编号获取模板ID
     * 备注: 由于不同微信公众号的模板ID不一样(即便是同一个行业模板), 所以需要根据统一编号做动态获取
     * 官方说明: 从行业模板库选择模板到帐号后台,获得模板ID的过程可在微信公众平台后台完成
     * @param $data
     * @return bool|mixed
     */
    public function getTemplateId($data)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;
        //$result = Http::post(self::API_URL_PREFIX . self::GET_TEMPLATE_URL . 'access_token=' . $this->access_token, json_encode($data));
        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::GET_TEMPLATE_URL, json_encode($data));

        if ($result)
        {
            $json = json_decode($result, true);
//            if (!$json || !empty($json['errcode'])) {
//                $this->errCode = $json['errcode'];
//                $this->errMsg = $json['errmsg'];
//                return false;
//            }
            return $json;
        }
        return false;
    }

    /**
     * 获取已添加的模板列表
     * 官方说明: 获取已添加至帐号下所有模板列表,可在微信公众平台后台中查看模板列表信息
     * @return boolean|array
     */
    public function getTemplateList()
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;
        $result = $this->safeHttpGet(self::API_URL_PREFIX . self::GET_TEMPLATE_LIST_URL);
        if ($result)
        {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 删除微信公众号后台指定的模板
     * 官方说明: 删除模板可在微信公众平台后台完成,为方便第三方开发者,提供通过接口调用的方式来删除某帐号下的模板
     * @param $data
     * @return bool|mixed
     */
    public function delTemplateId($data)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;
        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::DEL_TEMPLATE_URL, json_encode($data));
        if ($result)
        {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * oauth 授权跳转接口
     * @param string $callback 回调URI
     * @return string
     */
    public function getOAuthRedirect($callback, $state='', $scope='snsapi_userinfo')
    {
        return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
    }

    /*
     * 通过code获取Access Token(用户访问的)
     * @return array {access_token,expires_in,refresh_token,openid,scope}
     */
    public function getOAuthAccessToken($code)
    {
        if (!$code) {
            return false;
        }

        $url = self::OAUTH_TOKEN_PREFIX.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';

        $result = Http::get($url);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return $json;
            }
            $this->user_token = $json['access_token'];
            return $json;
        }
        return false;
    }

    /**
     * 刷新access token并续期
     * @param string $refresh_token
     * @return boolean|mixed
     */
    public function getOAuthRefreshToken($refresh_token)
    {
        $result = Http::get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
        if ($result) {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            $this->user_token = $json['access_token'];
            return $json;
        }
        return false;
    }

    /**
     * 获取授权后的用户资料
     * @param string $access_token
     * @param string $openid
     * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege}
     */
    public function getOAuthUserinfo($access_token, $openid)
    {
        $result = Http::get(self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 获取签名
     * @param array $arrdata 签名数组
     * @param string $method 签名方法
     * @return boolean|string 签名值
     */
    public function getSignature($arrdata,$method="sha1")
    {
        if (!function_exists($method)) return false;
        ksort($arrdata);
        $paramstring = "";
        foreach($arrdata as $key => $value)
        {
            if(strlen($paramstring) == 0)
                $paramstring .= $key . "=" . $value;
            else
                $paramstring .= "&" . $key . "=" . $value;
        }
        $paySign = $method($paramstring);
        return $paySign;
    }

    /**
     * 生成随机字串
     * $length 长度,默认为16,最长为32字节
     *
     * @param int $length
     * @return string
     */
    public function generateNonceStr($length=16){
        // 密码字符集,可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for($i = 0; $i < $length; $i++)
        {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    /**
     * 获取收货地址JS的签名
     * @param string $url
     * @param int $timeStamp
     * @param string $nonceStr
     * @param string $user_token
     * @return Ambigous <boolean, string>
     */
    public function getAddrSign($url, $timeStamp, $nonceStr, $user_token = '')
    {
        if (!$user_token) $user_token = $this->user_token;
        if (!$user_token) {
            $this->errMsg = 'no user access token found!';
            return false;
        }
        $url = htmlspecialchars_decode($url);
        $arrdata = array(
            'appid'=>$this->appid,
            'url'=>$url,
            'timestamp'=>strval($timeStamp),
            'noncestr'=>$nonceStr,
            'accesstoken'=>$user_token
        );
        return $this->getSignature($arrdata);
    }

    /**
     * 获取多客服获取会话记录
     * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
     * @return boolean|array
     */
    public function getCustomServiceMessage($data)
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        $result = Http::post(self::API_URL_PREFIX.self::CUSTOM_SERVICE.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 上传永久素材(认证后的订阅号可用)
     * 新增的永久素材也可以在公众平台官网素材管理模块中看到
     * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
     * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
     * @param array $data {"media":'@Path\filename.jpg'}
     * @param string $type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
     * @param boolean $is_video 是否为视频文件,默认为否
     * @param array $video_info 视频信息数组,非视频素材不需要提供 array('title'=>'视频标题','introduction'=>'描述')
     * @return boolean|array
     */
    public function uploadForeverMedia($data, $type, $is_video = false, $video_info = [])
    {
        if (!$this->access_token && !$this->checkAuth()) return false;
        //#TODO 暂不确定此接口是否需要让视频文件走http协议
        //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
        //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
        //当上传视频文件时,附加视频文件信息
        if ($is_video) $data['description'] = self::json_encode($video_info);
        $result = Http::post_material(self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
        //F("uploaddataurl",self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type);
        //F("uploaddata",$data);
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 上传临时素材,有效期为3天(认证后的订阅号可用)
     * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
     * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
     * 注意:临时素材的media_id是可复用的!
     * @param array $data {"media":'@Path\filename.jpg'}
     * @param string $type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
     * @return boolean|array
     */
    public function uploadMedia($filepath, $type)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        // 组成数据
        if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
            $filedata = array (
                'media' => new \CURLFile ( realpath ( $filepath ), 'image/jpeg' )
            );
        } else {
            $filedata = array (
                'media' => '@' . realpath ( $filepath )
            );
        }

        //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
        $url = self::API_URL_PREFIX . self::MEDIA_UPLOAD_URL . 'access_token=' . $this->access_token . '&type=' . $type;
        $result = Http::upload($url, $filedata);
        if ($result) {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * @param $file_info
     * @return bool
     */
    public function addMaterial($file_info)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        $url="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$this->access_token}&type=image";
        $ch1 = curl_init ();
        $timeout = 5;
        $real_path="{$_SERVER['DOCUMENT_ROOT']}{$file_info['filename']}";
        //$real_path=str_replace("/", "\\", $real_path);
        $data= array("media"=>"@{$real_path}",'form-data'=>$file_info);
        curl_setopt ( $ch1, CURLOPT_URL, $url );
        curl_setopt ( $ch1, CURLOPT_POST, 1 );
        curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec ( $ch1 );
        curl_close ( $ch1 );

        if(curl_errno()==0){
            $result=json_decode($result,true);
            return $result['media_id'];
        } else {
            return false;
        }

    }

    /**
     * 返回对应微信公众号的唯一AppID
     * @return string
     */
    public function getAppID()
    {
        return $this->appid;
    }

    /**
     * 封装一个较为稳妥的Http get请求接口
     * 说明: 可以自动纠正一次40001错误(access_token无效)
     * @param $urlHeader
     * @return bool|mixed
     */
    private function safeHttpGet($urlHeader)
    {
        $result = Http::get($urlHeader . 'access_token=' . $this->access_token);
        if ($result) {
            $json = json_decode($result);
            WxLog::init();
            WxLog::DEBUG("safeHttpGet: result=>" . $result);
            if (isset($json->errcode) && $json->errcode == 40001) {
                WxLog::WARN("safeHttpGet: 检测到access_token无效错误, 自动恢复!");
                if ($this->checkAuth(true)) {
                    $result = Http::get($urlHeader . 'access_token=' . $this->access_token);
                }
            }
        }
        return $result;
    }

    /**
     * 封装一个较为稳妥的Http post请求接口
     * 说明: 可以自动纠正一次40001错误(access_token无效)
     * @param $urlHeader
     * @param $param
     * @return bool|mixed
     */
    private function safeHttpPost($urlHeader, $param)
    {
        $result = Http::post($urlHeader . 'access_token=' . $this->access_token, $param);
        if ($result) {
            $json = json_decode($result);
            if(isset($json->errcode) && $json->errcode == 40001) {
                WxLog::init();
                WxLog::WARN("safeHttpPost: 检测到access_token无效错误, 自动恢复!");
                if ($this->checkAuth(true)) {
                    $result = Http::post($urlHeader . 'access_token=' . $this->access_token, $param);
                }
            }
        }

        return $result;
    }

    /**
     * 长链接转成短链接
     * 主要使用场景: 开发者用于生成二维码的原链接(商品、支付二维码等)太长导致扫码速度和成功率下降,
     * 将原长链接通过此接口转成短链接再生成二维码将大大提升扫码速度和成功率。
     * @param string long_url 需要转换的长链接,支持http://、https://、weixin://wxpay 格式的url
     * @return string
     */
    public function getShortUrl($long_url)
    {
        if (!$this->access_token && !$this->checkAuth())
            return false;

        $data = array(
            'action'=>'long2short',
            'long_url'=>$long_url
        );
        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::GET_SHORT_URL, json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                return false;
            }
            return $json['short_url'];
        }
        return false;
    }


    /**
     * 小程序-发送模板消息
     * @param $data
     * @return bool|mixed
     */
    public function miniAppSendTemplateMessage($data)
    {
        if (!$this->access_token && !$this->checkAuth()) {
            return false;
        }

        $result = $this->safeHttpPost(self::API_URL_PREFIX . self::MINIAPP_TEMPLATE_SEND_URL, json_encode($data));
        if ($result)
        {
            $json = json_decode($result, true);
//            if (!$json || !empty($json['errcode'])) {
//                $this->errCode = $json['errcode'];
//                $this->errMsg = $json['errmsg'];
//                return false;
//            }

            return $json;
        }
        return false;
    }

    /**
     * 获取小程序会话数据:  open_id和session_key
     * @param string $code 登录凭证
     */
    public function getMiniAppSession($appid, $secret, $code)
    {
        $url = self::MINIAPP_JSCODE2SESSION_URL . 'appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $result = Http::post($url, array());
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * @param $param
     * @return bool|mixed
     *
     * {
        "lifespan": 86400,
        "query": "{\"type\":100001}",
        "scene": 1,
        "data": "{\"items\":[{\"stock_name\":\"腾讯控股\", \"stock_code\":\"00700\", \"stock_market\":\"hk\"}], \"attribute\":{\"count\":2, \"totalcount\": 100, \"id\": \"XXX\", \"seq\": 0}}"
        }
     */
    public function setDynamicData($param)
    {
        if (!$this->access_token && !$this->checkAuth()) {
            return false;
        }
        $result = $this->safeHttpPost(self::SET_DYNAMIC_DATA, $param);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }
}