From 356cccd1d4afdfc541c720e997040e9bb324122b Mon Sep 17 00:00:00 2001 From: molong Date: Sat, 26 Aug 2017 17:57:10 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81=E5=B7=B2=E7=9F=A5bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=202=E3=80=81=E5=BE=AE=E4=BF=A1=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/admin/controller/Category.php | 8 +- application/common/controller/Api.php | 10 + application/common/model/AuthRule.php | 12 +- application/common/model/Page.php | 17 - application/common/validate/Member.php | 2 +- core/extend/Wechat/Lib/Cache.php | 71 +++- core/extend/Wechat/Lib/Common.php | 81 +++- core/extend/Wechat/Lib/Prpcrypt.php | 54 ++- core/extend/Wechat/Lib/Tools.php | 108 +++-- core/extend/Wechat/Loader.php | 32 +- core/extend/Wechat/WechatCard.php | 107 +++-- core/extend/Wechat/WechatCustom.php | 59 ++- core/extend/Wechat/WechatDevice.php | 68 +++- core/extend/Wechat/WechatExtends.php | 40 +- core/extend/Wechat/WechatHardware.php | 33 +- core/extend/Wechat/WechatMedia.php | 110 ++++-- core/extend/Wechat/WechatMenu.php | 33 +- core/extend/Wechat/WechatMessage.php | 352 +++++++++++++++++ core/extend/Wechat/WechatOauth.php | 30 +- core/extend/Wechat/WechatPay.php | 164 ++++++-- core/extend/Wechat/WechatPoi.php | 33 +- core/extend/Wechat/WechatReceive.php | 454 ++++++---------------- core/extend/Wechat/WechatScript.php | 24 +- core/extend/Wechat/WechatService.php | 65 +++- core/extend/Wechat/WechatUser.php | 81 ++-- 25 files changed, 1353 insertions(+), 695 deletions(-) delete mode 100644 application/common/model/Page.php create mode 100644 core/extend/Wechat/WechatMessage.php diff --git a/application/admin/controller/Category.php b/application/admin/controller/Category.php index e3b2f895..a784932b 100644 --- a/application/admin/controller/Category.php +++ b/application/admin/controller/Category.php @@ -129,10 +129,10 @@ class Category extends Admin { return $this->error('请先删除该分类下的子分类'); } //判断该分类下有没有内容 - $document_list = db('Document')->where(array('category_id' => $id))->field('id')->select(); - if (!empty($document_list)) { - return $this->error('请先删除该分类下的文章(包含回收站)'); - } + // $document_list = db('Document')->where(array('category_id' => $id))->field('id')->select(); + // if (!empty($document_list)) { + // return $this->error('请先删除该分类下的文章(包含回收站)'); + // } //删除该分类信息 $res = db('Category')->where(array('id' => $id))->delete(); if ($res !== false) { diff --git a/application/common/controller/Api.php b/application/common/controller/Api.php index 90035d21..400a8562 100644 --- a/application/common/controller/Api.php +++ b/application/common/controller/Api.php @@ -15,6 +15,16 @@ class Api { public function __construct() { header("Access-Control-Allow-Origin: *"); + header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE"); + header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept , token"); $this->data = array('code' => 0, 'msg' => '', 'time' => time(), 'data' => ''); + if (!$this->checkToken()) { + $this->data['code'] = '301'; + $this->data['data'] = '非法请求!'; + } + } + + protected function checkToken(){ + return true; } } \ No newline at end of file diff --git a/application/common/model/AuthRule.php b/application/common/model/AuthRule.php index a570a8b9..28cde637 100644 --- a/application/common/model/AuthRule.php +++ b/application/common/model/AuthRule.php @@ -32,7 +32,8 @@ class AuthRule extends Base{ public function uprule($data, $type){ foreach ($data as $value) { - $data = array( + $id = $this->where(array('name' => $value['url']))->value('id'); + $save = array( 'module' => $type, 'type' => 2, 'name' => $value['url'], @@ -40,14 +41,11 @@ class AuthRule extends Base{ 'group' => $value['group'], 'status' => 1, ); - $id = $this->where(array('name' => $data['name']))->value('id'); if ($id) { - $data['id'] = $id; - $this->save($data, array('id' => $id)); - } else { - self::create($data); + $save['id'] = $id; } + $list[] = $save; } - return true; + return $this->saveAll($list); } } \ No newline at end of file diff --git a/application/common/model/Page.php b/application/common/model/Page.php deleted file mode 100644 index 4d76b4ee..00000000 --- a/application/common/model/Page.php +++ /dev/null @@ -1,17 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace app\common\model; - -/** - * 分类模型 - */ -class Page extends Content{ - -} \ No newline at end of file diff --git a/application/common/validate/Member.php b/application/common/validate/Member.php index 85587a8f..548675bb 100644 --- a/application/common/validate/Member.php +++ b/application/common/validate/Member.php @@ -15,7 +15,7 @@ namespace app\common\validate; class Member extends Base{ protected $rule = array( - 'username' => 'require|unique:member|/^[a-zA-Z]\w{0,39}$/', + 'username' => 'require|unique:member', 'email' => 'require|unique:member|email', 'mobile' => 'unique:member', 'password' => 'require', diff --git a/core/extend/Wechat/Lib/Cache.php b/core/extend/Wechat/Lib/Cache.php index 43321bf6..69fac265 100644 --- a/core/extend/Wechat/Lib/Cache.php +++ b/core/extend/Wechat/Lib/Cache.php @@ -1,5 +1,18 @@ * @date 2016-08-20 17:50 */ -class Cache { +class Cache +{ /** * 缓存位置 @@ -25,7 +39,8 @@ class Cache { * @param int $expired * @return mixed */ - static public function set($name, $value, $expired = 0) { + static public function set($name, $value, $expired = 0) + { if (isset(Loader::$callback['CacheSet'])) { return call_user_func_array(Loader::$callback['CacheSet'], func_get_args()); } @@ -38,7 +53,8 @@ class Cache { * @param string $name * @return mixed */ - static public function get($name) { + static public function get($name) + { if (isset(Loader::$callback['CacheGet'])) { return call_user_func_array(Loader::$callback['CacheGet'], func_get_args()); } @@ -56,7 +72,8 @@ class Cache { * @param string $name * @return mixed */ - static public function del($name) { + static public function del($name) + { if (isset(Loader::$callback['CacheDel'])) { return call_user_func_array(Loader::$callback['CacheDel'], func_get_args()); } @@ -69,7 +86,8 @@ class Cache { * @param string $filename * @return mixed */ - static public function put($line, $filename = '') { + static public function put($line, $filename = '') + { if (isset(Loader::$callback['CachePut'])) { return call_user_func_array(Loader::$callback['CachePut'], func_get_args()); } @@ -81,13 +99,48 @@ class Cache { * 检查缓存目录 * @return bool */ - static protected function check() { + static protected function check() + { empty(self::$cachepath) && self::$cachepath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR; self::$cachepath = rtrim(self::$cachepath, '/\\') . DIRECTORY_SEPARATOR; - if (!is_dir(self::$cachepath) && !mkdir(self::$cachepath, 0755, TRUE)) { - return FALSE; + if (!is_dir(self::$cachepath) && !mkdir(self::$cachepath, 0755, true)) { + return false; } - return TRUE; + return true; + } + + /** + * 文件缓存,成功返回文件路径 + * @param string $content 文件内容 + * @param string $filename 文件名称 + * @return bool|string + */ + static public function file($content, $filename = '') + { + if (isset(Loader::$callback['CacheFile'])) { + return call_user_func_array(Loader::$callback['CacheFile'], func_get_args()); + } + empty($filename) && $filename = md5($content) . '.' . self::getFileExt($content); + if (self::check() && file_put_contents(self::$cachepath . $filename, $content)) { + return self::$cachepath . $filename; + } + return false; + } + + /** + * 根据文件流读取文件后缀 + * @param string $content + * @return string + */ + static public function getFileExt($content) + { + $types = [ + 255216 => 'jpg', 7173 => 'gif', 6677 => 'bmp', 13780 => 'png', + 7368 => 'mp3', 4838 => 'wma', 7784 => 'mid', 6063 => 'xml', + ]; + $typeInfo = @unpack("C2chars", substr($content, 0, 2)); + $typeCode = intval($typeInfo['chars1'] . $typeInfo['chars2']); + return isset($types[$typeCode]) ? $types[$typeCode] : 'mp4'; } } diff --git a/core/extend/Wechat/Lib/Common.php b/core/extend/Wechat/Lib/Common.php index d0af0d68..a8c503c8 100644 --- a/core/extend/Wechat/Lib/Common.php +++ b/core/extend/Wechat/Lib/Common.php @@ -1,5 +1,17 @@ * @date 2016/05/28 11:55 */ -class Common { +class Common +{ /** API接口URL需要使用此前缀 */ const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com'; @@ -31,13 +44,14 @@ class Common { public $errCode = 0; public $errMsg = ""; public $config = array(); - private $_retry = FALSE; + private $_retry = false; /** * 构造方法 * @param array $options */ - public function __construct($options = array()) { + public function __construct($options = array()) + { $config = Loader::config($options); $this->token = isset($config['token']) ? $config['token'] : ''; $this->appid = isset($config['appid']) ? $config['appid'] : ''; @@ -46,11 +60,49 @@ class Common { $this->config = $config; } + /** + * 当前当前错误代码 + * @return int + */ + public function getErrorCode() + { + return $this->errCode; + } + + /** + * 获取当前错误内容 + * @return string + */ + public function getError() + { + return $this->errMsg; + } + + /** + * 获取当前操作公众号APPID + * @return string + */ + public function getAppid() + { + return $this->appid; + } + + /** + * 获取SDK配置参数 + * @return array + */ + public function getConfig() + { + return $this->config; + } + + /** * 接口验证 * @return bool */ - public function valid() { + public function valid() + { $encryptStr = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { $postStr = file_get_contents("php://input"); @@ -58,7 +110,7 @@ class Common { $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"] : ''; if ($this->encrypt_type == 'aes') { $encryptStr = $array['Encrypt']; - !class_exists('Prpcrypt', FALSE) && require __DIR__ . '/Prpcrypt.php'; + !class_exists('Prpcrypt', false) && require __DIR__ . '/Prpcrypt.php'; $pc = new Prpcrypt($this->encodingAesKey); $array = $pc->decrypt($encryptStr, $this->appid); if (!isset($array[0]) || intval($array[0]) > 0) { @@ -75,9 +127,8 @@ class Common { } elseif (isset($_GET["echostr"])) { if ($this->checkSignature()) { exit($_GET["echostr"]); - } else { - return false; } + return false; } if (!$this->checkSignature($encryptStr)) { $this->errMsg = 'Interface authentication failed, please use the correct method to call.'; @@ -91,8 +142,8 @@ class Common { * @param string $str * @return bool */ - private function checkSignature($str = '') { - // 如果存在加密验证则用加密验证段 + private function checkSignature($str = '') + { $signature = isset($_GET["msg_signature"]) ? $_GET["msg_signature"] : (isset($_GET["signature"]) ? $_GET["signature"] : ''); $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : ''; $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : ''; @@ -100,9 +151,8 @@ class Common { sort($tmpArr, SORT_STRING); if (sha1(implode($tmpArr)) == $signature) { return true; - } else { - return false; } + return false; } /** @@ -112,7 +162,8 @@ class Common { * @param string $token 手动指定access_token,非必要情况不建议用 * @return bool|string */ - public function getAccessToken($appid = '', $appsecret = '', $token = '') { + public function getAccessToken($appid = '', $appsecret = '', $token = '') + { if (!$appid || !$appsecret) { $appid = $this->appid; $appsecret = $this->appsecret; @@ -151,7 +202,8 @@ class Common { * @param array $arguments SDK方法参数 * @return bool|mixed */ - protected function checkRetry($method, $arguments = array()) { + protected function checkRetry($method, $arguments = array()) + { if (!$this->_retry && in_array($this->errCode, array('40014', '40001', '41001', '42001'))) { Tools::log("Run {$method} Faild. {$this->errMsg}[{$this->errCode}]", 'ERR'); ($this->_retry = true) && $this->resetAuth(); @@ -168,7 +220,8 @@ class Common { * @param string $appid 如在类初始化时已提供,则可为空 * @return bool */ - public function resetAuth($appid = '') { + public function resetAuth($appid = '') + { $authname = 'wechat_access_token_' . (empty($appid) ? $this->appid : $appid); Tools::log("Reset Auth And Remove Old AccessToken."); $this->access_token = ''; diff --git a/core/extend/Wechat/Lib/Prpcrypt.php b/core/extend/Wechat/Lib/Prpcrypt.php index 07404620..5830ea43 100644 --- a/core/extend/Wechat/Lib/Prpcrypt.php +++ b/core/extend/Wechat/Lib/Prpcrypt.php @@ -1,12 +1,25 @@ PKCS7Encoder::$block_size) { $pad = 0; @@ -49,11 +64,13 @@ class PKCS7Encoder { * @subpackage library * @date 2016/06/28 11:59 */ -class Prpcrypt { +class Prpcrypt +{ public $key; - function __construct($k) { + function __construct($k) + { $this->key = base64_decode($k . "="); } @@ -61,9 +78,10 @@ class Prpcrypt { * 对明文进行加密 * @param string $text 需要加密的明文 * @param string $appid 公众号APPID - * @return string 加密后的密文 + * @return array */ - public function encrypt($text, $appid) { + public function encrypt($text, $appid) + { try { //获得16位随机字符串,填充到明文之前 $random = $this->getRandomStr();//"aaaabbbbccccdddd"; @@ -82,9 +100,10 @@ class Prpcrypt { * 对密文进行解密 * @param string $encrypted 需要解密的密文 * @param string $appid 公众号APPID - * @return string 解密得到的明文 + * @return array */ - public function decrypt($encrypted, $appid) { + public function decrypt($encrypted, $appid) + { try { $iv = substr($this->key, 0, 16); $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv); @@ -95,27 +114,26 @@ class Prpcrypt { $pkc_encoder = new PKCS7Encoder; $result = $pkc_encoder->decode($decrypted); if (strlen($result) < 16) { - return ""; + return array(ErrorCode::$DecryptAESError, null); } $content = substr($result, 16, strlen($result)); $len_list = unpack("N", substr($content, 0, 4)); $xml_len = $len_list[1]; $xml_content = substr($content, 4, $xml_len); $from_appid = substr($content, $xml_len + 4); - if (!$appid) { - $appid = $from_appid; - } + return array(0, $xml_content, $from_appid); } catch (Exception $e) { return array(ErrorCode::$IllegalBuffer, null); } - return array(0, $xml_content, $from_appid); + } /** * 随机生成16位字符串 * @return string 生成的字符串 */ - function getRandomStr() { + function getRandomStr() + { $str = ""; $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($str_pol) - 1; @@ -132,7 +150,8 @@ class Prpcrypt { * 不用于官方API接口的errCode码 * Class ErrorCode */ -class ErrorCode { +class ErrorCode +{ public static $OK = 0; public static $ValidateSignatureError = 40001; @@ -166,7 +185,8 @@ class ErrorCode { * @param string $err * @return bool */ - public static function getErrText($err) { + public static function getErrText($err) + { if (isset(self::$errCode[$err])) { return self::$errCode[$err]; } diff --git a/core/extend/Wechat/Lib/Tools.php b/core/extend/Wechat/Lib/Tools.php index d87d84ed..64dc87b2 100644 --- a/core/extend/Wechat/Lib/Tools.php +++ b/core/extend/Wechat/Lib/Tools.php @@ -1,5 +1,17 @@ * @date 2016/05/28 11:55 */ -class Tools { +class Tools +{ /** * 产生随机字符串 @@ -20,7 +33,8 @@ class Tools { * @param string $str * @return string */ - static public function createNoncestr($length = 32, $str = "") { + static public function createNoncestr($length = 32, $str = "") + { $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); @@ -34,7 +48,8 @@ class Tools { * @param string $method 签名方法 * @return bool|string 签名值 */ - static public function getSignature($arrdata, $method = "sha1") { + static public function getSignature($arrdata, $method = "sha1") + { if (!function_exists($method)) { return false; } @@ -52,7 +67,8 @@ class Tools { * @param string $partnerKey * @return string */ - static public function getPaySign($option, $partnerKey) { + static public function getPaySign($option, $partnerKey) + { ksort($option); $buff = ''; foreach ($option as $k => $v) { @@ -69,11 +85,21 @@ class Tools { * @param string $id 数字索引子节点key转换的属性名 * @return string */ - static public function arr2xml($data, $root = 'xml', $item = 'item', $id = 'id') { + static public function arr2xml($data, $root = 'xml', $item = 'item', $id = 'id') + { return "<{$root}>" . self::_data_to_xml($data, $item, $id) . ""; } - static private function _data_to_xml($data, $item = 'item', $id = 'id', $content = '') { + /** + * XML内容生成 + * @param array $data 数据 + * @param string $item 子节点 + * @param string $id 节点ID + * @param string $content 节点内容 + * @return string + */ + static private function _data_to_xml($data, $item = 'item', $id = 'id', $content = '') + { foreach ($data as $key => $val) { is_numeric($key) && $key = "{$item} {$id}=\"{$key}\""; $content .= "<{$key}>"; @@ -96,7 +122,8 @@ class Tools { * @param string $xml * @return array */ - static public function xml2arr($xml) { + static public function xml2arr($xml) + { return json_decode(Tools::json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); } @@ -105,7 +132,8 @@ class Tools { * @param array $array * @return string */ - static public function json_encode($array) { + static public function json_encode($array) + { return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'), json_encode($array)); } @@ -114,11 +142,12 @@ class Tools { * @param $url * @return bool|mixed */ - static public function httpGet($url) { + static public function httpGet($url) + { $oCurl = curl_init(); - if (stripos($url, "https://") !== FALSE) { - curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); + if (stripos($url, "https://") !== false) { + curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); } curl_setopt($oCurl, CURLOPT_URL, $url); @@ -128,9 +157,8 @@ class Tools { curl_close($oCurl); if (intval($aStatus["http_code"]) == 200) { return $sContent; - } else { - return false; } + return false; } /** @@ -139,17 +167,18 @@ class Tools { * @param array|string $data * @return bool|mixed */ - static public function httpPost($url, $data) { + static public function httpPost($url, $data) + { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); - curl_setopt($ch, CURLOPT_HEADER, FALSE); - curl_setopt($ch, CURLOPT_POST, TRUE); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_POST, true); if (is_array($data)) { foreach ($data as &$value) { - if (is_string($value) && stripos($value, '@') === 0 && class_exists('CURLFile', FALSE)) { + if (is_string($value) && stripos($value, '@') === 0 && class_exists('CURLFile', false)) { $value = new CURLFile(realpath(trim($value, '@'))); } } @@ -172,16 +201,15 @@ class Tools { * @param int $second 设置请求超时时间 * @return bool|mixed */ - static public function httpsPost($url, $postdata, $ssl_cer = null, $ssl_key = null, $second = 30) { + static public function httpsPost($url, $postdata, $ssl_cer = null, $ssl_key = null, $second = 30) + { $ch = curl_init(); curl_setopt($ch, CURLOPT_TIMEOUT, $second); curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); - curl_setopt($ch, CURLOPT_HEADER, FALSE); - /* 要求结果为字符串且输出到屏幕上 */ - curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); - /* 设置证书 */ + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (!is_null($ssl_cer) && file_exists($ssl_cer) && is_file($ssl_cer)) { curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM'); curl_setopt($ch, CURLOPT_SSLCERT, $ssl_cer); @@ -193,7 +221,7 @@ class Tools { curl_setopt($ch, CURLOPT_POST, true); if (is_array($postdata)) { foreach ($postdata as &$data) { - if (is_string($data) && stripos($data, '@') === 0 && class_exists('CURLFile', FALSE)) { + if (is_string($data) && stripos($data, '@') === 0 && class_exists('CURLFile', false)) { $data = new CURLFile(realpath(trim($data, '@'))); } } @@ -203,23 +231,23 @@ class Tools { curl_close($ch); if ($result) { return $result; - } else { - return false; } + return false; } /** * 读取微信客户端IP * @return null|string */ - static public function getAddress() { + static public function getAddress() + { foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP', 'REMOTE_ADDR') as $header) { - if (!isset($_SERVER[$header]) || ($spoof = $_SERVER[$header]) === NULL) { + if (!isset($_SERVER[$header]) || ($spoof = $_SERVER[$header]) === null) { continue; } sscanf($spoof, '%[^,]', $spoof); if (!filter_var($spoof, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - $spoof = NULL; + $spoof = null; } else { return $spoof; } @@ -234,7 +262,8 @@ class Tools { * @param int $expired * @return bool */ - static public function setCache($cachename, $value, $expired = 0) { + static public function setCache($cachename, $value, $expired = 0) + { return Cache::set($cachename, $value, $expired); } @@ -243,7 +272,8 @@ class Tools { * @param string $cachename * @return mixed */ - static public function getCache($cachename) { + static public function getCache($cachename) + { return Cache::get($cachename); } @@ -252,7 +282,8 @@ class Tools { * @param string $cachename * @return bool */ - static public function removeCache($cachename) { + static public function removeCache($cachename) + { return Cache::del($cachename); } @@ -261,7 +292,8 @@ class Tools { * @param string $msg 日志行内容 * @param string $type 日志级别 */ - static public function log($msg, $type = 'MSG') { + static public function log($msg, $type = 'MSG') + { Cache::put($type . ' - ' . $msg); } diff --git a/core/extend/Wechat/Loader.php b/core/extend/Wechat/Loader.php index 475193e0..ff396b04 100644 --- a/core/extend/Wechat/Loader.php +++ b/core/extend/Wechat/Loader.php @@ -1,5 +1,18 @@ * @date 2016-08-21 11:06 */ -class Loader { +class Loader +{ /** * 事件注册函数 @@ -47,8 +61,9 @@ class Loader { * @param string $method 处理方法(可以是普通方法或者类中的方法) * @param string|null $class 处理对象(可以直接使用的类实例) */ - static public function register($event, $method, $class = NULL) { - if (!empty($class) && class_exists($class, FALSE) && method_exists($class, $method)) { + static public function register($event, $method, $class = null) + { + if (!empty($class) && class_exists($class, false) && method_exists($class, $method)) { self::$callback[$event] = array($class, $method); } else { self::$callback[$event] = $method; @@ -61,7 +76,8 @@ class Loader { * @param array $config SDK配置(token,appid,appsecret,encodingaeskey,mch_id,partnerkey,ssl_cer,ssl_key,qrc_img) * @return WechatCard|WechatCustom|WechatDevice|WechatExtends|WechatMedia|WechatMenu|WechatOauth|WechatPay|WechatPoi|WechatReceive|WechatScript|WechatService|WechatUser */ - static public function & get_instance($type, $config = array()) { + static public function & get_instance($type, $config = array()) + { return self::get($type, $config); } @@ -71,13 +87,14 @@ class Loader { * @param array $config SDK配置(token,appid,appsecret,encodingaeskey,mch_id,partnerkey,ssl_cer,ssl_key,qrc_img) * @return WechatCard|WechatCustom|WechatDevice|WechatExtends|WechatMedia|WechatMenu|WechatOauth|WechatPay|WechatPoi|WechatReceive|WechatScript|WechatService|WechatUser */ - static public function & get($type, $config = array()) { + static public function & get($type, $config = array()) + { $index = md5(strtolower($type) . md5(json_encode(self::$config))); if (!isset(self::$cache[$index])) { $basicName = 'Wechat' . ucfirst(strtolower($type)); $className = "\\Wechat\\{$basicName}"; // 注册类的无命名空间别名,兼容未带命名空间的老版本SDK - !class_exists($basicName, FALSE) && class_alias($className, $basicName); + !class_exists($basicName, false) && class_alias($className, $basicName); self::$cache[$index] = new $className(self::config($config)); } return self::$cache[$index]; @@ -88,7 +105,8 @@ class Loader { * @param array $config * @return array */ - static public function config($config = array()) { + static public function config($config = array()) + { !empty($config) && self::$config = array_merge(self::$config, $config); if (!empty(self::$config['cachepath'])) { Cache::$cachepath = self::$config['cachepath']; diff --git a/core/extend/Wechat/WechatCard.php b/core/extend/Wechat/WechatCard.php index 5fb258f9..dfcae81f 100644 --- a/core/extend/Wechat/WechatCard.php +++ b/core/extend/Wechat/WechatCard.php @@ -1,5 +1,17 @@ access_token && !$this->getAccessToken()) { return false; } @@ -87,7 +101,8 @@ class WechatCard extends Common { * @param string $shopid 门店Id * @return array */ - public function createChooseCardJsPackage($cardid = NULL, $cardtype = NULL, $shopid = NULL) { + public function createChooseCardJsPackage($cardid = null, $cardtype = null, $shopid = null) + { $data = array(); $data['api_ticket'] = $this->getJsCardTicket(); $data['app_id'] = $this->appid; @@ -108,9 +123,11 @@ class WechatCard extends Common { * @param array $data 其它限定参数 * @return array */ - public function createAddCardJsPackage($cardid = NULL, $data = array()) { + public function createAddCardJsPackage($cardid = null, $data = array()) + { - function _sign($cardid = NULL, $attr = array(), $self) { + function _sign($cardid = null, $attr = array(), $self) + { unset($attr['outer_id']); $attr['cardId'] = $cardid; $attr['timestamp'] = time(); @@ -138,7 +155,8 @@ class WechatCard extends Common { * @param string $method 签名方法 * @return bool|string 签名值 */ - public function getTicketSignature($arrdata, $method = "sha1") { + public function getTicketSignature($arrdata, $method = "sha1") + { if (!function_exists($method)) { return false; } @@ -155,7 +173,8 @@ class WechatCard extends Common { * @param array $data 卡券数据 * @return bool|array 返回数组中card_id为卡券ID */ - public function createCard($data) { + public function createCard($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -178,7 +197,8 @@ class WechatCard extends Common { * @param string $data * @return bool */ - public function updateCard($data) { + public function updateCard($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -202,7 +222,8 @@ class WechatCard extends Common { * @param string $card_id 卡券ID * @return bool */ - public function delCard($card_id) { + public function delCard($card_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -226,7 +247,8 @@ class WechatCard extends Common { * @param string $card_id 卡卷ID(可不给) * @return bool|array */ - public function getCardList($openid, $card_id = '') { + public function getCardList($openid, $card_id = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -250,7 +272,8 @@ class WechatCard extends Common { * @param string $card_id 卡卷ID * @return bool|array */ - public function getCardMpHtml($card_id) { + public function getCardMpHtml($card_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -275,7 +298,8 @@ class WechatCard extends Common { * @param array $code_list 卡卷code列表(一维数组) * @return bool|array */ - public function checkCardCodeList($card_id, $code_list) { + public function checkCardCodeList($card_id, $code_list) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -298,7 +322,8 @@ class WechatCard extends Common { * @param string $card_id 卡卷ID * @return bool|array */ - public function getCardInfo($card_id) { + public function getCardInfo($card_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -321,7 +346,8 @@ class WechatCard extends Common { * 获得卡券的最新颜色列表,用于创建卡券 * @return bool|array */ - public function getCardColors() { + public function getCardColors() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -349,7 +375,8 @@ class WechatCard extends Common { * @param string $balance 红包余额,以分为单位。红包类型必填(LUCKY_MONEY),其他卡券类型不填。 * @return bool|string */ - public function createCardQrcode($card_id, $code = '', $openid = '', $expire_seconds = 0, $is_unique_code = false, $balance = '') { + public function createCardQrcode($card_id, $code = '', $openid = '', $expire_seconds = 0, $is_unique_code = false, $balance = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -387,7 +414,8 @@ class WechatCard extends Common { * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA" * } */ - public function consumeCardCode($code, $card_id = '') { + public function consumeCardCode($code, $card_id = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -416,7 +444,8 @@ class WechatCard extends Common { * "code":"751234212312" * } */ - public function decryptCardCode($encrypt_code) { + public function decryptCardCode($encrypt_code) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -449,7 +478,8 @@ class WechatCard extends Common { * } * } */ - public function checkCardCode($code) { + public function checkCardCode($code) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -479,7 +509,8 @@ class WechatCard extends Common { * "total_num":1 //该商户名下 card_id 总数 * } */ - public function getCardIdList($offset = 0, $count = 50) { + public function getCardIdList($offset = 0, $count = 50) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -507,7 +538,8 @@ class WechatCard extends Common { * @param string $new_code 新的卡券 code 编码 * @return bool */ - public function updateCardCode($code, $card_id, $new_code) { + public function updateCardCode($code, $card_id, $new_code) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -532,7 +564,8 @@ class WechatCard extends Common { * @param string $card_id 自定义 code 的卡券必填。非自定义 code 的卡券不填。 * @return bool */ - public function unavailableCardCode($code, $card_id = '') { + public function unavailableCardCode($code, $card_id = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -556,7 +589,8 @@ class WechatCard extends Common { * @param string $data * @return bool */ - public function modifyCardStock($data) { + public function modifyCardStock($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -578,7 +612,8 @@ class WechatCard extends Common { * @param string $data * @return bool */ - public function updateMeetingCard($data) { + public function updateMeetingCard($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -600,7 +635,8 @@ class WechatCard extends Common { * @param string $data 具体结构请参看卡券开发文档(6.1.1 激活/绑定会员卡)章节 * @return bool */ - public function activateMemberCard($data) { + public function activateMemberCard($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -623,7 +659,8 @@ class WechatCard extends Common { * @param string $data 具体结构请参看卡券开发文档(6.1.2 会员卡交易)章节 * @return bool|array */ - public function updateMemberCard($data) { + public function updateMemberCard($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -646,7 +683,8 @@ class WechatCard extends Common { * @param array $user 测试的微信号列表 * @return bool */ - public function setCardTestWhiteList($openid = array(), $user = array()) { + public function setCardTestWhiteList($openid = array(), $user = array()) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -673,7 +711,8 @@ class WechatCard extends Common { * @param string $card_id 自定义 code 的卡券必填。非自定义 code 可不填。 * @return bool|array */ - public function updateLuckyMoney($code, $balance, $card_id = '') { + public function updateLuckyMoney($code, $balance, $card_id = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -701,7 +740,8 @@ class WechatCard extends Common { * @param bool $need_remark_amount 用户核销时是否需要备注核销金额,填true/false,默认为false * @return bool|array */ - public function setSelfconsumecell($card_id, $is_openid = false, $need_verify_cod = false, $need_remark_amount = false) { + public function setSelfconsumecell($card_id, $is_openid = false, $need_verify_cod = false, $need_remark_amount = false) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -730,14 +770,12 @@ class WechatCard extends Common { * @param bool $is_openid * @return bool|mixed */ - public function setPaycell($card_id, $is_openid = true) { + public function setPaycell($card_id, $is_openid = true) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - $data = array( - 'card_id' => $card_id, - 'is_open' => $is_openid, - ); + $data = array('card_id' => $card_id, 'is_open' => $is_openid,); $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::CARD_PAYCELL_SET . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); @@ -756,7 +794,8 @@ class WechatCard extends Common { * @param array $data * @return bool|array */ - public function setMembercardActivateuserform($data) { + public function setMembercardActivateuserform($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } diff --git a/core/extend/Wechat/WechatCustom.php b/core/extend/Wechat/WechatCustom.php index 00482718..fc88803e 100644 --- a/core/extend/Wechat/WechatCustom.php +++ b/core/extend/Wechat/WechatCustom.php @@ -1,11 +1,24 @@ access_token && !$this->getAccessToken()) { return false; } @@ -49,7 +63,8 @@ class WechatCustom extends Common { * * @return bool|array */ - public function getCustomServiceKFlist() { + public function getCustomServiceKFlist() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -71,7 +86,8 @@ class WechatCustom extends Common { * * @return bool|array */ - public function getCustomServiceOnlineKFlist() { + public function getCustomServiceOnlineKFlist() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -96,14 +112,13 @@ class WechatCustom extends Common { * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空 * @return bool|array */ - public function createKFSession($openid, $kf_account, $text = '') { - $data = array("openid" => $openid, "kf_account" => $kf_account); - if ($text) { - $data["text"] = $text; - } + public function createKFSession($openid, $kf_account, $text = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } + $data = array("openid" => $openid, "kf_account" => $kf_account); + $text !== '' && $data["text"] = $text; $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::CUSTOM_SESSION_CREATE . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); @@ -129,7 +144,8 @@ class WechatCustom extends Common { * "errmsg": "ok", * } */ - public function closeKFSession($openid, $kf_account, $text = '') { + public function closeKFSession($openid, $kf_account, $text = '') + { $data = array("openid" => $openid, "kf_account" => $kf_account); if ($text) { $data["text"] = $text; @@ -161,7 +177,8 @@ class WechatCustom extends Common { * "createtime": 123456789, //会话接入时间 * } */ - public function getKFSession($openid) { + public function getKFSession($openid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -195,7 +212,8 @@ class WechatCustom extends Common { * ) * ) */ - public function getKFSessionlist($kf_account) { + public function getKFSessionlist($kf_account) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -216,7 +234,8 @@ class WechatCustom extends Common { * 获取未接入会话列表 * @return bool|array */ - public function getKFSessionWait() { + public function getKFSessionWait() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -241,7 +260,8 @@ class WechatCustom extends Common { * @param string $password 客服账号明文登录密码,会自动加密 * @return bool|array */ - public function addKFAccount($account, $nickname, $password) { + public function addKFAccount($account, $nickname, $password) + { $data = array("kf_account" => $account, "nickname" => $nickname, "password" => md5($password)); if (!$this->access_token && !$this->getAccessToken()) { return false; @@ -272,7 +292,8 @@ class WechatCustom extends Common { * "errmsg": "ok", * } */ - public function updateKFAccount($account, $nickname, $password) { + public function updateKFAccount($account, $nickname, $password) + { $data = array("kf_account" => $account, "nickname" => $nickname, "password" => md5($password)); if (!$this->access_token && !$this->getAccessToken()) { return false; @@ -295,7 +316,8 @@ class WechatCustom extends Common { * @param string $account 完整客服账号(账号前缀@公众号微信号,账号前缀最多10个字符) * @return bool|array */ - public function deleteKFAccount($account) { + public function deleteKFAccount($account) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -318,11 +340,12 @@ class WechatCustom extends Common { * @param string $imgfile 头像文件完整路径,如:'D:\user.jpg'。头像文件必须JPG格式,像素建议640*640 * @return bool|array */ - public function setKFHeadImg($account, $imgfile) { + public function setKFHeadImg($account, $imgfile) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL . "access_token={$this->access_token}" . '&kf_account=' . $account, array('media' => '@' . $imgfile), true); + $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL . "access_token={$this->access_token}&kf_account={$account}", array('media' => '@' . $imgfile)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { diff --git a/core/extend/Wechat/WechatDevice.php b/core/extend/Wechat/WechatDevice.php index 8126f94f..d1cae9d3 100644 --- a/core/extend/Wechat/WechatDevice.php +++ b/core/extend/Wechat/WechatDevice.php @@ -1,5 +1,17 @@ * @date 2016-08-22 10:35 */ -class WechatDevice extends Common { +class WechatDevice extends Common +{ const SHAKEAROUND_DEVICE_APPLYID = '/shakearound/device/applyid?'; //申请设备ID const SHAKEAROUND_DEVICE_APPLYSTATUS = '/shakearound/device/applystatus?'; //查询设备ID申请审核状态 @@ -33,7 +46,8 @@ class WechatDevice extends Common { * @param array $data * @return bool|array */ - public function applyShakeAroundDevice($data) { + public function applyShakeAroundDevice($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -55,7 +69,8 @@ class WechatDevice extends Common { * @param int $apply_id * @return bool|array */ - public function applyStatusShakeAroundDevice($apply_id) { + public function applyStatusShakeAroundDevice($apply_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -78,7 +93,8 @@ class WechatDevice extends Common { * @param array $data * @return bool */ - public function updateShakeAroundDevice($data) { + public function updateShakeAroundDevice($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -101,7 +117,8 @@ class WechatDevice extends Common { * @param $data * @return bool|array */ - public function searchShakeAroundDevice($data) { + public function searchShakeAroundDevice($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -127,7 +144,8 @@ class WechatDevice extends Common { * @param int $minor * @return bool|array */ - public function bindLocationShakeAroundDevice($device_id, $poi_id, $uuid = '', $major = 0, $minor = 0) { + public function bindLocationShakeAroundDevice($device_id, $poi_id, $uuid = '', $major = 0, $minor = 0) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -137,9 +155,7 @@ class WechatDevice extends Common { } $device_identifier = array('uuid' => $uuid, 'major' => $major, 'minor' => $minor); } else { - $device_identifier = array( - 'device_id' => $device_id - ); + $device_identifier = array('device_id' => $device_id); } $data = array('device_identifier' => $device_identifier, 'poi_id' => $poi_id); $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDLOCATION . "access_token={$this->access_token}", Tools::json_encode($data)); @@ -162,7 +178,8 @@ class WechatDevice extends Common { * @param type $poi_appid 目标微信appid * @return boolean */ - public function bindLocationOtherShakeAroundDevice($device_identifier, $poi_id, $poi_appid) { + public function bindLocationOtherShakeAroundDevice($device_identifier, $poi_id, $poi_appid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -175,7 +192,7 @@ class WechatDevice extends Common { $this->errMsg = $json['errmsg']; return $this->checkRetry(__FUNCTION__, func_get_args()); } - return $json; //这个可以更改为返回true + return $json; } return false; } @@ -191,7 +208,8 @@ class WechatDevice extends Common { * @param int $minor * @return bool|array */ - public function bindPageShakeAroundDevice($device_id, $page_ids = array(), $bind = 1, $append = 1, $uuid = '', $major = 0, $minor = 0) { + public function bindPageShakeAroundDevice($device_id, $page_ids = array(), $bind = 1, $append = 1, $uuid = '', $major = 0, $minor = 0) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -223,11 +241,12 @@ class WechatDevice extends Common { * @param array $data {"media":'@Path\filename.jpg'} * @return bool|array */ - public function uploadShakeAroundMedia($data) { + public function uploadShakeAroundMedia($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_MATERIAL_ADD . "access_token={$this->access_token}", $data, true); + $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_MATERIAL_ADD . "access_token={$this->access_token}", $data); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { @@ -250,7 +269,8 @@ class WechatDevice extends Common { * @param string $comment 页面的备注信息,不超过15 个字,可不填 * @return bool|array */ - public function addShakeAroundPage($title, $description, $icon_url, $page_url, $comment = '') { + public function addShakeAroundPage($title, $description, $icon_url, $page_url, $comment = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -279,7 +299,8 @@ class WechatDevice extends Common { * @param string $comment 页面的备注信息,不超过15 个字,可不填 * @return bool|array */ - public function updateShakeAroundPage($page_id, $title, $description, $icon_url, $page_url, $comment = '') { + public function updateShakeAroundPage($page_id, $title, $description, $icon_url, $page_url, $comment = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -305,7 +326,8 @@ class WechatDevice extends Common { * @param int $count * @return bool|mixed */ - public function searchShakeAroundPage($page_ids = array(), $begin = 0, $count = 1) { + public function searchShakeAroundPage($page_ids = array(), $begin = 0, $count = 1) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -333,7 +355,8 @@ class WechatDevice extends Common { * @param array $page_ids * @return bool|array */ - public function deleteShakeAroundPage($page_ids = array()) { + public function deleteShakeAroundPage($page_ids = array()) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -357,7 +380,8 @@ class WechatDevice extends Common { * @param string $ticket 摇周边业务的ticket(可在摇到的URL中得到,ticket生效时间为30 分钟) * @return bool|array */ - public function getShakeInfoShakeAroundUser($ticket) { + public function getShakeInfoShakeAroundUser($ticket) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -386,7 +410,8 @@ class WechatDevice extends Common { * @param int $minor * @return bool|array */ - public function deviceShakeAroundStatistics($device_id, $begin_date, $end_date, $uuid = '', $major = 0, $minor = 0) { + public function deviceShakeAroundStatistics($device_id, $begin_date, $end_date, $uuid = '', $major = 0, $minor = 0) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -420,7 +445,8 @@ class WechatDevice extends Common { * @param int $end_date 结束日期时间戳,最长时间跨度为30 天 * @return bool|array */ - public function pageShakeAroundStatistics($page_id, $begin_date, $end_date) { + public function pageShakeAroundStatistics($page_id, $begin_date, $end_date) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } diff --git a/core/extend/Wechat/WechatExtends.php b/core/extend/Wechat/WechatExtends.php index 6a8e6ca8..cd1c5529 100644 --- a/core/extend/Wechat/WechatExtends.php +++ b/core/extend/Wechat/WechatExtends.php @@ -1,5 +1,17 @@ * @date 2016-08-22 10:32 */ -class WechatExtends extends Common { +class WechatExtends extends Common +{ const QR_LIMIT_SCENE = 1; @@ -56,7 +69,8 @@ class WechatExtends extends Common { * @param string $ticket 传入由getQRCode方法生成的ticket参数 * @return string url 返回http地址 */ - public function getQRUrl($ticket) { + public function getQRUrl($ticket) + { return self::QRCODE_IMG_URL . urlencode($ticket); } @@ -65,14 +79,12 @@ class WechatExtends extends Common { * @param string $long_url 传入要转换的长url * @return bool|string url 成功则返回转换后的短url */ - public function getShortUrl($long_url) { + public function getShortUrl($long_url) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - $data = array( - 'action' => 'long2short', - 'long_url' => $long_url - ); + $data = array('action' => 'long2short', 'long_url' => $long_url); $result = Tools::httpPost(self::API_URL_PREFIX . self::SHORT_URL . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); @@ -93,7 +105,8 @@ class WechatExtends extends Common { * @param int $expire 临时二维码有效期,最大为2592000秒(30天) * @return bool|array ('ticket'=>'qrcode字串','expire_seconds'=>2592000,'url'=>'二维码图片解析后的地址') */ - public function getQRCode($scene_id, $type = 0, $expire = 2592000) { + public function getQRCode($scene_id, $type = 0, $expire = 2592000) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -130,7 +143,8 @@ class WechatExtends extends Common { * @param string $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入 * @return bool|array */ - public function querySemantic($uid, $query, $category, $latitude = 0.00, $longitude = 0.00, $city = "", $region = "") { + public function querySemantic($uid, $query, $category, $latitude = 0.00, $longitude = 0.00, $city = "", $region = "") + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -170,17 +184,15 @@ class WechatExtends extends Common { * @param string $end_date 结束时间 * @return bool|array 成功返回查询结果数组,其定义请看官方文档 */ - public function getDatacube($type, $subtype, $begin_date, $end_date = '') { + public function getDatacube($type, $subtype, $begin_date, $end_date = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } if (!isset(self::$DATACUBE_URL_ARR[$type]) || !isset(self::$DATACUBE_URL_ARR[$type][$subtype])) { return false; } - $data = array( - 'begin_date' => $begin_date, - 'end_date' => $end_date ? $end_date : $begin_date - ); + $data = array('begin_date' => $begin_date, 'end_date' => $end_date ? $end_date : $begin_date); $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::$DATACUBE_URL_ARR[$type][$subtype] . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); diff --git a/core/extend/Wechat/WechatHardware.php b/core/extend/Wechat/WechatHardware.php index 9ac4339c..f4a110a9 100644 --- a/core/extend/Wechat/WechatHardware.php +++ b/core/extend/Wechat/WechatHardware.php @@ -1,11 +1,24 @@ access_token && !$this->getAccessToken()) { return false; } @@ -37,7 +51,8 @@ class WechatHardware extends Common { } - public function transmsg($data) { + public function transmsg($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -55,7 +70,8 @@ class WechatHardware extends Common { return false; } - public function getQrcode($product_id) { + public function getQrcode($product_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -77,7 +93,8 @@ class WechatHardware extends Common { * @param $data * @return bool|mixed */ - public function deviceAuthorize($data) { + public function deviceAuthorize($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -99,7 +116,8 @@ class WechatHardware extends Common { * @param $data * @return bool|mixed */ - public function getDeviceQrcode($data) { + public function getDeviceQrcode($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -122,7 +140,8 @@ class WechatHardware extends Common { * @param $device_id * @return bool|mixed */ - public function getDeviceStat($device_id) { + public function getDeviceStat($device_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } diff --git a/core/extend/Wechat/WechatMedia.php b/core/extend/Wechat/WechatMedia.php index 3fff1663..87e8064d 100644 --- a/core/extend/Wechat/WechatMedia.php +++ b/core/extend/Wechat/WechatMedia.php @@ -1,7 +1,20 @@ * @date 2016/10/26 14:47 */ -class WechatMedia extends Common { +class WechatMedia extends Common +{ const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin'; const MEDIA_UPLOAD_URL = '/media/upload?'; @@ -36,12 +50,17 @@ class WechatMedia extends Common { * @param string $type 类型:图片:image 语音:voice 视频:video 缩略图:thumb * @return bool|array */ - public function uploadMedia($data, $type) { + public function uploadMedia($data, $type) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀 - $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_UPLOAD_URL . "access_token={$this->access_token}" . '&type=' . $type, $data, true); + list($cache_file, $media_content) = ['', base64_decode($data['media'])]; + if (!empty($media_content) && ($cache_file = Cache::file($media_content))) { + $data['media'] = "@{$cache_file}"; + } + $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_UPLOAD_URL . "access_token={$this->access_token}&type={$type}", $data); + !empty($cache_file) && @unlink($cache_file); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { @@ -60,7 +79,8 @@ class WechatMedia extends Common { * @param bool $is_video 是否为视频文件,默认为否 * @return bool|array */ - public function getMedia($media_id, $is_video = false) { + public function getMedia($media_id, $is_video = false) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -88,7 +108,8 @@ class WechatMedia extends Common { * @param bool $is_video 是否为视频文件,默认为否 * @return bool|array */ - public function getMediaWithHttpInfo($media_id, $is_video = false) { + public function getMediaWithHttpInfo($media_id, $is_video = false) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -97,9 +118,9 @@ class WechatMedia extends Common { $url_prefix = $is_video ? str_replace('https', 'http', self::API_URL_PREFIX) : self::API_URL_PREFIX; $url = $url_prefix . self::MEDIA_GET_URL . "access_token={$this->access_token}" . '&media_id=' . $media_id; $oCurl = curl_init(); - if (stripos($url, "https://") !== FALSE) { - curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); + if (stripos($url, "https://") !== false) { + curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); } curl_setopt($oCurl, CURLOPT_URL, $url); @@ -136,12 +157,17 @@ class WechatMedia extends Common { * @param array $data {"media":'@Path\filename.jpg'} * @return bool|array */ - public function uploadImg($data) { + public function uploadImg($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - /* 原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀 */ - $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_UPLOADIMG_URL . "access_token={$this->access_token}", $data, true); + list($cache_file, $media_content) = ['', base64_decode($data['media'])]; + if (!empty($media_content) && ($cache_file = Cache::file($media_content))) { + $data['media'] = "@{$cache_file}"; + } + $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_UPLOADIMG_URL . "access_token={$this->access_token}", $data); + !empty($cache_file) && @unlink($cache_file); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { @@ -159,20 +185,24 @@ class WechatMedia extends Common { * 新增的永久素材也可以在公众平台官网素材管理模块中看到 * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时 * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义 - * @param array $data {"media":'@Path\filename.jpg'} + * @param array $data {"media":'@Path\filename.jpg'}, 支持base64格式 * @param string $type 类型:图片:image 语音:voice 视频:video 缩略图:thumb * @param bool $is_video 是否为视频文件,默认为否 * @param array $video_info 视频信息数组,非视频素材不需要提供 array('title'=>'视频标题','introduction'=>'描述') * @return bool|array */ - public function uploadForeverMedia($data, $type, $is_video = false, $video_info = array()) { + public function uploadForeverMedia($data, $type, $is_video = false, $video_info = array()) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - if ($is_video) { - $data['description'] = Tools::json_encode($video_info); + $is_video && ($data['description'] = Tools::json_encode($video_info)); + list($cache_file, $media_content) = ['', base64_decode($data['media'])]; + if (!empty($media_content) && ($cache_file = Cache::file($media_content))) { + $data['media'] = "@{$cache_file}"; } - $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_FOREVER_UPLOAD_URL . "access_token={$this->access_token}" . '&type=' . $type, $data, true); + $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_FOREVER_UPLOAD_URL . "access_token={$this->access_token}&type={$type}", $data); + !empty($cache_file) && @unlink($cache_file); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { @@ -191,7 +221,8 @@ class WechatMedia extends Common { * @param array $data 消息结构{"articles":[{...}]} * @return bool|array */ - public function uploadForeverArticles($data) { + public function uploadForeverArticles($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -216,16 +247,13 @@ class WechatMedia extends Common { * @param int $index 更新的文章在图文素材的位置,第一篇为0,仅多图文使用 * @return bool|array */ - public function updateForeverArticles($media_id, $data, $index = 0) { + public function updateForeverArticles($media_id, $data, $index = 0) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - if (!isset($data['media_id'])) { - $data['media_id'] = $media_id; - } - if (!isset($data['index'])) { - $data['index'] = $index; - } + !isset($data['index']) && $data['index'] = $index; + !isset($data['media_id']) && $data['media_id'] = $media_id; $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_FOREVER_NEWS_UPDATE_URL . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); @@ -244,16 +272,14 @@ class WechatMedia extends Common { * 返回图文消息数组或二进制数据,失败返回false * @param string $media_id 媒体文件id * @param bool $is_video 是否为视频文件,默认为否 - * @return bool|array|raw data + * @return bool|array */ - public function getForeverMedia($media_id, $is_video = false) { + public function getForeverMedia($media_id, $is_video = false) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } $data = array('media_id' => $media_id); - //#TODO 暂不确定此接口是否需要让视频文件走http协议 - //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议 - //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX; $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_FOREVER_GET_URL . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { if (is_string($result)) { @@ -265,9 +291,8 @@ class WechatMedia extends Common { return $this->checkRetry(__FUNCTION__, func_get_args()); } return $json; - } else { - return $result; } + return $result; } return $result; } @@ -279,7 +304,8 @@ class WechatMedia extends Common { * @param string $media_id 媒体文件id * @return bool */ - public function delForeverMedia($media_id) { + public function delForeverMedia($media_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -310,15 +336,12 @@ class WechatMedia extends Common { * 'item'=>array() //素材列表数组,内容定义请参考官方文档 * ) */ - public function getForeverList($type, $offset, $count) { + public function getForeverList($type, $offset, $count) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - $data = array( - 'type' => $type, - 'offset' => $offset, - 'count' => $count, - ); + $data = array('type' => $type, 'offset' => $offset, 'count' => $count,); $result = Tools::httpPost(self::API_URL_PREFIX . self::MEDIA_FOREVER_BATCHGET_URL . "access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); @@ -343,7 +366,8 @@ class WechatMedia extends Common { * 'news_count'=>0 //图文总数量 * ) */ - public function getForeverCount() { + public function getForeverCount() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -365,7 +389,8 @@ class WechatMedia extends Common { * @param array $data 消息结构{"articles":[{...}]} * @return bool|array */ - public function uploadArticles($data) { + public function uploadArticles($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -397,7 +422,8 @@ class WechatMedia extends Common { * "created_at":1398848981 * } */ - public function uploadMpVideo($data) { + public function uploadMpVideo($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } diff --git a/core/extend/Wechat/WechatMenu.php b/core/extend/Wechat/WechatMenu.php index e8704562..583a89e2 100644 --- a/core/extend/Wechat/WechatMenu.php +++ b/core/extend/Wechat/WechatMenu.php @@ -1,5 +1,17 @@ * @date 2016/06/28 11:52 */ -class WechatMenu extends Common { +class WechatMenu extends Common +{ /** 创建自定义菜单 */ const MENU_ADD_URL = '/menu/create?'; @@ -33,7 +46,8 @@ class WechatMenu extends Common { * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013&token=&lang=zh_CN 文档 * @return bool */ - public function createMenu($data) { + public function createMenu($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -54,7 +68,8 @@ class WechatMenu extends Common { * 获取所有菜单 * @return bool|array */ - public function getMenu() { + public function getMenu() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -75,7 +90,8 @@ class WechatMenu extends Common { * 删除所有菜单 * @return bool */ - public function deleteMenu() { + public function deleteMenu() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -98,7 +114,8 @@ class WechatMenu extends Common { * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN 文档 * @return bool|string */ - public function createCondMenu($data) { + public function createCondMenu($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -120,7 +137,8 @@ class WechatMenu extends Common { * @param string $menuid 菜单ID * @return bool */ - public function deleteCondMenu($menuid) { + public function deleteCondMenu($menuid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -143,7 +161,8 @@ class WechatMenu extends Common { * @param string $openid 粉丝openid * @return bool */ - public function tryCondMenu($openid) { + public function tryCondMenu($openid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } diff --git a/core/extend/Wechat/WechatMessage.php b/core/extend/Wechat/WechatMessage.php new file mode 100644 index 00000000..b3f5648e --- /dev/null +++ b/core/extend/Wechat/WechatMessage.php @@ -0,0 +1,352 @@ + + * @date 2016/06/28 11:29 + */ +class WechatMessage extends Common +{ + + /** + * 获取模板列表 + * @return bool|array + */ + public function getAllPrivateTemplate() + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $result = Tools::httpPost(self::API_URL_PREFIX . "/template/get_all_private_template?access_token={$this->access_token}", []); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 获取设置的行业信息 + * @return bool|array + */ + public function getTMIndustry() + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $result = Tools::httpPost(self::API_URL_PREFIX . "/template/get_industry?access_token={$this->access_token}", []); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 删除模板消息 + * @param string $tpl_id + * @return bool + */ + public function delPrivateTemplate($tpl_id) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $data = array('template_id' => $tpl_id); + $result = Tools::httpPost(self::API_URL_PREFIX . "/template/del_private_template?access_token={$this->access_token}", [Tools::json_encode($data)]); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return true; + } + return false; + } + + /** + * 模板消息 设置所属行业 + * @param string $id1 公众号模板消息所属行业编号,参看官方开发文档 行业代码 + * @param string $id2 同$id1。但如果只有一个行业,此参数可省略 + * @return bool|mixed + */ + public function setTMIndustry($id1, $id2 = '') + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $data = array(); + !empty($id1) && $data['industry_id1'] = $id1; + !empty($id2) && $data['industry_id2'] = $id2; + $json = Tools::json_encode($data); + $result = Tools::httpPost(self::API_URL_PREFIX . "/template/api_set_industry?access_token={$this->access_token}", $json); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errMsg = $json['errmsg']; + $this->errCode = $json['errcode']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 模板消息 添加消息模板 + * 成功返回消息模板的调用id + * @param string $tpl_id 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式 + * @return bool|string + */ + public function addTemplateMessage($tpl_id) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $data = Tools::json_encode(array('template_id_short' => $tpl_id)); + $result = Tools::httpPost(self::API_URL_PREFIX . "/template/api_add_template?access_token={$this->access_token}", $data); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errMsg = $json['errmsg']; + $this->errCode = $json['errcode']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json['template_id']; + } + return false; + } + + /** + * 发送模板消息 + * @param array $data 消息结构 + * { + * "touser":"OPENID", + * "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY", + * "url":"http://weixin.qq.com/download", + * "topcolor":"#FF0000", + * "data":{ + * "参数名1": { + * "value":"参数", + * "color":"#173177" //参数颜色 + * }, + * "Date":{ + * "value":"06月07日 19时24分", + * "color":"#173177" + * }, + * "CardNumber":{ + * "value":"0426", + * "color":"#173177" + * }, + * "Type":{ + * "value":"消费", + * "color":"#173177" + * } + * } + * } + * @return bool|array + */ + public function sendTemplateMessage($data) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/template/send?access_token={$this->access_token}", Tools::json_encode($data)); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errMsg = $json['errmsg']; + $this->errCode = $json['errcode']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 根据标签进行群发 ( 订阅号与服务号认证后均可用 ) + * @param array $data 消息结构 + * 注意: 视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成, + * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。 + * @return bool|array + * { + * "touser"=>array( + * "OPENID1", + * "OPENID2" + * ), + * "msgtype"=>"mpvideo", + * // 在下面5种类型中选择对应的参数内容 + * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId") + * // text => array ( "content" => "hello") + * } + */ + public function sendMassMessage($data) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/mass/send?access_token={$this->access_token}", Tools::json_encode($data)); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 根据标签进行群发 ( 订阅号与服务号认证后均可用 ) + * @param array $data 消息结构 + * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成, + * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。 + * @return bool|array + * { + * "filter"=>array( + * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id + * "group_id"=>"2" //群发的分组id + * ), + * "msgtype"=>"mpvideo", + * // 在下面5种类型中选择对应的参数内容 + * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId") + * // text => array ( "content" => "hello") + * } + */ + public function sendGroupMassMessage($data) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/mass/sendall?access_token={$this->access_token}", Tools::json_encode($data)); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 删除群发图文消息 ( 订阅号与服务号认证后均可用 ) + * @param string $msg_id 消息ID + * @return bool + */ + public function deleteMassMessage($msg_id) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $data = Tools::json_encode(array('msg_id' => $msg_id)); + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/mass/delete?access_token={$this->access_token}", $data); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return true; + } + return false; + } + + /** + * 预览群发消息 ( 订阅号与服务号认证后均可用 ) + * @param array $data + * 注意: 视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成, + * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。 + * @消息结构 + * { + * "touser"=>"OPENID", + * "msgtype"=>"mpvideo", + * // 在下面5种类型中选择对应的参数内容 + * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId") + * // text => array ( "content" => "hello") + * } + * @return bool|array + */ + public function previewMassMessage($data) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/mass/preview?access_token={$this->access_token}", Tools::json_encode($data)); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + + /** + * 查询群发消息发送状态 ( 订阅号与服务号认证后均可用 ) + * @param string $msg_id 消息ID + * @return bool|array + * { + * "msg_id":201053012, //群发消息后返回的消息id + * "msg_status":"SEND_SUCCESS", //消息发送后的状态,SENDING表示正在发送 SEND_SUCCESS表示发送成功 + * } + */ + public function queryMassMessage($msg_id) + { + if (!$this->access_token && !$this->getAccessToken()) { + return false; + } + $data = Tools::json_encode(array('msg_id' => $msg_id)); + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/mass/get?access_token={$this->access_token}", $data); + if ($result) { + $json = json_decode($result, true); + if (!$json || !empty($json['errcode'])) { + $this->errCode = $json['errcode']; + $this->errMsg = $json['errmsg']; + return $this->checkRetry(__FUNCTION__, func_get_args()); + } + return $json; + } + return false; + } + +} \ No newline at end of file diff --git a/core/extend/Wechat/WechatOauth.php b/core/extend/Wechat/WechatOauth.php index bbef2ea8..3d05b3ed 100644 --- a/core/extend/Wechat/WechatOauth.php +++ b/core/extend/Wechat/WechatOauth.php @@ -1,5 +1,17 @@ appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect"; } @@ -33,7 +47,8 @@ class WechatOauth extends Common { * 通过 code 获取 AccessToken 和 openid * @return bool|array */ - public function getOauthAccessToken() { + public function getOauthAccessToken() + { $code = isset($_GET['code']) ? $_GET['code'] : ''; if (empty($code)) { Tools::log("getOauthAccessToken Fail, Because there is no access to the code value in get."); @@ -58,7 +73,8 @@ class WechatOauth extends Common { * @param string $refresh_token * @return bool|array */ - public function getOauthRefreshToken($refresh_token) { + public function getOauthRefreshToken($refresh_token) + { $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_REFRESH_URL . "appid={$this->appid}&grant_type=refresh_token&refresh_token={$refresh_token}"); if ($result) { $json = json_decode($result, true); @@ -80,7 +96,8 @@ class WechatOauth extends Common { * @return bool|array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]} * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下 */ - public function getOauthUserInfo($access_token, $openid) { + public function getOauthUserInfo($access_token, $openid) + { $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_USERINFO_URL . "access_token={$access_token}&openid={$openid}"); if ($result) { $json = json_decode($result, true); @@ -101,7 +118,8 @@ class WechatOauth extends Common { * @param string $openid * @return bool 是否有效 */ - public function getOauthAuth($access_token, $openid) { + public function getOauthAuth($access_token, $openid) + { $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_AUTH_URL . "access_token={$access_token}&openid={$openid}"); if ($result) { $json = json_decode($result, true); diff --git a/core/extend/Wechat/WechatPay.php b/core/extend/Wechat/WechatPay.php index 8be39107..36648336 100644 --- a/core/extend/Wechat/WechatPay.php +++ b/core/extend/Wechat/WechatPay.php @@ -1,5 +1,17 @@ * @date 2015/05/13 12:12:00 */ -class WechatPay { +class WechatPay +{ /** 支付接口基础地址 */ const MCH_BASE_URL = 'https://api.mch.weixin.qq.com'; @@ -17,6 +30,9 @@ class WechatPay { /** 公众号appid */ public $appid; + /** 公众号配置 */ + public $config; + /** 商户身份ID */ public $mch_id; @@ -35,13 +51,50 @@ class WechatPay { * WechatPay constructor. * @param array $options */ - public function __construct($options = array()) { - $config = Loader::config($options); - $this->appid = isset($config['appid']) ? $config['appid'] : ''; - $this->mch_id = isset($config['mch_id']) ? $config['mch_id'] : ''; - $this->partnerKey = isset($config['partnerkey']) ? $config['partnerkey'] : ''; - $this->ssl_cer = isset($config['ssl_cer']) ? $config['ssl_cer'] : ''; - $this->ssl_key = isset($config['ssl_key']) ? $config['ssl_key'] : ''; + public function __construct($options = array()) + { + $this->config = Loader::config($options); + $this->appid = isset($this->config['appid']) ? $this->config['appid'] : ''; + $this->mch_id = isset($this->config['mch_id']) ? $this->config['mch_id'] : ''; + $this->partnerKey = isset($this->config['partnerkey']) ? $this->config['partnerkey'] : ''; + $this->ssl_cer = isset($this->config['ssl_cer']) ? $this->config['ssl_cer'] : ''; + $this->ssl_key = isset($this->config['ssl_key']) ? $this->config['ssl_key'] : ''; + } + + /** + * 获取当前错误内容 + * @return string + */ + public function getError() + { + return $this->errMsg; + } + + /** + * 当前当前错误代码 + * @return int + */ + public function getErrorCode() + { + return $this->errCode; + } + + /** + * 获取当前操作公众号APPID + * @return string + */ + public function getAppid() + { + return $this->appid; + } + + /** + * 获取SDK配置参数 + * @return array + */ + public function getConfig() + { + return $this->config; } /** @@ -49,7 +102,8 @@ class WechatPay { * @param array $data * @return string */ - protected function createXml($data) { + protected function createXml($data) + { if (!isset($data['wxappid']) && !isset($data['mch_appid']) && !isset($data['appid'])) { $data['appid'] = $this->appid; } @@ -67,7 +121,8 @@ class WechatPay { * @param string $url * @return mixed */ - public function postXml($data, $url) { + public function postXml($data, $url) + { return Tools::httpPost($url, $this->createXml($data)); } @@ -77,7 +132,8 @@ class WechatPay { * @param string $url * @return mixed */ - function postXmlSSL($data, $url) { + function postXmlSSL($data, $url) + { return Tools::httpsPost($url, $this->createXml($data), $this->ssl_cer, $this->ssl_key); } @@ -88,7 +144,8 @@ class WechatPay { * @param string $method * @return array */ - public function getArrayResult($data, $url, $method = 'postXml') { + public function getArrayResult($data, $url, $method = 'postXml') + { return Tools::xml2arr($this->$method($data, $url)); } @@ -97,7 +154,8 @@ class WechatPay { * @param array $result * @return bool|array */ - protected function _parseResult($result) { + protected function _parseResult($result) + { if (empty($result)) { $this->errCode = 'result error'; $this->errMsg = '解析返回结果失败'; @@ -125,7 +183,8 @@ class WechatPay { * @param null $goods_tag 商品标签 * @return array|bool */ - public function createMicroPay($auth_code, $out_trade_no, $total_fee, $body, $goods_tag = null) { + public function createMicroPay($auth_code, $out_trade_no, $total_fee, $body, $goods_tag = null) + { $data = array( "appid" => $this->appid, "mch_id" => $this->mch_id, @@ -147,7 +206,8 @@ class WechatPay { * 支付通知验证处理 * @return bool|array */ - public function getNotify() { + public function getNotify() + { $notifyInfo = (array)simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA); if (empty($notifyInfo)) { Tools::log('Payment notification forbidden access.', 'ERR'); @@ -182,7 +242,8 @@ class WechatPay { * @param bool $isReturn 是否返回XML内容,默认不返回 * @return string */ - public function replyXml(array $data, $isReturn = false) { + public function replyXml(array $data, $isReturn = false) + { $xml = Tools::arr2xml($data); if ($isReturn) { return $xml; @@ -200,12 +261,15 @@ class WechatPay { * @param string $notify_url 支付成功回调地址 * @param string $trade_type 支付类型JSAPI|NATIVE|APP * @param string $goods_tag 商品标记,代金券或立减优惠功能的参数 + * @param string $fee_type 交易币种 * @return bool|string */ - public function getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI", $goods_tag = null) { + public function getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI", $goods_tag = null, $fee_type = 'CNY') + { $postdata = array( "body" => $body, "out_trade_no" => $out_trade_no, + "fee_type" => $fee_type, "total_fee" => $total_fee, "notify_url" => $notify_url, "trade_type" => $trade_type, @@ -217,7 +281,7 @@ class WechatPay { if (false === $this->_parseResult($result)) { return false; } - return in_array($trade_type, array('JSAPI', 'APP')) ? $result['prepay_id'] : $result['code_url']; + return in_array($trade_type, array('JSAPI', 'APP')) ? $result['prepay_id'] : ($trade_type === 'MWEB' ? $result['mweb_url'] : $result['code_url']); } /** @@ -228,12 +292,15 @@ class WechatPay { * @param int $total_fee 订单总价 * @param string $notify_url 支付成功回调地址 * @param string $goods_tag 商品标记,代金券或立减优惠功能的参数 + * @param string $fee_type 交易币种 * @return bool|string */ - public function getQrcPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $goods_tag = null) { + public function getQrcPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $goods_tag = null, $fee_type = 'CNY') + { $postdata = array( "body" => $body, "out_trade_no" => $out_trade_no, + "fee_type" => $fee_type, "total_fee" => $total_fee, "notify_url" => $notify_url, "trade_type" => 'NATIVE', @@ -253,7 +320,8 @@ class WechatPay { * @param string $product_id 商户定义的商品id 或者订单号 * @return string */ - public function getQrcPayUrl($product_id) { + public function getQrcPayUrl($product_id) + { $data = array( 'appid' => $this->appid, 'mch_id' => $this->mch_id, @@ -271,7 +339,8 @@ class WechatPay { * @param string $prepay_id * @return array */ - public function createMchPay($prepay_id) { + public function createMchPay($prepay_id) + { $option = array(); $option["appId"] = $this->appid; $option["timeStamp"] = (string)time(); @@ -288,7 +357,8 @@ class WechatPay { * @param string $out_trade_no * @return bool */ - public function closeOrder($out_trade_no) { + public function closeOrder($out_trade_no) + { $data = array('out_trade_no' => $out_trade_no); $result = $this->getArrayResult($data, self::MCH_BASE_URL . '/pay/closeorder'); if (false === $this->_parseResult($result)) { @@ -302,7 +372,8 @@ class WechatPay { * @param $out_trade_no * @return bool|array */ - public function queryOrder($out_trade_no) { + public function queryOrder($out_trade_no) + { $data = array('out_trade_no' => $out_trade_no); $result = $this->getArrayResult($data, self::MCH_BASE_URL . '/pay/orderquery'); if (false === $this->_parseResult($result)) { @@ -314,26 +385,31 @@ class WechatPay { /** * 订单退款接口 * @param string $out_trade_no 商户订单号 - * @param string $transaction_id 微信订单号 - * @param string $out_refund_no 商户退款订单号 + * @param string $transaction_id 微信订单号,与 out_refund_no 二选一(不选时传0或false) + * @param string $out_refund_no 商户退款订单号,与 transaction_id 二选一(不选时传0或false) * @param int $total_fee 商户订单总金额 - * @param int $refund_fee 退款金额 + * @param int $refund_fee 退款金额,不可大于订单总金额 * @param int|null $op_user_id 操作员ID,默认商户ID * @param string $refund_account 退款资金来源 - * 仅针对老资金流商户使用 - * REFUND_SOURCE_UNSETTLED_FUNDS --- 未结算资金退款(默认使用未结算资金退款) - * REFUND_SOURCE_RECHARGE_FUNDS --- 可用余额退款 + * 仅针对老资金流商户使用 + * REFUND_SOURCE_UNSETTLED_FUNDS --- 未结算资金退款(默认使用未结算资金退款) + * REFUND_SOURCE_RECHARGE_FUNDS --- 可用余额退款 + * @param string $refund_desc 退款原因 + * @param string $refund_fee_type 退款货币种类 * @return bool */ - public function refund($out_trade_no, $transaction_id, $out_refund_no, $total_fee, $refund_fee, $op_user_id = null, $refund_account = '') { + public function refund($out_trade_no, $transaction_id, $out_refund_no, $total_fee, $refund_fee, $op_user_id = null, $refund_account = '', $refund_desc = '', $refund_fee_type = 'CNY') + { $data = array(); $data['out_trade_no'] = $out_trade_no; - $data['transaction_id'] = $transaction_id; - $data['out_refund_no'] = $out_refund_no; $data['total_fee'] = $total_fee; $data['refund_fee'] = $refund_fee; + $data['refund_fee_type'] = $refund_fee_type; $data['op_user_id'] = empty($op_user_id) ? $this->mch_id : $op_user_id; + !empty($out_refund_no) && $data['out_refund_no'] = $out_refund_no; + !empty($transaction_id) && $data['transaction_id'] = $transaction_id; !empty($refund_account) && $data['refund_account'] = $refund_account; + !empty($refund_desc) && $data['refund_desc'] = $refund_desc; $result = $this->getArrayResult($data, self::MCH_BASE_URL . '/secapi/pay/refund', 'postXmlSSL'); if (false === $this->_parseResult($result)) { return false; @@ -346,7 +422,8 @@ class WechatPay { * @param string $out_trade_no * @return bool|array */ - public function refundQuery($out_trade_no) { + public function refundQuery($out_trade_no) + { $data = array(); $data['out_trade_no'] = $out_trade_no; $result = $this->getArrayResult($data, self::MCH_BASE_URL . '/pay/refundquery'); @@ -362,7 +439,8 @@ class WechatPay { * @param string $bill_type ALL|SUCCESS|REFUND|REVOKED * @return bool|array */ - public function getBill($bill_date, $bill_type = 'ALL') { + public function getBill($bill_date, $bill_type = 'ALL') + { $data = array(); $data['bill_date'] = $bill_date; $data['bill_type'] = $bill_type; @@ -390,7 +468,8 @@ class WechatPay { * @return array|bool * @link https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5 */ - public function sendRedPack($openid, $total_amount, $mch_billno, $sendname, $wishing, $act_name, $remark, $total_num = 1, $scene_id = null, $risk_info = '', $consume_mch_id = null) { + public function sendRedPack($openid, $total_amount, $mch_billno, $sendname, $wishing, $act_name, $remark, $total_num = 1, $scene_id = null, $risk_info = '', $consume_mch_id = null) + { $data = array(); $data['mch_billno'] = $mch_billno; // 商户订单号 mch_id+yyyymmdd+10位一天内不能重复的数字 $data['wxappid'] = $this->appid; @@ -427,7 +506,8 @@ class WechatPay { * @return bool|array * @link https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_7&index=6 */ - public function queryRedPack($billno) { + public function queryRedPack($billno) + { $data['mch_billno'] = $billno; $data['bill_type'] = 'MCHT'; $result = $this->postXmlSSL($data, self::MCH_BASE_URL . '/mmpaymkttransfers/gethbinfo'); @@ -447,7 +527,8 @@ class WechatPay { * @return bool|array * @link https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 */ - public function transfers($openid, $amount, $billno, $desc) { + public function transfers($openid, $amount, $billno, $desc) + { $data = array(); $data['mchid'] = $this->mch_id; $data['mch_appid'] = $this->appid; @@ -471,7 +552,8 @@ class WechatPay { * @return bool|array * @link https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3 */ - public function queryTransfers($billno) { + public function queryTransfers($billno) + { $data['appid'] = $this->appid; $data['mch_id'] = $this->mch_id; $data['partner_trade_no'] = $billno; @@ -488,7 +570,8 @@ class WechatPay { * @param string $url 需要处理的长链接 * @return bool|string */ - public function shortUrl($url) { + public function shortUrl($url) + { $data = array(); $data['long_url'] = $url; $result = $this->getArrayResult($data, self::MCH_BASE_URL . '/tools/shorturl'); @@ -514,7 +597,8 @@ class WechatPay { * @return bool|array * @link https://pay.weixin.qq.com/wiki/doc/api/tools/sp_coupon.php?chapter=12_3 */ - public function sendCoupon($coupon_stock_id, $partner_trade_no, $openid, $op_user_id = null) { + public function sendCoupon($coupon_stock_id, $partner_trade_no, $openid, $op_user_id = null) + { $data = array(); $data['appid'] = $this->appid; $data['coupon_stock_id'] = $coupon_stock_id; diff --git a/core/extend/Wechat/WechatPoi.php b/core/extend/Wechat/WechatPoi.php index 1bce669f..8adf85ad 100644 --- a/core/extend/Wechat/WechatPoi.php +++ b/core/extend/Wechat/WechatPoi.php @@ -1,5 +1,17 @@ * @date 2016/10/26 15:43 */ -class WechatPoi extends Common { +class WechatPoi extends Common +{ /** 创建门店 */ const POI_ADD = '/cgi-bin/poi/addpoi?'; @@ -36,7 +49,8 @@ class WechatPoi extends Common { * @param array $data * @return bool */ - public function addPoi($data) { + public function addPoi($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -59,7 +73,8 @@ class WechatPoi extends Common { * @param string $poi_id JSON数据格式 * @return bool|array */ - public function delPoi($poi_id) { + public function delPoi($poi_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -83,7 +98,8 @@ class WechatPoi extends Common { * @param array $data * @return bool */ - public function updatePoi($data) { + public function updatePoi($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -106,7 +122,8 @@ class WechatPoi extends Common { * @param string $poi_id * @return bool */ - public function getPoi($poi_id) { + public function getPoi($poi_id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -131,7 +148,8 @@ class WechatPoi extends Common { * @param int $limit 返回数据条数,最大允许50,默认为20 * @return bool|array */ - public function getPoiList($begin = 0, $limit = 50) { + public function getPoiList($begin = 0, $limit = 50) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -154,7 +172,8 @@ class WechatPoi extends Common { * 获取商家门店类目表 * @return bool|string */ - public function getCategory() { + public function getCategory() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } diff --git a/core/extend/Wechat/WechatReceive.php b/core/extend/Wechat/WechatReceive.php index 1c33199b..f2d2300a 100644 --- a/core/extend/Wechat/WechatReceive.php +++ b/core/extend/Wechat/WechatReceive.php @@ -1,9 +1,20 @@ * @date 2016/06/28 11:29 */ -class WechatReceive extends Common { - - /** 消息推送地址 */ - const CUSTOM_SEND_URL = '/message/custom/send?'; - const MASS_SEND_URL = '/message/mass/send?'; - const TEMPLATE_SET_INDUSTRY_URL = '/message/template/api_set_industry?'; - const TEMPLATE_ADD_TPL_URL = '/message/template/api_add_template?'; - const TEMPLATE_SEND_URL = '/message/template/send?'; - const MASS_SEND_GROUP_URL = '/message/mass/sendall?'; - const MASS_DELETE_URL = '/message/mass/delete?'; - const MASS_PREVIEW_URL = '/message/mass/preview?'; - const MASS_QUERY_URL = '/message/mass/get?'; +class WechatReceive extends WechatMessage +{ /** 消息回复类型 */ const MSGTYPE_TEXT = 'text'; - const MSGTYPE_IMAGE = 'image'; - const MSGTYPE_LOCATION = 'location'; const MSGTYPE_LINK = 'link'; + const MSGTYPE_NEWS = 'news'; + const MSGTYPE_IMAGE = 'image'; + const MSGTYPE_VOICE = 'voice'; const MSGTYPE_EVENT = 'event'; const MSGTYPE_MUSIC = 'music'; - const MSGTYPE_NEWS = 'news'; - const MSGTYPE_VOICE = 'voice'; const MSGTYPE_VIDEO = 'video'; + const MSGTYPE_LOCATION = 'location'; - /** 文件过滤 */ + /** 文本过滤 */ protected $_text_filter = true; /** 消息对象 */ @@ -46,7 +47,8 @@ class WechatReceive extends Common { * 获取微信服务器发来的内容 * @return $this */ - public function getRev() { + public function getRev() + { if ($this->_receive) { return $this; } @@ -59,7 +61,8 @@ class WechatReceive extends Common { * 获取微信服务器发来的信息数据 * @return array */ - public function getRevData() { + public function getRevData() + { return $this->_receive; } @@ -67,7 +70,8 @@ class WechatReceive extends Common { * 获取消息发送者 * @return bool|string */ - public function getRevFrom() { + public function getRevFrom() + { if (isset($this->_receive['FromUserName'])) { return $this->_receive['FromUserName']; } @@ -78,7 +82,8 @@ class WechatReceive extends Common { * 获取消息接受者 * @return bool|string */ - public function getRevTo() { + public function getRevTo() + { if (isset($this->_receive['ToUserName'])) { return $this->_receive['ToUserName']; } @@ -89,7 +94,8 @@ class WechatReceive extends Common { * 获取接收消息的类型 * @return bool|string */ - public function getRevType() { + public function getRevType() + { if (isset($this->_receive['MsgType'])) { return $this->_receive['MsgType']; } @@ -100,7 +106,8 @@ class WechatReceive extends Common { * 获取消息ID * @return bool|string */ - public function getRevID() { + public function getRevID() + { if (isset($this->_receive['MsgId'])) { return $this->_receive['MsgId']; } @@ -111,7 +118,8 @@ class WechatReceive extends Common { * 获取消息发送时间 * @return bool|string */ - public function getRevCtime() { + public function getRevCtime() + { if (isset($this->_receive['CreateTime'])) { return $this->_receive['CreateTime']; } @@ -123,7 +131,8 @@ class WechatReceive extends Common { * 当Event为 card_pass_check(审核通过) 或 card_not_pass_check(未通过) * @return bool|string 返回卡券ID */ - public function getRevCardPass() { + public function getRevCardPass() + { if (isset($this->_receive['CardId'])) { return $this->_receive['CardId']; } @@ -135,7 +144,8 @@ class WechatReceive extends Common { * 当Event为 user_get_card(用户领取卡券) * @return bool|array */ - public function getRevCardGet() { + public function getRevCardGet() + { $array = array(); if (isset($this->_receive['CardId'])) { $array['CardId'] = $this->_receive['CardId']; @@ -147,38 +157,34 @@ class WechatReceive extends Common { if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) { $array['UserCardCode'] = $this->_receive['UserCardCode']; } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** * 获取卡券事件推送 - 删除卡券 - * 当Event为 user_del_card(用户删除卡券) + * 当Event为 user_del_card (用户删除卡券) * @return bool|array */ - public function getRevCardDel() { + public function getRevCardDel() + { if (isset($this->_receive['CardId'])) { //卡券 ID $array['CardId'] = $this->_receive['CardId']; } if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) { $array['UserCardCode'] = $this->_receive['UserCardCode']; } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** * 获取接收消息内容正文 * @return bool */ - public function getRevContent() { + public function getRevContent() + { if (isset($this->_receive['Content'])) { return $this->_receive['Content']; - } else if (isset($this->_receive['Recognition'])) { //获取语音识别文字内容,需申请开通 + } else if (isset($this->_receive['Recognition'])) { return $this->_receive['Recognition']; } return false; @@ -188,11 +194,12 @@ class WechatReceive extends Common { * 获取接收消息图片 * @return array|bool */ - public function getRevPic() { + public function getRevPic() + { if (isset($this->_receive['PicUrl'])) { return array( 'mediaid' => $this->_receive['MediaId'], - 'picurl' => (string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错 + 'picurl' => (string)$this->_receive['PicUrl'], ); } return false; @@ -202,7 +209,8 @@ class WechatReceive extends Common { * 获取接收消息链接 * @return bool|array */ - public function getRevLink() { + public function getRevLink() + { if (isset($this->_receive['Url'])) { return array( 'url' => $this->_receive['Url'], @@ -217,7 +225,8 @@ class WechatReceive extends Common { * 获取接收地理位置 * @return bool|array */ - public function getRevGeo() { + public function getRevGeo() + { if (isset($this->_receive['Location_X'])) { return array( 'x' => $this->_receive['Location_X'], @@ -233,7 +242,8 @@ class WechatReceive extends Common { * 获取上报地理位置事件 * @return bool|array */ - public function getRevEventGeo() { + public function getRevEventGeo() + { if (isset($this->_receive['Latitude'])) { return array( 'x' => $this->_receive['Latitude'], @@ -248,28 +258,27 @@ class WechatReceive extends Common { * 获取接收事件推送 * @return bool|array */ - public function getRevEvent() { + public function getRevEvent() + { if (isset($this->_receive['Event'])) { $array['event'] = $this->_receive['Event']; } if (isset($this->_receive['EventKey'])) { $array['key'] = $this->_receive['EventKey']; } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** * 获取自定义菜单的扫码推事件信息 * * 事件类型为以下两种时则调用此方法有效 - * Event 事件类型,scancode_push - * Event 事件类型,scancode_waitmsg + * Event 事件类型, scancode_push + * Event 事件类型, scancode_waitmsg * @return bool|array */ - public function getRevScanInfo() { + public function getRevScanInfo() + { if (isset($this->_receive['ScanCodeInfo'])) { if (!is_array($this->_receive['ScanCodeInfo'])) { $array = (array)$this->_receive['ScanCodeInfo']; @@ -278,10 +287,7 @@ class WechatReceive extends Common { $array = $this->_receive['ScanCodeInfo']; } } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** @@ -304,7 +310,8 @@ class WechatReceive extends Common { * ) * */ - public function getRevSendPicsInfo() { + public function getRevSendPicsInfo() + { if (isset($this->_receive['SendPicsInfo'])) { if (!is_array($this->_receive['SendPicsInfo'])) { $array = (array)$this->_receive['SendPicsInfo']; @@ -321,10 +328,7 @@ class WechatReceive extends Common { $array = $this->_receive['SendPicsInfo']; } } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** @@ -343,7 +347,8 @@ class WechatReceive extends Common { * ) * */ - public function getRevSendGeoInfo() { + public function getRevSendGeoInfo() + { if (isset($this->_receive['SendLocationInfo'])) { if (!is_array($this->_receive['SendLocationInfo'])) { $array = (array)$this->_receive['SendLocationInfo']; @@ -358,17 +363,15 @@ class WechatReceive extends Common { $array = $this->_receive['SendLocationInfo']; } } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** * 获取接收语音推送 * @return bool|array */ - public function getRevVoice() { + public function getRevVoice() + { if (isset($this->_receive['MediaId'])) { return array( 'mediaid' => $this->_receive['MediaId'], @@ -382,7 +385,8 @@ class WechatReceive extends Common { * 获取接收视频推送 * @return array|bool */ - public function getRevVideo() { + public function getRevVideo() + { if (isset($this->_receive['MediaId'])) { return array( 'mediaid' => $this->_receive['MediaId'], @@ -396,7 +400,8 @@ class WechatReceive extends Common { * 获取接收TICKET * @return bool|string */ - public function getRevTicket() { + public function getRevTicket() + { if (isset($this->_receive['Ticket'])) { return $this->_receive['Ticket']; } @@ -407,7 +412,8 @@ class WechatReceive extends Common { * 获取二维码的场景值 * @return bool|string */ - public function getRevSceneId() { + public function getRevSceneId() + { if (isset($this->_receive['EventKey'])) { return str_replace('qrscene_', '', $this->_receive['EventKey']); } @@ -420,7 +426,8 @@ class WechatReceive extends Common { * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH * @return bool|string */ - public function getRevTplMsgID() { + public function getRevTplMsgID() + { if (isset($this->_receive['MsgID'])) { return $this->_receive['MsgID']; } @@ -431,7 +438,8 @@ class WechatReceive extends Common { * 获取模板消息发送状态 * @return bool|string */ - public function getRevStatus() { + public function getRevStatus() + { if (isset($this->_receive['Status'])) { return $this->_receive['Status']; } @@ -443,7 +451,8 @@ class WechatReceive extends Common { * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH,即高级群发/模板消息 * @return bool|array */ - public function getRevResult() { + public function getRevResult() + { if (isset($this->_receive['Status'])) { //发送是否成功,具体的返回值请参考 高级群发/模板消息 的事件推送说明 $array['Status'] = $this->_receive['Status']; } @@ -474,7 +483,8 @@ class WechatReceive extends Common { * 当Event为 kfcreatesession 即接入会话 * @return bool|string */ - public function getRevKFCreate() { + public function getRevKFCreate() + { if (isset($this->_receive['KfAccount'])) { return $this->_receive['KfAccount']; } @@ -486,7 +496,8 @@ class WechatReceive extends Common { * 当Event为 kfclosesession 即关闭会话 * @return bool|string */ - public function getRevKFClose() { + public function getRevKFClose() + { if (isset($this->_receive['KfAccount'])) { return $this->_receive['KfAccount']; } @@ -498,17 +509,15 @@ class WechatReceive extends Common { * 当Event为 kfswitchsession 即转接会话 * @return bool|array */ - public function getRevKFSwitch() { + public function getRevKFSwitch() + { if (isset($this->_receive['FromKfAccount'])) { //原接入客服 $array['FromKfAccount'] = $this->_receive['FromKfAccount']; } if (isset($this->_receive['ToKfAccount'])) { //转接到客服 $array['ToKfAccount'] = $this->_receive['ToKfAccount']; } - if (isset($array) && count($array) > 0) { - return $array; - } - return false; + return (isset($array) && count($array) > 0) ? $array : false; } /** @@ -516,109 +525,12 @@ class WechatReceive extends Common { * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}} * @return bool|array */ - public function sendCustomMessage($data) { + public function sendCustomMessage($data) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } - $result = Tools::httpPost(self::API_URL_PREFIX . self::CUSTOM_SEND_URL . "access_token={$this->access_token}", Tools::json_encode($data)); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json; - } - return false; - } - - /** - * 模板消息 设置所属行业 - * @param string $id1 公众号模板消息所属行业编号,参看官方开发文档 行业代码 - * @param string $id2 同$id1。但如果只有一个行业,此参数可省略 - * @return bool|mixed - */ - public function setTMIndustry($id1, $id2 = '') { - if ($id1) { - $data['industry_id1'] = $id1; - } - if ($id2) { - $data['industry_id2'] = $id2; - } - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::TEMPLATE_SET_INDUSTRY_URL . "access_token={$this->access_token}", Tools::json_encode($data)); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json; - } - return false; - } - - /** - * 模板消息 添加消息模板 - * 成功返回消息模板的调用id - * @param string $tpl_id 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式 - * @return bool|string - */ - public function addTemplateMessage($tpl_id) { - $data = array('template_id_short' => $tpl_id); - if (!$this->access_token && !$this->getAccessToken()) - return false; - $result = Tools::httpPost(self::API_URL_PREFIX . self::TEMPLATE_ADD_TPL_URL . "access_token={$this->access_token}", Tools::json_encode($data)); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json['template_id']; - } - return false; - } - - /** - * 发送模板消息 - * @param array $data 消息结构 - * { - * "touser":"OPENID", - * "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY", - * "url":"http://weixin.qq.com/download", - * "topcolor":"#FF0000", - * "data":{ - * "参数名1": { - * "value":"参数", - * "color":"#173177" //参数颜色 - * }, - * "Date":{ - * "value":"06月07日 19时24分", - * "color":"#173177" - * }, - * "CardNumber":{ - * "value":"0426", - * "color":"#173177" - * }, - * "Type":{ - * "value":"消费", - * "color":"#173177" - * } - * } - * } - * @return bool|array - */ - public function sendTemplateMessage($data) { - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::TEMPLATE_SEND_URL . "access_token={$this->access_token}", Tools::json_encode($data)); + $result = Tools::httpPost(self::API_URL_PREFIX . "/message/custom/send?access_token={$this->access_token}", Tools::json_encode($data)); if ($result) { $json = json_decode($result, true); if (!$json || !empty($json['errcode'])) { @@ -636,7 +548,8 @@ class WechatReceive extends Common { * @param string $customer_account * @return $this */ - public function transfer_customer_service($customer_account = '') { + public function transfer_customer_service($customer_account = '') + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -650,161 +563,14 @@ class WechatReceive extends Common { return $this; } - /** - * 高级群发消息, 根据OpenID列表群发图文消息(订阅号不可用) - * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成, - * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。 - * @param array $data 消息结构 - * { - * "touser"=>array( - * "OPENID1", - * "OPENID2" - * ), - * "msgtype"=>"mpvideo", - * // 在下面5种类型中选择对应的参数内容 - * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId") - * // text => array ( "content" => "hello") - * } - * @return bool|array - */ - public function sendMassMessage($data) { - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_SEND_URL . "access_token={$this->access_token}", Tools::json_encode($data)); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json; - } - return false; - } - - /** - * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用) - * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成, - * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。 - * @param array $data 消息结构 - * { - * "filter"=>array( - * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id - * "group_id"=>"2" //群发的分组id - * ), - * "msgtype"=>"mpvideo", - * // 在下面5种类型中选择对应的参数内容 - * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId") - * // text => array ( "content" => "hello") - * } - * @return bool|array - */ - public function sendGroupMassMessage($data) { - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_SEND_GROUP_URL . "access_token={$this->access_token}", Tools::json_encode($data)); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json; - } - return false; - } - - /** - * 高级群发消息, 删除群发图文消息(认证后的订阅号可用) - * @param string $msg_id 消息ID - * @return bool - */ - public function deleteMassMessage($msg_id) { - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_DELETE_URL . "access_token={$this->access_token}", Tools::json_encode(array('msg_id' => $msg_id))); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return true; - } - return false; - } - - /** - * 高级群发消息, 预览群发消息(认证后的订阅号可用) - * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成, - * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。 - * @param type $data - * @消息结构 - * { - * "touser"=>"OPENID", - * "msgtype"=>"mpvideo", - * // 在下面5种类型中选择对应的参数内容 - * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId") - * // text => array ( "content" => "hello") - * } - * @return bool|array - */ - public function previewMassMessage($data) { - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_PREVIEW_URL . "access_token={$this->access_token}", Tools::json_encode($data)); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json; - } - return false; - } - - /** - * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用) - * @param string $msg_id 消息ID - * @return bool|array - * { - * "msg_id":201053012, //群发消息后返回的消息id - * "msg_status":"SEND_SUCCESS" //消息发送后的状态,SENDING表示正在发送 SEND_SUCCESS表示发送成功 - * } - */ - public function queryMassMessage($msg_id) { - if (!$this->access_token && !$this->getAccessToken()) { - return false; - } - $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_QUERY_URL . "access_token={$this->access_token}", Tools::json_encode(array('msg_id' => $msg_id))); - if ($result) { - $json = json_decode($result, true); - if (!$json || !empty($json['errcode'])) { - $this->errCode = $json['errcode']; - $this->errMsg = $json['errmsg']; - return $this->checkRetry(__FUNCTION__, func_get_args()); - } - return $json; - } - return false; - } - /** * 设置发送消息 * @param string|array $msg 消息数组 * @param bool $append 是否在原消息数组追加 * @return array */ - public function Message($msg = '', $append = false) { + public function Message($msg = '', $append = false) + { if (is_null($msg)) { $this->_msg = array(); } elseif (is_array($msg)) { @@ -823,7 +589,8 @@ class WechatReceive extends Common { * @param string $text 文本内容 * @return $this */ - public function text($text = '') { + public function text($text = '') + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -840,7 +607,8 @@ class WechatReceive extends Common { * @param string $mediaid 图片媒体ID * @return $this */ - public function image($mediaid = '') { + public function image($mediaid = '') + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -857,7 +625,8 @@ class WechatReceive extends Common { * @param string $mediaid 语音媒体ID * @return $this */ - public function voice($mediaid = '') { + public function voice($mediaid = '') + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -876,7 +645,8 @@ class WechatReceive extends Common { * @param string $description 视频描述 * @return $this */ - public function video($mediaid = '', $title = '', $description = '') { + public function video($mediaid = '', $title = '', $description = '') + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -901,7 +671,8 @@ class WechatReceive extends Common { * @param string $thumbmediaid 音乐图片缩略图的媒体id(可选) * @return $this */ - public function music($title, $desc, $musicurl, $hgmusicurl = '', $thumbmediaid = '') { + public function music($title, $desc, $musicurl, $hgmusicurl = '', $thumbmediaid = '') + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -926,7 +697,8 @@ class WechatReceive extends Common { * @param array $newsData * @return $this */ - public function news($newsData = array()) { + public function news($newsData = array()) + { $msg = array( 'ToUserName' => $this->getRevFrom(), 'FromUserName' => $this->getRevTo(), @@ -945,7 +717,8 @@ class WechatReceive extends Common { * @param bool $return 是否返回信息而不抛出到浏览器(默认:否) * @return bool|string */ - public function reply($msg = array(), $return = false) { + public function reply($msg = array(), $return = false) + { if (empty($msg)) { if (empty($this->_msg)) { //防止不先设置回复内容,直接调用reply方法导致异常 return false; @@ -954,7 +727,7 @@ class WechatReceive extends Common { } $xmldata = Tools::arr2xml($msg); if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式 - !class_exists('Prpcrypt', FALSE) && require __DIR__ . '/Lib/Prpcrypt.php'; + !class_exists('Prpcrypt', false) && require __DIR__ . '/Lib/Prpcrypt.php'; $pc = new Prpcrypt($this->encodingAesKey); // 如果是第三方平台,加密得使用 component_appid $array = $pc->encrypt($xmldata, empty($this->config['component_appid']) ? $this->appid : $this->config['component_appid']); @@ -966,7 +739,7 @@ class WechatReceive extends Common { $timestamp = time(); $nonce = rand(77, 999) * rand(605, 888) * rand(11, 99); $encrypt = $array[1]; - $tmpArr = array($this->token, $timestamp, $nonce, $encrypt); //比普通公众平台多了一个加密的密文 + $tmpArr = array($this->token, $timestamp, $nonce, $encrypt); sort($tmpArr, SORT_STRING); $signature = sha1(implode($tmpArr)); $format = "%s"; @@ -983,7 +756,8 @@ class WechatReceive extends Common { * @param string $text * @return string */ - private function _auto_text_filter($text) { + private function _auto_text_filter($text) + { if (!$this->_text_filter) { return $text; } diff --git a/core/extend/Wechat/WechatScript.php b/core/extend/Wechat/WechatScript.php index e96120cb..b23df1de 100644 --- a/core/extend/Wechat/WechatScript.php +++ b/core/extend/Wechat/WechatScript.php @@ -1,5 +1,17 @@ * @date 2016/06/28 11:24 */ -class WechatScript extends Common { +class WechatScript extends Common +{ /** * JSAPI授权TICKET @@ -24,7 +37,8 @@ class WechatScript extends Common { * @param string $appid * @return bool */ - public function resetJsTicket($appid = '') { + public function resetJsTicket($appid = '') + { $this->jsapi_ticket = ''; $authname = 'wechat_jsapi_ticket_' . empty($appid) ? $this->appid : $appid; Tools::removeCache($authname); @@ -38,7 +52,8 @@ class WechatScript extends Common { * @param string $access_token 获取 jsapi_ticket 指定 access_token * @return bool|string */ - public function getJsTicket($appid = '', $jsapi_ticket = '', $access_token = '') { + public function getJsTicket($appid = '', $jsapi_ticket = '', $access_token = '') + { if (empty($access_token)) { if (!$this->access_token && !$this->getAccessToken()) { return false; @@ -88,7 +103,8 @@ class WechatScript extends Common { * @param string $access_token 获取 jsapi_ticket 指定 access_token * @return array|bool 返回签名字串 */ - public function getJsSign($url, $timestamp = 0, $noncestr = '', $appid = '', $access_token = '') { + public function getJsSign($url, $timestamp = 0, $noncestr = '', $appid = '', $access_token = '') + { if (!$this->jsapi_ticket && !$this->getJsTicket($appid, '', $access_token) || empty($url)) { return false; } diff --git a/core/extend/Wechat/WechatService.php b/core/extend/Wechat/WechatService.php index 8a16ad14..49b2198e 100644 --- a/core/extend/Wechat/WechatService.php +++ b/core/extend/Wechat/WechatService.php @@ -1,5 +1,17 @@ * @date 2016/10/18 00:35:55 */ -class WechatService { +class WechatService +{ const URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin/component'; // 获取服务access_token @@ -57,7 +70,8 @@ class WechatService { * WechatService constructor. * @param array $options */ - public function __construct($options = array()) { + public function __construct($options = array()) + { $options = Loader::config($options); $this->component_encodingaeskey = !empty($options['component_encodingaeskey']) ? $options['component_encodingaeskey'] : ''; $this->component_verify_ticket = !empty($options['component_verify_ticket']) ? $options['component_verify_ticket'] : ''; @@ -70,7 +84,8 @@ class WechatService { * 接收公众平台推送的 Ticket * @return bool|array */ - public function getComonentTicket() { + public function getComonentTicket() + { $receive = new WechatReceive(array( 'appid' => $this->component_appid, 'appsecret' => $this->component_appsecret, @@ -102,7 +117,8 @@ class WechatService { * @param string $authorizer_refresh_token 授权方刷新令牌 * @return bool|string */ - public function refreshAccessToken($authorizer_appid, $authorizer_refresh_token) { + public function refreshAccessToken($authorizer_appid, $authorizer_refresh_token) + { empty($this->component_access_token) && $this->getComponentAccessToken(); if (empty($this->component_access_token)) { return false; @@ -123,7 +139,8 @@ class WechatService { * 获取或刷新服务 AccessToken * @return bool|string */ - public function getComponentAccessToken() { + public function getComponentAccessToken() + { $cacheKey = 'wechat_component_access_token'; $this->component_access_token = Tools::getCache($cacheKey); if (empty($this->component_access_token)) { @@ -148,7 +165,8 @@ class WechatService { * @param string|null $field * @return bool|array */ - private function _decode($result, $field = null) { + private function _decode($result, $field = null) + { $this->data = json_decode($result, true); if (!empty($this->data['errcode'])) { $this->errCode = $this->data['errcode']; @@ -171,7 +189,8 @@ class WechatService { * @param string $authorization_code * @return bool|array */ - public function getAuthorizationInfo($authorization_code) { + public function getAuthorizationInfo($authorization_code) + { empty($this->component_access_token) && $this->getComponentAccessToken(); if (empty($this->component_access_token)) { return false; @@ -195,11 +214,12 @@ class WechatService { * @param array $func_info * @return string */ - private function _parseFuncInfo($func_info) { + private function _parseFuncInfo($func_info) + { $authorization_list = array(); foreach ($func_info as $func) { foreach ($func as $f) { - $authorization_list[] = $f['id']; + isset($f['id']) && $authorization_list[] = $f['id']; } } return join($authorization_list, ','); @@ -210,7 +230,8 @@ class WechatService { * @param string $authorizer_appid * @return bool */ - public function getWechatInfo($authorizer_appid) { + public function getWechatInfo($authorizer_appid) + { empty($this->component_access_token) && $this->getComponentAccessToken(); $data = array(); $data['component_access_token'] = $this->component_access_token; @@ -237,7 +258,8 @@ class WechatService { * @param string $option_name * @return bool */ - public function getAuthorizerOption($authorizer_appid, $option_name) { + public function getAuthorizerOption($authorizer_appid, $option_name) + { empty($this->component_access_token) && $this->getComponentAccessToken(); if (empty($this->authorizer_appid)) { return false; @@ -261,7 +283,8 @@ class WechatService { * @param string $option_value * @return bool */ - public function setAuthorizerOption($authorizer_appid, $option_name, $option_value) { + public function setAuthorizerOption($authorizer_appid, $option_name, $option_value) + { empty($this->component_access_token) && $this->getComponentAccessToken(); if (empty($this->authorizer_appid)) { return false; @@ -284,7 +307,8 @@ class WechatService { * @param string $redirect_uri * @return bool */ - public function getAuthRedirect($redirect_uri) { + public function getAuthRedirect($redirect_uri) + { empty($this->pre_auth_code) && $this->getPreauthCode(); if (empty($this->pre_auth_code)) { return false; @@ -297,7 +321,8 @@ class WechatService { * * @return bool|string */ - public function getPreauthCode() { + public function getPreauthCode() + { empty($this->component_access_token) && $this->getComponentAccessToken(); if (empty($this->component_access_token)) { return false; @@ -320,7 +345,8 @@ class WechatService { * @param string $scope snsapi_userinfo|snsapi_base * @return string */ - public function getOauthRedirect($appid, $redirect_uri, $scope = 'snsapi_userinfo') { + public function getOauthRedirect($appid, $redirect_uri, $scope = 'snsapi_userinfo') + { return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri=" . urlencode($redirect_uri) . "&response_type=code&scope={$scope}&state={$appid}&component_appid={$this->component_appid}#wechat_redirect"; } @@ -330,7 +356,8 @@ class WechatService { * @param string $appid * @return bool|array */ - public function getOauthAccessToken($appid) { + public function getOauthAccessToken($appid) + { $code = isset($_GET['code']) ? $_GET['code'] : ''; if (empty($code)) { return false; @@ -356,7 +383,8 @@ class WechatService { * @param string $result * @return bool */ - private function parseJson($result) { + private function parseJson($result) + { $json = json_decode($result, true); if (!empty($json['errcode'])) { $this->errCode = $json['errcode']; @@ -373,7 +401,8 @@ class WechatService { * @return bool|array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]} * 注意:unionid字段 只有在用户将公众号绑定到公众号第三方平台账号后,才会出现。建议调用前用isset()检测一下 */ - public function getOauthUserInfo($openid, $oauthAccessToken) { + public function getOauthUserInfo($openid, $oauthAccessToken) + { $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$oauthAccessToken}&openid={$openid}&lang=zh_CN"; return $this->parseJson(Tools::httpGet($url)); } diff --git a/core/extend/Wechat/WechatUser.php b/core/extend/Wechat/WechatUser.php index 71a703dc..5de7c9f1 100644 --- a/core/extend/Wechat/WechatUser.php +++ b/core/extend/Wechat/WechatUser.php @@ -1,5 +1,17 @@ * @date 2016/06/28 11:20 */ -class WechatUser extends Common { +class WechatUser extends Common +{ /** 获取粉丝列表 */ const USER_GET_URL = '/user/get?'; @@ -66,7 +79,8 @@ class WechatUser extends Common { * @param string $next_openid * @return bool|array */ - public function getUserList($next_openid = '') { + public function getUserList($next_openid = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -89,7 +103,8 @@ class WechatUser extends Common { * @return bool|array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]} * @注意:unionid字段 只有在粉丝将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下 */ - public function getUserInfo($openid) { + public function getUserInfo($openid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -112,7 +127,8 @@ class WechatUser extends Common { * @param string $lang 指定返回语言 * @return bool|mixed */ - public function getUserBatchInfo(array $openids, $lang = 'zh_CN') { + public function getUserBatchInfo(array $openids, $lang = 'zh_CN') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -139,7 +155,8 @@ class WechatUser extends Common { * @param string $remark 备注名 * @return bool|array */ - public function updateUserRemark($openid, $remark) { + public function updateUserRemark($openid, $remark) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -161,7 +178,8 @@ class WechatUser extends Common { * 获取粉丝分组列表 * @return bool|array */ - public function getGroup() { + public function getGroup() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -183,7 +201,8 @@ class WechatUser extends Common { * @param type $id * @return bool */ - public function delGroup($id) { + public function delGroup($id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -206,7 +225,8 @@ class WechatUser extends Common { * @param string $openid * @return bool|int 成功则返回粉丝分组id */ - public function getUserGroup($openid) { + public function getUserGroup($openid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -230,7 +250,8 @@ class WechatUser extends Common { * @param string $name 分组名称 * @return bool|array */ - public function createGroup($name) { + public function createGroup($name) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -254,7 +275,8 @@ class WechatUser extends Common { * @param string $name 分组名称 * @return bool|array */ - public function updateGroup($groupid, $name) { + public function updateGroup($groupid, $name) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -278,7 +300,8 @@ class WechatUser extends Common { * @param string $openid 粉丝openid * @return bool|array */ - public function updateGroupMembers($groupid, $openid) { + public function updateGroupMembers($groupid, $openid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -302,7 +325,8 @@ class WechatUser extends Common { * @param string $openid_list 粉丝openid数组(一次不能超过50个) * @return bool|array */ - public function batchUpdateGroupMembers($groupid, $openid_list) { + public function batchUpdateGroupMembers($groupid, $openid_list) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -325,7 +349,8 @@ class WechatUser extends Common { * @param string $name 标签名称 * @return bool|array */ - public function createTags($name) { + public function createTags($name) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -349,7 +374,8 @@ class WechatUser extends Common { * @param string $name 标签名称 * @return bool|array */ - public function updateTag($id, $name) { + public function updateTag($id, $name) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -371,7 +397,8 @@ class WechatUser extends Common { * 获取粉丝标签列表 * @return bool|array */ - public function getTags() { + public function getTags() + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -393,7 +420,8 @@ class WechatUser extends Common { * @param string $id * @return bool */ - public function delTag($id) { + public function delTag($id) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -417,7 +445,8 @@ class WechatUser extends Common { * @param string $next_openid * @return bool */ - public function getTagUsers($tagid, $next_openid = '') { + public function getTagUsers($tagid, $next_openid = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -441,7 +470,8 @@ class WechatUser extends Common { * @param array $openid_list 粉丝openid数组,一次不能超过50个 * @return bool|array */ - public function batchAddUserTag($tagid, $openid_list) { + public function batchAddUserTag($tagid, $openid_list) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -465,7 +495,8 @@ class WechatUser extends Common { * @param array $openid_list 粉丝openid数组,一次不能超过50个 * @return bool|array */ - public function batchDeleteUserTag($tagid, $openid_list) { + public function batchDeleteUserTag($tagid, $openid_list) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -488,7 +519,8 @@ class WechatUser extends Common { * @param string $openid 粉丝openid * @return bool|array */ - public function getUserTags($openid) { + public function getUserTags($openid) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -511,7 +543,8 @@ class WechatUser extends Common { * @param string $begin_openid * @return bool|array */ - public function getBacklist($begin_openid = '') { + public function getBacklist($begin_openid = '') + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -534,7 +567,8 @@ class WechatUser extends Common { * @param string $openids * @return bool|array */ - public function addBacklist($openids) { + public function addBacklist($openids) + { if (!$this->access_token && !$this->getAccessToken()) { return false; } @@ -557,7 +591,8 @@ class WechatUser extends Common { * @param string $openids * @return bool|array */ - public function delBacklist($openids) { + public function delBacklist($openids) + { if (!$this->access_token && !$this->getAccessToken()) { return false; }