WechatApi.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /**
  3. * Author: 芸众商城 www.yunzshop.com
  4. * Date: 2017/11/7
  5. * Time: 下午5:10
  6. */
  7. namespace app\common\services\notice;
  8. use app\common\exceptions\AppException;
  9. use app\common\exceptions\ShopException;
  10. use app\common\models\AccountWechats;
  11. use app\common\traits\JsonTrait;
  12. class WechatApi
  13. {
  14. use JsonTrait;
  15. private $account;
  16. public function __construct()
  17. {
  18. $this->account = AccountWechats::getAccountByUniacid(\YunShop::app()->uniacid);
  19. }
  20. /**
  21. * @name 通过模板编号从行业模板库选择模板到帐号后台
  22. * @author
  23. * @param $templateIdShort
  24. * @return array
  25. */
  26. public function getTmpByTemplateIdShort($templateIdShort)
  27. {
  28. $param = '{"template_id_short":"' . $templateIdShort . '"}';
  29. $http_result = $this->ihttp_request($this->getTmpUrl(), $param);
  30. $result = @json_decode($http_result['content'], true);
  31. return $this->commonReturn($result);
  32. }
  33. /**
  34. * @name 通过模板编号从行业模板库获取模版id
  35. * @author
  36. * @param $templateIdShort
  37. * @return array
  38. */
  39. public function getTemplateIdByTemplateIdShort($templateIdShort)
  40. {
  41. $param = '{"template_id_short":"' . $templateIdShort . '"}';
  42. $http_result = $this->ihttp_request($this->getTmpUrl(), $param);
  43. $result = @json_decode($http_result['content'], true);
  44. return $result['template_id'];
  45. }
  46. /**
  47. * @name 通过模板ID删除
  48. * @author
  49. * @param $templateId
  50. * @return array
  51. */
  52. public function delTmpByTemplateId($templateId)
  53. {
  54. $param = '{"template_id":"' . $templateId . '"}';
  55. $http_result = $this->ihttp_request($this->delTmpUrl(), $param);
  56. $result = @json_decode($http_result['content'], true);
  57. return $this->commonReturn($result);
  58. }
  59. /**
  60. * @name 获取公众号模板列表
  61. * @author
  62. * @return \Illuminate\Http\JsonResponse
  63. * @throws ShopException
  64. */
  65. public function getTmpList()
  66. {
  67. $http_result = $this->ihttp_request($this->getTmpListUrl());
  68. $result = @json_decode($http_result['content'], true);
  69. if (!is_array($result)) {
  70. throw new ShopException('请求失败');
  71. }
  72. if (!(empty($result['errcode']))) {
  73. throw new ShopException($result['errmsg']);
  74. }
  75. foreach ($result['template_list'] as $key => &$value )
  76. {
  77. preg_match_all('{{(.)*?}}', $value['content'], $matches);
  78. foreach ($matches[0] as &$v )
  79. {
  80. $v = str_replace(array('{', '}', '.DATA'), '', $v);
  81. }
  82. unset($v);
  83. $value['contents'] = $matches[0];
  84. $result['template_list'][$key]['content'] = str_replace(array("\n\n", "\n"), '<br />', $value['content']);
  85. }
  86. unset($value);
  87. return $result;
  88. }
  89. /**
  90. * @name 获取公众平台模板消息目前所属行业
  91. * @author
  92. * @return bool|mixed
  93. */
  94. public function getIndustry()
  95. {
  96. $http_result = $this->ihttp_request($this->getIndustryUrl());
  97. $result = @json_decode($http_result['content'], true);
  98. if (!is_array($result)) {
  99. return false;
  100. }
  101. if (!(empty($result['errcode']))) {
  102. return false;
  103. }
  104. return $result;
  105. }
  106. /**
  107. * @name 获取公众平台模板消息目前所属行业文本
  108. * @author
  109. * @param $industry
  110. * @return string
  111. */
  112. public function getIndustryText($industry)
  113. {
  114. $industrytext = '';
  115. if ($industry && is_array($industry)) {
  116. foreach ($industry as $item) {
  117. $industrytext .= $item['first_class'] . '/' . $item['second_class'] . '&nbsp;&nbsp;&nbsp;';
  118. }
  119. }
  120. return $industrytext;
  121. }
  122. private function commonReturn($result)
  123. {
  124. if (!is_array($result)) {
  125. return [
  126. 'status' => 0,
  127. 'msg' => '请求失败'
  128. ];
  129. }
  130. if (!(empty($result['errcode']))) {
  131. return [
  132. 'status' => 0,
  133. 'msg' => $result['errcode']
  134. ];
  135. }
  136. return [
  137. 'status' => 1,
  138. 'msg' => '成功'
  139. ];
  140. }
  141. private function getAccessToken()
  142. {
  143. $global_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->account->key . '&secret=' . $this->account->secret;
  144. $global_token = \Curl::to($global_access_token_url)
  145. ->asJsonResponse(true)
  146. ->get();
  147. if (isset($global_token['errcode']) && isset($global_token['errmsg'])) {
  148. throw new AppException($global_token['errmsg']);
  149. }
  150. return $global_token['access_token'];
  151. }
  152. private function getTmpUrl()
  153. {
  154. return 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=' . $this->getAccessToken();
  155. }
  156. private function delTmpUrl()
  157. {
  158. return 'https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=' . $this->getAccessToken();
  159. }
  160. private function getTmpListUrl()
  161. {
  162. return 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=' . $this->getAccessToken();
  163. }
  164. private function getIndustryUrl()
  165. {
  166. return 'https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=' . $this->getAccessToken();
  167. }
  168. private function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
  169. $urlset = parse_url($url);
  170. if (empty($urlset['path'])) {
  171. $urlset['path'] = '/';
  172. }
  173. if (!empty($urlset['query'])) {
  174. $urlset['query'] = "?{$urlset['query']}";
  175. }
  176. if (empty($urlset['port'])) {
  177. $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
  178. }
  179. if (strexists($url, 'https://') && !extension_loaded('openssl')) {
  180. if (!extension_loaded("openssl")) {
  181. message('请开启您PHP环境的openssl');
  182. }
  183. }
  184. if (function_exists('curl_init') && function_exists('curl_exec')) {
  185. $ch = curl_init();
  186. if (ver_compare(phpversion(), '5.6') >= 0) {
  187. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
  188. }
  189. if (!empty($extra['ip'])) {
  190. $extra['Host'] = $urlset['host'];
  191. $urlset['host'] = $extra['ip'];
  192. unset($extra['ip']);
  193. }
  194. curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
  195. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  196. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  197. curl_setopt($ch, CURLOPT_HEADER, 1);
  198. @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  199. if ($post) {
  200. if (is_array($post)) {
  201. $filepost = false;
  202. foreach ($post as $name => $value) {
  203. if ((is_string($value) && substr($value, 0, 1) == '@') || (class_exists('CURLFile') && $value instanceof CURLFile)) {
  204. $filepost = true;
  205. break;
  206. }
  207. }
  208. if (!$filepost) {
  209. $post = http_build_query($post);
  210. }
  211. }
  212. curl_setopt($ch, CURLOPT_POST, 1);
  213. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  214. }
  215. if (!empty($GLOBALS['_W']['config']['setting']['proxy'])) {
  216. $urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
  217. if (!empty($urls['host'])) {
  218. curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
  219. $proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
  220. if (!empty($urls['scheme']) && defined($proxytype)) {
  221. curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
  222. } else {
  223. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  224. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  225. }
  226. if (!empty($GLOBALS['_W']['config']['setting']['proxy']['auth'])) {
  227. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
  228. }
  229. }
  230. }
  231. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  232. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  233. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  234. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  235. curl_setopt($ch, CURLOPT_SSLVERSION, 1);
  236. if (defined('CURL_SSLVERSION_TLSv1')) {
  237. curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
  238. }
  239. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
  240. if (!empty($extra) && is_array($extra)) {
  241. $headers = array();
  242. foreach ($extra as $opt => $value) {
  243. if (strexists($opt, 'CURLOPT_')) {
  244. curl_setopt($ch, constant($opt), $value);
  245. } elseif (is_numeric($opt)) {
  246. curl_setopt($ch, $opt, $value);
  247. } else {
  248. $headers[] = "{$opt}: {$value}";
  249. }
  250. }
  251. if (!empty($headers)) {
  252. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  253. }
  254. }
  255. $data = curl_exec($ch);
  256. $status = curl_getinfo($ch);
  257. $errno = curl_errno($ch);
  258. $error = curl_error($ch);
  259. curl_close($ch);
  260. if ($errno || empty($data)) {
  261. return error(1, $error);
  262. } else {
  263. return $this->ihttp_response_parse($data);
  264. }
  265. }
  266. $method = empty($post) ? 'GET' : 'POST';
  267. $fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
  268. $fdata .= "Host: {$urlset['host']}\r\n";
  269. if (function_exists('gzdecode')) {
  270. $fdata .= "Accept-Encoding: gzip, deflate\r\n";
  271. }
  272. $fdata .= "Connection: close\r\n";
  273. if (!empty($extra) && is_array($extra)) {
  274. foreach ($extra as $opt => $value) {
  275. if (!strexists($opt, 'CURLOPT_')) {
  276. $fdata .= "{$opt}: {$value}\r\n";
  277. }
  278. }
  279. }
  280. $body = '';
  281. if ($post) {
  282. if (is_array($post)) {
  283. $body = http_build_query($post);
  284. } else {
  285. $body = urlencode($post);
  286. }
  287. $fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
  288. } else {
  289. $fdata .= "\r\n";
  290. }
  291. if ($urlset['scheme'] == 'https') {
  292. $fp = fsockopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
  293. } else {
  294. $fp = fsockopen($urlset['host'], $urlset['port'], $errno, $error);
  295. }
  296. stream_set_blocking($fp, true);
  297. stream_set_timeout($fp, $timeout);
  298. if (!$fp) {
  299. return error(1, $error);
  300. } else {
  301. fwrite($fp, $fdata);
  302. $content = '';
  303. while (!feof($fp))
  304. $content .= fgets($fp, 512);
  305. fclose($fp);
  306. return $this->ihttp_response_parse($content, true);
  307. }
  308. }
  309. private function ihttp_response_parse($data, $chunked = false) {
  310. $rlt = array();
  311. $headermeta = explode('HTTP/', $data);
  312. if (count($headermeta) > 2) {
  313. $data = 'HTTP/' . array_pop($headermeta);
  314. }
  315. $pos = strpos($data, "\r\n\r\n");
  316. $split1[0] = substr($data, 0, $pos);
  317. $split1[1] = substr($data, $pos + 4, strlen($data));
  318. $split2 = explode("\r\n", $split1[0], 2);
  319. preg_match('/^(\S+) (\S+) (\S+)$/', $split2[0], $matches);
  320. $rlt['code'] = $matches[2];
  321. $rlt['status'] = $matches[3];
  322. $rlt['responseline'] = $split2[0];
  323. $header = explode("\r\n", $split2[1]);
  324. $isgzip = false;
  325. $ischunk = false;
  326. foreach ($header as $v) {
  327. $pos = strpos($v, ':');
  328. $key = substr($v, 0, $pos);
  329. $value = trim(substr($v, $pos + 1));
  330. if (is_array($rlt['headers'][$key])) {
  331. $rlt['headers'][$key][] = $value;
  332. } elseif (!empty($rlt['headers'][$key])) {
  333. $temp = $rlt['headers'][$key];
  334. unset($rlt['headers'][$key]);
  335. $rlt['headers'][$key][] = $temp;
  336. $rlt['headers'][$key][] = $value;
  337. } else {
  338. $rlt['headers'][$key] = $value;
  339. }
  340. if(!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
  341. $isgzip = true;
  342. }
  343. if(!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
  344. $ischunk = true;
  345. }
  346. }
  347. if($chunked && $ischunk) {
  348. $rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
  349. } else {
  350. $rlt['content'] = $split1[1];
  351. }
  352. if($isgzip && function_exists('gzdecode')) {
  353. $rlt['content'] = gzdecode($rlt['content']);
  354. }
  355. $rlt['meta'] = $data;
  356. if($rlt['code'] == '100') {
  357. return ihttp_response_parse($rlt['content']);
  358. }
  359. return $rlt;
  360. }
  361. }