wxUtil.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  1. <?php
  2. namespace common\components;
  3. use bizHd\wx\classes\WxBaseClass;
  4. use bizHd\wx\services\WxBaseService;
  5. use bizHd\wx\services\WxMiniBaseService;
  6. use common\services\xhMerchantExtendService;
  7. use Yii;
  8. use yii\helpers\Json;
  9. use linslin\yii2\curl;
  10. use common\services\xhWxOpenService;
  11. use common\services\xhMerchantService;
  12. /**
  13. * 微信和微信开放平台交互接口
  14. */
  15. class wxUtil
  16. {
  17. public $access_token;
  18. public function __construct($merchant = '')
  19. {
  20. $this->access_token = !empty($merchant) ? self::getAuthorizerAccessToken($merchant) : '';
  21. }
  22. //获取用户基本信息
  23. public static function userInfo($openId, $merchant, $isOpen = 0)
  24. {
  25. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  26. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openId";
  27. $curl = new curl\Curl();
  28. $result = $curl->get($url);
  29. $result = Json::decode($result);
  30. Yii::info('get user Info' . json_encode($result));
  31. if (isset($result['errcode']) == false) {
  32. $result['nickName'] = isset($result['nickname']) ? $result['nickname'] : '';
  33. return $result;
  34. }
  35. return [];
  36. }
  37. //创建开放平台帐号
  38. public static function createOpenAccount($appId, $merchant, $isOpen = 0)
  39. {
  40. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  41. $url = "https://api.weixin.qq.com/cgi-bin/open/create?access_token=" . $accessToken;
  42. $curl = new curl\Curl();
  43. $data = ['appid' => $appId];
  44. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  45. $result = Json::decode($result);
  46. return $result;
  47. }
  48. //绑定到开放平台
  49. public static function bindOpenAccount($appId, $openAppId, $merchant, $isMiniProgram, $isOpen = 0)
  50. {
  51. if ($isMiniProgram) {
  52. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  53. } else {
  54. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  55. }
  56. $url = 'https://api.weixin.qq.com/cgi-bin/open/bind?access_token=' . $accessToken;
  57. $curl = new curl\Curl();
  58. $data = ['appid' => $appId, 'open_appid' => $openAppId];
  59. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  60. $result = Json::decode($result);
  61. return $result;
  62. }
  63. //获取公众号、小程序绑定的开放平台帐号
  64. public static function getOpenAccount($appId, $merchant, $isMiniProgram, $isOpen = 0)
  65. {
  66. if ($isMiniProgram) {
  67. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  68. } else {
  69. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  70. }
  71. Yii::info('获取access token:' . $accessToken);
  72. $url = "https://api.weixin.qq.com/cgi-bin/open/get?access_token=" . $accessToken;
  73. $curl = new curl\Curl();
  74. $data = ['appid' => $appId];
  75. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  76. $result = Json::decode($result);
  77. return $result;
  78. }
  79. //解绑公众号绑定的平台 ssh 2019.9.15
  80. public static function unbindAccount($merchant, $isOpen = 0)
  81. {
  82. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  83. $url = "https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $accessToken;
  84. $curl = new curl\Curl();
  85. $openAppId = $merchant['openAppId'];
  86. $appId = $merchant['wxAppId'];
  87. $data = ['appid' => $appId, 'open_appid' => $openAppId];
  88. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  89. $result = Json::decode($result);
  90. return $result;
  91. }
  92. //解绑小程序绑定的平台 ssh 2019.9.15
  93. public static function unbindMiniProgram($merchant, $isOpen = 0)
  94. {
  95. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  96. $url = "https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $accessToken;
  97. $curl = new curl\Curl();
  98. $openAppId = $merchant['openAppId'];
  99. $appId = $merchant['miniAppId'];
  100. $data = ['appid' => $appId, 'open_appid' => $openAppId];
  101. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  102. $result = Json::decode($result);
  103. return $result;
  104. }
  105. public static function getSubscribeUserList($merchant, $nextOpenId = '')
  106. {
  107. $accessToken = self::getAuthorizerAccessToken($merchant);
  108. $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$accessToken&next_openid=$nextOpenId";
  109. $curl = new curl\Curl();
  110. $result = $curl->get($url);
  111. return Json::decode($result);
  112. }
  113. public static function batchGetUserInfo($merchant, $openIdList)
  114. {
  115. $accessToken = self::getAuthorizerAccessToken($merchant);
  116. $url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" . $accessToken;
  117. $format = [];
  118. foreach ($openIdList as $val) {
  119. $format[] = ['openid' => $val, 'lang' => "zh-CN"];
  120. }
  121. $newOpenIdList = ["user_list" => $format];
  122. $curl = new curl\Curl();
  123. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($newOpenIdList))->post($url);
  124. $result = Json::decode($result);
  125. return $result;
  126. }
  127. //查询所有分组
  128. public static function groupList($accessToken)
  129. {
  130. $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$accessToken";
  131. $curl = new curl\Curl();
  132. $result = $curl->get($url);
  133. $result = Json::decode($result);
  134. if (isset($result['errcode'])) {
  135. return null;
  136. } else {
  137. return $result;
  138. }
  139. }
  140. /**
  141. * 提交自定义菜单到微信平台
  142. */
  143. public function userMenuToWeiXin($menu)
  144. {
  145. $jsonData = urldecode(json_encode($menu, JSON_UNESCAPED_UNICODE));
  146. $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->access_token;
  147. $curl = new curl\Curl();
  148. $response = $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  149. return $response;
  150. }
  151. /**
  152. * 上传图片多媒体文件
  153. */
  154. public static function uploadImgMedia($merchant, $fullFile)
  155. {
  156. $access_token = self::getAuthorizerAccessToken($merchant);
  157. $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $access_token . "&type=image";
  158. $curl = curl_init();
  159. if (class_exists('\CURLFile')) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
  160. $data = array('media' => new \CURLFile($fullFile));
  161. } else {
  162. $data = array('media' => file_get_contents($fullFile));
  163. }
  164. if (class_exists('\CURLFile')) {
  165. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
  166. } else {
  167. if (defined('CURLOPT_SAFE_UPLOAD')) {
  168. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
  169. }
  170. }
  171. curl_setopt($curl, CURLOPT_URL, $url);
  172. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  173. curl_setopt($curl, CURLOPT_POST, true);
  174. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  175. $result = curl_exec($curl);
  176. curl_close($curl);
  177. return json_decode($result);
  178. }
  179. /**
  180. * 上传视频文件
  181. */
  182. public function uploadVideoMedia($merchant, $fullFile)
  183. {
  184. $access_token = self::getAuthorizerAccessToken($merchant);
  185. $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $access_token . "&type=video";
  186. $curl = curl_init();
  187. if (class_exists('\CURLFile')) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
  188. $data = array('media' => new \CURLFile($fullFile));
  189. } else {
  190. $data = array('media' => file_get_contents($fullFile));
  191. }
  192. if (class_exists('\CURLFile')) {
  193. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
  194. } else {
  195. if (defined('CURLOPT_SAFE_UPLOAD')) {
  196. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
  197. }
  198. }
  199. curl_setopt($curl, CURLOPT_URL, $url);
  200. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  201. curl_setopt($curl, CURLOPT_POST, true);
  202. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  203. $result = curl_exec($curl);
  204. curl_close($curl);
  205. return json_decode($result);
  206. }
  207. /**
  208. * 下载多媒体文件
  209. */
  210. public static function uploadMedia($media_id, $access_token)
  211. {
  212. $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' . $access_token . '&media_id=' . $media_id;
  213. $result = CurlUtil::httpsGet($url);
  214. if (isset($result['errcode'])) {
  215. return false;
  216. } else {
  217. return $result;
  218. }
  219. }
  220. /**
  221. * 获取素材总数
  222. * 图片和图文消息素材(包括单图文和多图文)的总数上限为5000,其他素材的总数上限为1000
  223. */
  224. public function getMaterialCount($merchant)
  225. {
  226. $token = self::getAuthorizerAccessToken($merchant);
  227. $url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token={$token}";
  228. $curl = new curl\Curl();
  229. $response = $curl->get($url);
  230. return $response;
  231. }
  232. /**
  233. * 获取素材列表 图文列表
  234. * $data = ['type' => 'image','offset' => 0,'count' => 100];
  235. * type:news image video voice
  236. */
  237. public function batchgetMaterial($merchant, $data)
  238. {
  239. $token = self::getAuthorizerAccessToken($merchant);
  240. $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={$token}";
  241. $curl = new curl\Curl();
  242. $response = $curl->setOption(CURLOPT_POSTFIELDS, json_encode($data))->post($url);
  243. return json_decode($response, true);
  244. }
  245. /**
  246. * 解除绑定删除自定义菜单
  247. */
  248. public static function menuDelete($merchant)
  249. {
  250. $token = self::getAuthorizerAccessToken($merchant);
  251. $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=$token";
  252. $curl = new curl\Curl();
  253. $response = $curl->get($url);
  254. return $response;
  255. }
  256. //微信api不支持中文转义的json结构
  257. static function json_encode($arr)
  258. {
  259. if (count($arr) == 0) return "[]";
  260. $parts = array();
  261. $is_list = false;
  262. //Find out if the given array is a numerical array
  263. $keys = array_keys($arr);
  264. $max_length = count($arr) - 1;
  265. if (($keys [0] === 0) && ($keys [$max_length] === $max_length)) { //See if the first key is 0 and last key is length - 1
  266. $is_list = true;
  267. for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position
  268. if ($i != $keys [$i]) { //A key fails at position check.
  269. $is_list = false; //It is an associative array.
  270. break;
  271. }
  272. }
  273. }
  274. foreach ($arr as $key => $value) {
  275. if (is_array($value)) { //Custom handling for arrays
  276. if ($is_list)
  277. $parts [] = self::json_encode($value); /* :RECURSION: */
  278. else
  279. $parts [] = '"' . $key . '":' . self::json_encode($value); /* :RECURSION: */
  280. } else {
  281. $str = '';
  282. if (!$is_list)
  283. $str = '"' . $key . '":';
  284. //Custom handling for multiple data types
  285. if (!is_string($value) && is_numeric($value) && $value < 2000000000)
  286. $str .= $value; //Numbers
  287. elseif ($value === false)
  288. $str .= 'false'; //The booleans
  289. elseif ($value === true)
  290. $str .= 'true';
  291. else
  292. $str .= '"' . addslashes($value) . '"'; //All other things
  293. $parts [] = $str;
  294. }
  295. }
  296. $json = implode(',', $parts);
  297. if ($is_list)
  298. return '[' . $json . ']'; //Return numerical JSON
  299. return '{' . $json . '}'; //Return associative JSON
  300. }
  301. /**
  302. * 创建临时二维码 ssh 2019.9.4
  303. */
  304. public static function qrcodeCreate($merchant, $sceneId, $expireSeconds = null)
  305. {
  306. $accessToken = self::getAuthorizerAccessToken($merchant);
  307. $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$accessToken";
  308. //有效期默认一天
  309. $expireSeconds = isset($expireSeconds) ? $expireSeconds : 86400;
  310. $post = array('expire_seconds' => $expireSeconds, 'action_name' => 'QR_STR_SCENE', "action_info" => array('scene' => array('scene_str' => $sceneId)));
  311. $curl = new curl\Curl();
  312. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  313. $result = Json::decode($result);
  314. return $result;
  315. }
  316. /**
  317. * 创建永久二维码
  318. */
  319. public static function qrcodePermanentCreate($merchant, $sceneId)
  320. {
  321. $accessToken = self::getAuthorizerAccessToken($merchant);
  322. $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$accessToken";
  323. $post = array('action_name' => 'QR_LIMIT_STR_SCENE', "action_info" => array('scene' => array('scene_str' => $sceneId)));
  324. $curl = new curl\Curl();
  325. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  326. $result = Json::decode($result);
  327. return $result;
  328. }
  329. /**
  330. * 微信授权获取code
  331. */
  332. public static function getCode($urlEncode, $merchant, $scope, $isOpen = 1)
  333. {
  334. $host = Yii::$app->request->getHostInfo();
  335. $REDIRECT_URI = $host . '/auth/get-user-info?url=' . $urlEncode . '&authScope=' . $scope;
  336. Yii::info($REDIRECT_URI);
  337. $appId = $merchant['wxAppId'];
  338. $open = [];
  339. if ($isOpen == 1) {
  340. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  341. }
  342. if ($isOpen == 2) {
  343. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  344. }
  345. if ($isOpen == 3) {
  346. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  347. }
  348. if (empty($open)) {
  349. util::fail('没有找到平台');
  350. }
  351. $component_app_id = $open['appId'];
  352. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appId . "&redirect_uri=" . urlencode($REDIRECT_URI) . "&response_type=code&scope=" . $scope . "&state=1&component_appid={$component_app_id}#wechat_redirect";
  353. header("Location:" . $url);
  354. //如果这里没有exit(),在apache服务器下无法实现跳转
  355. exit();
  356. }
  357. /**
  358. * 获取openId
  359. */
  360. public static function getOpenId($code, $merchant, $isOpen = 1)
  361. {
  362. $appId = $merchant['wxAppId'];
  363. $open = [];
  364. if ($isOpen == 1) {
  365. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  366. }
  367. if ($isOpen == 2) {
  368. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  369. }
  370. if ($isOpen == 3) {
  371. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  372. }
  373. if (empty($open)) {
  374. util::fail('没有找到平台');
  375. }
  376. $component_app_id = $open['appId'];
  377. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  378. $url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={$appId}&code={$code}&grant_type=authorization_code&component_appid={$component_app_id}&component_access_token={$componentAccessToken}";
  379. $curl = new curl\Curl();
  380. $result = $curl->get($url);
  381. $data = Json::decode($result);
  382. if (isset($data['openid']) == false) {
  383. Yii::warning('error:' . json_encode($data) . ' code:' . $code, __METHOD__);
  384. return false;
  385. }
  386. return $data;
  387. }
  388. /**
  389. * 授权获取自己的信息
  390. */
  391. public function authGetUserInfo($openid, $access_token)
  392. {
  393. $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
  394. $curl = new curl\Curl();
  395. $result = $curl->get($url);
  396. $data = Json::decode($result);
  397. $data['nickName'] = isset($data['nickname']) ? $data['nickname'] : '';
  398. return $data;
  399. }
  400. /**
  401. * 自动获取自己的信息(公众号的粉丝才能获取)
  402. */
  403. public static function autoGetUserInfo($openid, $merchant)
  404. {
  405. $access_token = self::getAuthorizerAccessToken($merchant);
  406. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
  407. $curl = new curl\Curl();
  408. $result = $curl->get($url);
  409. $data = Json::decode($result);
  410. return $data;
  411. }
  412. /**
  413. * 网址接入验证
  414. */
  415. public static function signatureValidation()
  416. {
  417. $signature = $_GET['signature'];
  418. $timestamp = $_GET['timestamp'];
  419. $nonce = $_GET['nonce'];
  420. $account = $_GET['account'];
  421. $merchant = xhMerchantService::getByAccount($account);
  422. if ($merchant) {
  423. $token = $merchant['wxToken'];
  424. // 3个数值组成数组验证
  425. $tmpArr = array(
  426. $token,
  427. $timestamp,
  428. $nonce
  429. );
  430. // 字典排序
  431. sort($tmpArr, SORT_STRING);
  432. $tmpStr = implode($tmpArr);
  433. // sha1加密
  434. $tmpStr = sha1($tmpStr);
  435. if ($signature == $tmpStr) {
  436. return true;
  437. } else {
  438. return false;
  439. }
  440. } else {
  441. return false;
  442. }
  443. }
  444. //客服接口发消息
  445. public static function sendMsg($content, $merchant, $openId, $isOpen = 0)
  446. {
  447. $token = self::getAuthorizerAccessToken($merchant, $isOpen);
  448. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
  449. $data = ['touser' => $openId, 'msgtype' => 'text', 'text' => ['content' => $content]];
  450. $curl = new curl\Curl();
  451. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  452. $result = Json::decode($result);
  453. return $result;
  454. }
  455. public static function sendImgMsg($mediaId, $merchant, $openId)
  456. {
  457. $token = self::getAuthorizerAccessToken($merchant);
  458. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
  459. $data = ['touser' => $openId, 'msgtype' => 'image', 'image' => ['media_id' => $mediaId]];
  460. $curl = new curl\Curl();
  461. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  462. $result = Json::decode($result);
  463. return $result;
  464. }
  465. public static function sendVideoMsg($mediaId, $merchant, $openId)
  466. {
  467. $token = self::getAuthorizerAccessToken($merchant);
  468. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
  469. $data = ['touser' => $openId, 'msgtype' => 'video', 'video' => ['media_id' => $mediaId,
  470. 'thumb_media_id' => $mediaId,
  471. 'title' => '因爱而生',
  472. 'description' => "情定原生,爱在今生;\n坐标:浙江,绍兴上虞;\n看到过一句话:“一个城市不过是几条巷道上,几间房子和几个人的组合。如果没有了这些,一个城市如同陨落,只剩下悲凉的记忆;”\n万事万物持续流变,珍爱的东西尤其不可能一直存在,如朝霞,如春花,如爱情;\n无论什么时候,不管天气好坏,都能拿出某些个让人喜欢的东西。",
  473. ]];
  474. $curl = new curl\Curl();
  475. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  476. $result = Json::decode($result);
  477. return $result;
  478. }
  479. /**
  480. * 消息模板,发送任务通知
  481. */
  482. public static function sendTaskInform($data, $merchant, $isOpen = 0)
  483. {
  484. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  485. $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}";
  486. $data = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  487. $curl = new curl\Curl();
  488. $response = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  489. $arr = json_decode($response);
  490. return $arr;
  491. }
  492. /**
  493. * 创建模板消息
  494. */
  495. public static function tMessageCreate($merchant, $shortTemplateId, $isOpen = 0)
  496. {
  497. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  498. $url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={$accessToken}";
  499. $post = array('template_id_short' => $shortTemplateId);
  500. $curl = new curl\Curl();
  501. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  502. $result = Json::decode($result);
  503. return $result;
  504. }
  505. /**
  506. * 删除模板消息
  507. */
  508. public static function delTMessage($merchant, $templateId)
  509. {
  510. $accessToken = self::getAuthorizerAccessToken($merchant);
  511. $url = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={$accessToken}";
  512. $post = array('template_id' => $templateId);
  513. $curl = new curl\Curl();
  514. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  515. $result = Json::decode($result);
  516. return $result;
  517. }
  518. /**
  519. * 取所有模板消息
  520. */
  521. public function getAllTMessage($merchant)
  522. {
  523. $accessToken = self::getAuthorizerAccessToken($merchant);
  524. $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={$accessToken}";
  525. $curl = new curl\Curl();
  526. $result = $curl->get($url);
  527. $result = Json::decode($result);
  528. return $result;
  529. }
  530. /**
  531. * 设置模板消息的行业
  532. */
  533. public function setTMIndustry($merchant, $industry_id1, $industry_id2)
  534. {
  535. $accessToken = self::getAuthorizerAccessToken($merchant);
  536. $url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={$accessToken}";
  537. $post = array('industry_id1' => $industry_id1, 'industry_id2' => $industry_id2);
  538. $curl = new curl\Curl();
  539. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  540. $result = Json::decode($result);
  541. return $result;
  542. }
  543. /**
  544. * 获取公众号的accessToken 公众号调用凭据
  545. */
  546. public static function getAuthorizerAccessToken($merchant, $isOpen = 0)
  547. {
  548. $sjId = $merchant['id'];
  549. $open = [];
  550. if ($isOpen == 1) {
  551. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  552. }
  553. if ($isOpen == 2) {
  554. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  555. }
  556. if ($isOpen == 3) {
  557. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  558. }
  559. if (empty($open)) {
  560. util::fail('没有找到平台信息');
  561. }
  562. $component_app_id = $open['appId'];
  563. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  564. $appId = $merchant['wxAppId'];
  565. $wxAccessToken = $merchant['wxAccessToken'];
  566. $wxAccessTokenTime = $merchant['wxAccessTokenTime'];
  567. $authorize_refresh_token = $merchant['wxRefreshToken'];
  568. $now = time();
  569. if ($now > strtotime($wxAccessTokenTime)) {
  570. $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}";
  571. $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $authorize_refresh_token];
  572. $curl = new curl\Curl();
  573. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  574. Yii::info('通过refresh_token获取access_token返回:' . $result);
  575. $result = Json::decode($result);
  576. if (isset($result['authorizer_access_token'])) {
  577. $wxAccessToken = $result['authorizer_access_token'];
  578. $expires_in = $result['expires_in'];
  579. $authorize_refresh_token = $result['authorizer_refresh_token'];
  580. $uData['wxRefreshToken'] = $authorize_refresh_token;;
  581. $uData['wxAccessToken'] = $wxAccessToken;
  582. $uData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  583. if (in_array($isOpen, [1, 2, 3])) {
  584. //零售、供货商和商城
  585. $wxBaseId = $open['wxBaseId'] ?? 0;
  586. if (!empty($wxBaseId)) {
  587. WxBaseService::updateById($wxBaseId, $uData);
  588. }
  589. } else {
  590. //其它
  591. xhMerchantService::updateById($sjId, $uData);
  592. }
  593. } else {
  594. noticeUtil::push("access_token已经失效,并且通过refresh_token没有获取到新的token isOpen:{$isOpen}", '15280215347');
  595. }
  596. }
  597. Yii::info('获取componentAccessToken 成功:' . $componentAccessToken);
  598. return $wxAccessToken;
  599. }
  600. /**
  601. * 获取小程序的accessToken
  602. */
  603. public static function getMiniProgramAccessToken($merchant, $isOpen = 0)
  604. {
  605. $sjId = isset($merchant['id']) ? $merchant['id'] : 0;
  606. $open = [];
  607. if ($isOpen == 1) {
  608. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  609. } elseif ($isOpen == 2) {
  610. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  611. } elseif ($isOpen == 3) {
  612. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  613. } else {
  614. util::fail('没有找到平台');
  615. }
  616. $component_app_id = $open['appId'];
  617. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  618. $appId = $merchant['miniAppId'];
  619. if ($isOpen == 1) {
  620. $miniAccessToken = $merchant['miniAccessToken'];
  621. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  622. $miniRefreshToken = $merchant['miniRefreshToken'];
  623. } elseif ($isOpen == 2) {
  624. $miniAccessToken = $merchant['miniAccessToken'];
  625. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  626. $miniRefreshToken = $merchant['miniRefreshToken'];
  627. } elseif ($isOpen == 3) {
  628. $miniAccessToken = $merchant['miniAccessToken'];
  629. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  630. $miniRefreshToken = $merchant['miniRefreshToken'];
  631. } else {
  632. $extend = xhMerchantExtendService::getBySjId($sjId);
  633. $miniAccessToken = $extend['miniAccessToken'];
  634. $miniAccessTokenTime = $extend['miniAccessTokenTime'];
  635. $miniRefreshToken = $extend['miniRefreshToken'];
  636. }
  637. $now = time();
  638. Yii::info("当前时间:{$now} 小程序accessToken过期时间:" . strtotime($miniAccessTokenTime) . " merchant:" . json_encode($merchant));
  639. if ($now > strtotime($miniAccessTokenTime)) {
  640. $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}";
  641. $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $miniRefreshToken];
  642. $curl = new curl\Curl();
  643. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  644. $result = Json::decode($result);
  645. Yii::info('重新获取mini accesstoken:' . json_encode($result));
  646. if (isset($result['authorizer_access_token'])) {
  647. $expires_in = $result['expires_in'];
  648. $miniAccessToken = $result['authorizer_access_token'];
  649. $uData['miniRefreshToken'] = $result['authorizer_refresh_token'];
  650. $uData['miniAccessToken'] = $miniAccessToken;
  651. $uData['miniAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  652. if ($isOpen == 1) {
  653. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  654. if (!empty($wxMiniBaseId)) {
  655. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  656. }
  657. } elseif ($isOpen == 2) {
  658. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  659. if (!empty($wxMiniBaseId)) {
  660. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  661. }
  662. } elseif ($isOpen == 3) {
  663. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  664. if (!empty($wxMiniBaseId)) {
  665. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  666. }
  667. } else {
  668. xhMerchantExtendService::updateBySjId($sjId, $uData);
  669. }
  670. return $miniAccessToken;
  671. }
  672. Yii::info('accessToken失效:sjId:' . $sjId);
  673. }
  674. Yii::info('有效小程序 accesstoken:' . $miniAccessToken);
  675. return $miniAccessToken;
  676. }
  677. public static function saveWeixinImg($userId, $url, $class = 0)
  678. {
  679. $className = [
  680. '0' => 'weixinUserAvatar',//微信头像
  681. '1' => 'weixinUserImg',//微信公众号二维码
  682. '2' => 'weixinMpQrcode',
  683. '3' => 'weixinMpAvatar',
  684. ];
  685. $folder = Yii::getAlias('@webroot') . '/../../images';
  686. $pre = '/' . $className[$class] . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  687. if (!file_exists($folder . $pre))
  688. mkdir($folder . $pre, 0777, true);
  689. $randString = stringUtil::buildOrderNo();
  690. $name = md5($userId . $randString) . '.jpg';
  691. $fullFileName = $folder . $pre . $name;
  692. $fileName = $pre . $name;
  693. $curl = new curl\Curl();
  694. $result = $curl->get($url);
  695. $fp2 = @fopen($fullFileName, 'a');//文件大小
  696. fwrite($fp2, $result);
  697. fclose($fp2);
  698. return $fileName;
  699. }
  700. /**
  701. * 下载学员作品图片
  702. */
  703. public static function downloadStudentWorksImg($merchant, $mediaId, $savePathType = 'wxUserImg')
  704. {
  705. $accessToken = self::getAuthorizerAccessToken($merchant);
  706. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}";
  707. $ch = curl_init($url);
  708. curl_setopt($ch, CURLOPT_HEADER, 0);
  709. curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。
  710. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  711. $body = curl_exec($ch);
  712. $httpinfo = curl_getinfo($ch);
  713. curl_close($ch);
  714. preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式
  715. $fileExt = $extmatches[1];
  716. $imgSavePath = dict::getDict('imgSavePath');
  717. $comImgSavePath = $imgSavePath[$savePathType];
  718. $folder = Yii::getAlias('@webroot') . '/../../images';
  719. $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  720. if (!file_exists($folder . $pre)) {
  721. mkdir($folder . $pre, 0777, true);
  722. }
  723. $randString = stringUtil::buildOrderNo();
  724. $fullFileName = $folder . $pre . $randString . '.jpg';
  725. $fileName = $pre . $randString . '.jpg';
  726. $fp2 = @fopen($fullFileName, 'a');//文件大小
  727. fwrite($fp2, $body);
  728. fclose($fp2);
  729. $srcImg = $fullFileName;
  730. $dstImg300 = $folder . $pre . $randString . "_300.jpg";//生成300px缩略图,不保存到数据库
  731. util::img2thumb($srcImg, $dstImg300, $width = 300, 0, 0, 0);
  732. $dstImg100 = $folder . $pre . $randString . "_100.jpg";//生成50px缩略图,不保存到数据库
  733. util::img2thumb($srcImg, $dstImg100, $width = 100, 0, 0, 0);
  734. return $fileName;
  735. }
  736. /**
  737. * 获取media_id里的图片保存到服务器
  738. */
  739. public static function downloadmediaIdImg($merchant, $mediaId, $savePathType = 'wxUserImg')
  740. {
  741. $accessToken = self::getAuthorizerAccessToken($merchant);
  742. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}";
  743. $ch = curl_init($url);
  744. curl_setopt($ch, CURLOPT_HEADER, 0);
  745. curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。
  746. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  747. $body = curl_exec($ch);
  748. $httpinfo = curl_getinfo($ch);
  749. curl_close($ch);
  750. preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式
  751. $fileExt = $extmatches[1];
  752. $imgSavePath = dict::getDict('imgSavePath');
  753. $comImgSavePath = $imgSavePath[$savePathType];
  754. $folder = Yii::getAlias('@webroot') . '/../../images';
  755. $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  756. if (!file_exists($folder . $pre)) {
  757. mkdir($folder . $pre, 0777, true);
  758. }
  759. $randString = stringUtil::buildOrderNo();
  760. $fullFileName = $folder . $pre . $randString . '.jpg';
  761. $fileName = $pre . $randString . '.jpg';
  762. $fp2 = @fopen($fullFileName, 'a');//文件大小
  763. fwrite($fp2, $body);
  764. fclose($fp2);
  765. $srcImg = $fullFileName;
  766. $mediumImg = $pre . $randString . "_200.jpg";
  767. $dstImg200 = $folder . $mediumImg;//生成200px缩略图,不保存到数据库
  768. util::img2thumb($srcImg, $dstImg200, $width = 200, 0, 0, 0);
  769. $smallImg = $pre . $randString . "_50.jpg";
  770. $dstImg50 = $folder . $smallImg;//生成50px缩略图,不保存到数据库
  771. util::img2thumb($srcImg, $dstImg50, $width = 50, 0, 0, 0);
  772. return ['large' => $fileName, 'medium' => $mediumImg, 'small' => $smallImg];
  773. }
  774. public static function createTag($merchant, $name)
  775. {
  776. $accessToken = self::getAuthorizerAccessToken($merchant);
  777. $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token={$accessToken}";
  778. $post = ['tag' => ['name' => $name]];
  779. $curl = new curl\Curl();
  780. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  781. $result = Json::decode($result);
  782. return $result;
  783. }
  784. public static function delTag($merchant, $id)
  785. {
  786. $accessToken = self::getAuthorizerAccessToken($merchant);
  787. $url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={$accessToken}";
  788. $post = ['tag' => ['id' => $id]];
  789. $curl = new curl\Curl();
  790. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  791. $result = Json::decode($result);
  792. return $result;
  793. }
  794. public static function modTag($merchant, $id, $name)
  795. {
  796. $accessToken = self::getAuthorizerAccessToken($merchant);
  797. $url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token={$accessToken}";
  798. $post = ['tag' => ['id' => $id, 'name' => $name]];
  799. $curl = new curl\Curl();
  800. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  801. $result = Json::decode($result);
  802. return $result;
  803. }
  804. /**
  805. * 获取商家所有标签
  806. */
  807. public static function getTag($merchant)
  808. {
  809. $accessToken = self::getAuthorizerAccessToken($merchant);
  810. $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$accessToken}";
  811. $curl = new curl\Curl();
  812. $result = $curl->get($url);
  813. $result = Json::decode($result);
  814. return $result;
  815. }
  816. public function getUserTag($tagId, $nextOpenId = '')
  817. {
  818. $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" . $this->access_token;
  819. $post = ['tagid' => $tagId, 'next_openid' => $nextOpenId];
  820. $curl = new curl\Curl();
  821. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  822. $result = Json::decode($result);
  823. return $result;
  824. }
  825. /**
  826. * 批量为用户打标签
  827. */
  828. public static function membersBatchTag($merchant, $openIdList, $tagId)
  829. {
  830. $accessToken = self::getAuthorizerAccessToken($merchant);
  831. $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={$accessToken}";
  832. $post = ['openid_list' => $openIdList, 'tagid' => $tagId];
  833. $curl = new curl\Curl();
  834. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  835. $result = Json::decode($result);
  836. return $result;
  837. }
  838. /**
  839. * 批量取消用户标签
  840. */
  841. public static function membersCancelTag($merchant, $openIdList, $tagId)
  842. {
  843. $accessToken = self::getAuthorizerAccessToken($merchant);
  844. $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={$accessToken}";
  845. $post = ['openid_list' => $openIdList, 'tagid' => $tagId];
  846. $curl = new curl\Curl();
  847. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  848. $result = Json::decode($result);
  849. return $result;
  850. }
  851. /**
  852. * 新增临时素材
  853. */
  854. public static function uploadTempMedia($merchant, $imgUrl, $type = 'image')
  855. {
  856. $accessToken = self::getAuthorizerAccessToken($merchant);
  857. $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accessToken}&type=" . $type;
  858. $postData = ['media' => '@' . $imgUrl];
  859. $ch = curl_init();
  860. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
  861. curl_setopt($ch, CURLOPT_URL, $url);
  862. curl_setopt($ch, CURLOPT_POST, 1);
  863. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  864. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  865. $response = curl_exec($ch);
  866. $result = Json::decode($response);
  867. return $result;
  868. }
  869. /**
  870. * 获取临时素材
  871. */
  872. public static function getTempMaterial($merchant, $mediaId)
  873. {
  874. $accessToken = self::getAuthorizerAccessToken($merchant);
  875. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id=" . $mediaId;
  876. $fileInfo = self::getTempMaterialInfo($url);
  877. if (empty($fileInfo) || isset($fileInfo['errcode'])) {
  878. $msg = '未错误哦~';
  879. return ['code' => 'A0002', 'msg' => $msg];
  880. }
  881. $fileName = substr(md5($mediaId), -4) . stringUtil::buildOrderNo() . '.amr';
  882. $preFolder = Yii::getAlias('@webroot') . '/../../images';
  883. $folder = '/weixinChatVoice/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  884. if (!file_exists($preFolder . $folder))
  885. mkdir($preFolder . $folder, 0777, true);
  886. $saveFile = $preFolder . $folder . $fileName;
  887. if (file_exists($saveFile) == false) {
  888. self::readTempMaterial($saveFile, $fileInfo["body"]);
  889. }
  890. return ['code' => 'A0001', 'msg' => 'success', 'data' => ['url' => $folder . $fileName]];
  891. }
  892. /**
  893. * 获取临时素材的头信息等
  894. */
  895. public static function getTempMaterialInfo($url)
  896. {
  897. $ch = curl_init($url);
  898. curl_setopt($ch, CURLOPT_HEADER, 0);
  899. curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头
  900. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  901. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  902. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  903. $package = curl_exec($ch);
  904. $httpinfo = curl_getinfo($ch);
  905. curl_close($ch);
  906. $imageAll = ['header' => $httpinfo, 'body' => $package];
  907. return $imageAll;
  908. }
  909. /**
  910. * 读取临时素材的资源
  911. */
  912. function readTempMaterial($filename, $fileContent)
  913. {
  914. $localFile = fopen($filename, 'w');
  915. if (false !== $localFile) {
  916. if (false !== fwrite($localFile, $fileContent)) {
  917. fclose($localFile);
  918. }
  919. }
  920. }
  921. /**
  922. * 创建门店
  923. */
  924. public function createStore($info)
  925. {
  926. $jsonData = urldecode(json_encode($info, JSON_UNESCAPED_UNICODE));
  927. $url = "http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=" . $this->access_token;
  928. $curl = new curl\Curl();
  929. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  930. }
  931. /**
  932. * 查询门店信息
  933. */
  934. public function getStoreInfo($poi_id)
  935. {
  936. $data = ['poi_id' => $poi_id];
  937. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  938. $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoi?access_token=" . $this->access_token;
  939. $curl = new curl\Curl();
  940. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  941. }
  942. /**
  943. * 查询门店列表
  944. */
  945. public function getStoreList($begin = 0, $count = 20)
  946. {
  947. $data = ["begin" => $begin, "limit" => $count];
  948. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  949. $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token;
  950. $curl = new curl\Curl();
  951. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  952. }
  953. /**
  954. * 查询门店列表 -- 重复 可删除
  955. */
  956. function getShopList($data)
  957. {
  958. $url = "https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token;
  959. $curl = new curl\Curl();
  960. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  961. $result = Json::decode($result);
  962. return $result;
  963. }
  964. /**
  965. * 修改门店服务信息
  966. */
  967. public function updateStore(array $buffer)
  968. {
  969. $jsonData = urldecode(json_encode($buffer, JSON_UNESCAPED_UNICODE));
  970. $url = "http://api.weixin.qq.com/cgi-bin/poi/updatepoi?access_token=" . $this->access_token;
  971. $curl = new curl\Curl();
  972. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  973. }
  974. /**
  975. * 删除门店
  976. */
  977. public function delStore($poi_id)
  978. {
  979. $data = ['poi_id' => $poi_id];
  980. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  981. $url = "http://api.weixin.qq.com/cgi-bin/poi/delpoi?access_token=" . $this->access_token;
  982. $curl = new curl\Curl();
  983. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  984. }
  985. /**
  986. * 门店类目表
  987. */
  988. public function storeTypeList()
  989. {
  990. $url = "http://api.weixin.qq.com/cgi-bin/poi/getwxcategory?access_token=" . $this->access_token;
  991. $curl = new curl\Curl();
  992. return $curl->get($url);
  993. }
  994. /******************************* wifi *************************************/
  995. /**
  996. * 获取wifi门店列表
  997. */
  998. function getShopWifiList($pageindex = 1, $pagesize = 10)
  999. {
  1000. $data = ["pageindex" => $pageindex, "pagesize" => $pagesize];
  1001. $url = "https://api.weixin.qq.com/bizwifi/shop/list?access_token=" . $this->access_token;
  1002. $curl = new curl\Curl();
  1003. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1004. $result = Json::decode($result);
  1005. return $result;
  1006. }
  1007. /**
  1008. * 添加密码型设备
  1009. */
  1010. function addPasswordDevice($shopId, $ssid, $pwd)
  1011. {
  1012. $data = ["shop_id" => $shopId, "ssid" => $ssid, "password" => $pwd];
  1013. $url = "https://api.weixin.qq.com/bizwifi/device/add?access_token=" . $this->access_token;
  1014. $curl = new curl\Curl();
  1015. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1016. $result = Json::decode($result);
  1017. return $result;
  1018. }
  1019. /**
  1020. * 修改门店Wi-Fi(修改门店网络信息)
  1021. */
  1022. function updateDevice($shopId, $oldSsid, $ssid, $pwd = '')
  1023. {
  1024. $data = ["shop_id" => $shopId, "old_ssid" => $oldSsid, "ssid" => $ssid];
  1025. if (!empty($pwd)) {
  1026. $data["password"] = $pwd;
  1027. }
  1028. $url = "https://api.weixin.qq.com/bizwifi/shop/update?access_token=" . $this->access_token;
  1029. $curl = new curl\Curl();
  1030. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1031. $result = Json::decode($result);
  1032. return $result;
  1033. }
  1034. /**
  1035. * 删除密码型设备
  1036. */
  1037. function delPasswordDevice($bssid)
  1038. {
  1039. $data = ["bssid" => $bssid];
  1040. $url = "https://api.weixin.qq.com/bizwifi/device/delete?access_token=" . $this->access_token;
  1041. $curl = new curl\Curl();
  1042. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1043. $result = Json::decode($result);
  1044. return $result;
  1045. }
  1046. /**
  1047. * 查询门店Wi-Fi信息
  1048. */
  1049. function getShopWifi($shopId)
  1050. {
  1051. $data = ["shop_id" => $shopId];
  1052. $url = "https://api.weixin.qq.com/bizwifi/shop/get?access_token=" . $this->access_token;
  1053. $curl = new curl\Curl();
  1054. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1055. $result = Json::decode($result);
  1056. return $result;
  1057. }
  1058. /**
  1059. * 获取物料二维码
  1060. */
  1061. function getWifiQrCode($shopId, $ssid, $img_id)
  1062. {
  1063. //$data = ["shop_id" => 429620, "ssid" => "WX567", "img_id" => $img_id];
  1064. $data = ["shop_id" => $shopId, "ssid" => $ssid, "img_id" => $img_id];
  1065. $url = "https://api.weixin.qq.com/bizwifi/qrcode/get?access_token=" . $this->access_token;
  1066. $curl = new curl\Curl();
  1067. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1068. $result = Json::decode($result);
  1069. return $result;
  1070. }
  1071. function getWifiUrl()
  1072. {
  1073. $url = "https://api.weixin.qq.com/bizwifi/account/get_connecturl?access_token=" . $this->access_token;
  1074. $curl = new curl\Curl();
  1075. $result = $curl->get($url);
  1076. $result = Json::decode($result);
  1077. return $result;
  1078. }
  1079. function generateShortUrl($longUrl)
  1080. {
  1081. $data = ["action" => "long2short", "long_url" => $longUrl,];
  1082. $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $this->access_token;
  1083. $curl = new curl\Curl();
  1084. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1085. $result = Json::decode($result);
  1086. if (isset($result['errcode']) && $result['errcode'] == 0) {
  1087. return ['code' => 'A0001', 'data' => ['shortUrl' => $result['short_url']]];
  1088. }
  1089. return ['code' => 'A0002', 'data' => []];
  1090. }
  1091. //长链接转短链接 ssh 2019.9.26
  1092. public static function urlLongToShort($longUrl, $merchant)
  1093. {
  1094. $accessToken = self::getMiniProgramAccessToken($merchant);
  1095. $data = ["action" => "long2short", "long_url" => $longUrl,];
  1096. $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $accessToken;
  1097. $curl = new curl\Curl();
  1098. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1099. $result = Json::decode($result);
  1100. $url = '';
  1101. if (isset($result['errcode']) && $result['errcode'] == 0) {
  1102. $url = $result['short_url'];
  1103. }
  1104. return ['url' => $url];
  1105. }
  1106. /**
  1107. * 拉取门店所有的设备信息
  1108. */
  1109. public function getShopWifiListAll()
  1110. {
  1111. $startPage = 1;
  1112. $list = [];
  1113. while (true) {
  1114. $reList = $this->getShopWifiList($startPage, 20);
  1115. if ($startPage <= $reList['data']['pagecount']) {
  1116. $list = array_merge($list, $reList['data']['records']);
  1117. ++$startPage;
  1118. } else {
  1119. break;
  1120. }
  1121. }
  1122. return $list;
  1123. }
  1124. /**
  1125. * 通过 poi_id 从Wi-Fi门店列表中 获取 shopId
  1126. */
  1127. public function getShopId($poiId, $list = [])
  1128. {
  1129. if (empty($list)) {
  1130. $list = $this->getShopWifiListAll();
  1131. }
  1132. foreach ($list as $shop) {
  1133. if ($shop['poi_id'] == $poiId)
  1134. return (string)$shop['shop_id'];
  1135. }
  1136. return false;
  1137. }
  1138. //设置小程序服务器域名
  1139. public static function setDomain($merchant, $isOpen = 0)
  1140. {
  1141. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1142. $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token=" . $accessToken;
  1143. $curl = new curl\Curl();
  1144. //零售
  1145. $currentHost = Yii::$app->params['hdHost'];
  1146. if ($isOpen == 2) {
  1147. //供货商
  1148. $currentHost = Yii::$app->params['ghsHost'];
  1149. }
  1150. if ($isOpen == 3) {
  1151. //供货商
  1152. $currentHost = Yii::$app->params['mallHost'];
  1153. }
  1154. $has = strpos($currentHost, 'https');
  1155. //如果不是https则换成https
  1156. if ($has === false) {
  1157. $currentHost = str_replace('http', 'https', $currentHost);
  1158. }
  1159. $socket = str_replace("https", "", $currentHost);
  1160. $socket = str_replace("http", "", $socket);
  1161. $data = [
  1162. "action" => "set",
  1163. "requestdomain" => [$currentHost],
  1164. "wsrequestdomain" => ['wss' . $socket],
  1165. "uploaddomain" => [$currentHost],
  1166. "downloaddomain" => [$currentHost],
  1167. ];
  1168. print_r($data);
  1169. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1170. $respond = Json::decode($result);
  1171. print_r($respond);
  1172. }
  1173. //设置业务域名
  1174. public static function setWebViewDomain($merchant, $isOpen = 0)
  1175. {
  1176. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1177. $url = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" . $accessToken;
  1178. $curl = new curl\Curl();
  1179. //零售
  1180. $currentHost = Yii::$app->params['hdHost'];
  1181. if ($isOpen == 2) {
  1182. //供货商
  1183. $currentHost = Yii::$app->params['ghsHost'];
  1184. }
  1185. if ($isOpen == 3) {
  1186. //供货商
  1187. $currentHost = Yii::$app->params['mallHost'];
  1188. }
  1189. $has = strpos($currentHost, 'https');
  1190. //如果不是https则换成https
  1191. if ($has === false) {
  1192. $currentHost = str_replace('http', 'https', $currentHost);
  1193. }
  1194. $data = [
  1195. "action" => "set",
  1196. "webviewdomain" => [$currentHost],
  1197. ];
  1198. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1199. $respond = Json::decode($result);
  1200. print_r($respond);
  1201. }
  1202. //为授权的小程序帐号上传小程序代码
  1203. public static function miniCommit($merchant, $templateId, $isOpen = 0)
  1204. {
  1205. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1206. $url = 'https://api.weixin.qq.com/wxa/commit?access_token=' . $accessToken;
  1207. $curl = new curl\Curl();
  1208. $apiUrl = Yii::$app->params['mallHost'];
  1209. if ($isOpen == 1) {
  1210. $apiUrl = Yii::$app->params['hdHost'];
  1211. } elseif ($isOpen == 2) {
  1212. $apiUrl = Yii::$app->params['ghsHost'];
  1213. } elseif ($isOpen == 3) {
  1214. $apiUrl = Yii::$app->params['mallHost'];
  1215. }
  1216. $imgUrl = imgUtil::getPrefix();
  1217. //如果不是https则换成https
  1218. $has = strpos($apiUrl, 'https');
  1219. if ($has === false) {
  1220. $apiUrl = str_replace('http', 'https', $apiUrl);
  1221. }
  1222. $open = [];
  1223. if ($isOpen == 1) {
  1224. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  1225. }
  1226. if ($isOpen == 2) {
  1227. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  1228. }
  1229. if ($isOpen == 3) {
  1230. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  1231. }
  1232. if (empty($open)) {
  1233. util::fail('没有找到平台');
  1234. }
  1235. //如果不是https则换成https
  1236. $has = strpos($imgUrl, 'https');
  1237. if ($has === false) {
  1238. $imgUrl = str_replace('http', 'https', $imgUrl);
  1239. }
  1240. $account = isset($merchant['id']) ? $merchant['id'] : 0;
  1241. $name = isset($merchant['name']) ? $merchant['name'] : '';
  1242. if ($isOpen == 1) {
  1243. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1244. $wxBase = WxBaseClass::getById($wxBaseId);
  1245. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1246. } elseif ($isOpen == 2) {
  1247. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1248. $wxBase = WxBaseClass::getById($wxBaseId);
  1249. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1250. } elseif ($isOpen == 3) {
  1251. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1252. $wxBase = WxBaseClass::getById($wxBaseId);
  1253. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1254. }
  1255. $ext = [
  1256. 'extAppid' => $merchant['miniAppId'],
  1257. 'ext' => [
  1258. 'account' => $account,
  1259. 'apiHost' => $apiUrl,
  1260. 'imgHost' => $imgUrl,
  1261. 'name' => $name,
  1262. ],
  1263. ];
  1264. echo '<pre>';
  1265. print_r($ext);
  1266. Yii::info("ext:" . json_encode($ext));
  1267. $extJson = json_encode($ext);
  1268. $data = [
  1269. "template_id" => $templateId,
  1270. "ext_json" => $extJson,
  1271. "user_version" => date("mdHis"),
  1272. "user_desc" => date("mdHis")
  1273. ];
  1274. print_r($data);
  1275. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1276. $respond = Json::decode($result);
  1277. print_r($respond);
  1278. }
  1279. //获取体验小程序的体验二维码
  1280. public static function getExperienceQrCode($merchant, $page, $isOpen = 0)
  1281. {
  1282. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1283. $path = urlencode($page);
  1284. $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$accessToken}&path=" . $path;
  1285. $curl = new curl\Curl();
  1286. $result = $curl->get($url);
  1287. $file = dirUtil::getImgDir() . 'retail/miniExperience/' . $merchant['id'] . '.jpg';
  1288. file_put_contents($file, $result);
  1289. //上传oss
  1290. $obj = 'retail/miniExperience/' . $merchant['id'] . '.jpg';
  1291. oss::uploadImage($obj, $file);
  1292. echo "<b /><img src='" . imgUtil::getPrefix() . "/retail/miniExperience/" . $merchant['id'] . ".jpg' />";
  1293. }
  1294. //获取授权小程序帐号已设置的类目
  1295. public static function getMiniCategory($merchant, $isOpen = 0)
  1296. {
  1297. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1298. $url = "https://api.weixin.qq.com/wxa/get_category?access_token=" . $accessToken;
  1299. $curl = new curl\Curl();
  1300. $result = $curl->get($url);
  1301. $respond = Json::decode($result);
  1302. echo "<pre>";
  1303. print_r($respond);
  1304. }
  1305. //小程序加急审核 ssh 2020.4.20
  1306. public static function speedupAudit($merchant, $id, $isOpen = 0)
  1307. {
  1308. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1309. $url = "https://api.weixin.qq.com/wxa/speedupaudit?access_token=" . $accessToken;
  1310. $curl = new curl\Curl();
  1311. $data = [
  1312. "auditid" => $id
  1313. ];
  1314. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1315. $respond = Json::decode($result);
  1316. print_r($respond);
  1317. }
  1318. //获取小程序的第三方提交代码的页面配置
  1319. public static function getMiniPage($merchant, $isOpen = 0)
  1320. {
  1321. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1322. $url = "https://api.weixin.qq.com/wxa/get_page?access_token=" . $accessToken;
  1323. $curl = new curl\Curl();
  1324. $result = $curl->get($url);
  1325. $respond = Json::decode($result);
  1326. echo "<pre>";
  1327. print_r($respond);
  1328. }
  1329. //将第三方提交的代码包提交审核
  1330. public static function miniSubmitAudit($merchant, $page, $isOpen = 0)
  1331. {
  1332. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1333. $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token=" . $accessToken;
  1334. $curl = new curl\Curl();
  1335. $data = [
  1336. "item_list" => [
  1337. [
  1338. "address" => $page,
  1339. "tag" => "花卉宝 花店",
  1340. "first_class" => "IT科技",
  1341. "second_class" => "软件服务提供商",
  1342. "first_id" => 210,
  1343. "second_id" => 413,
  1344. "title" => "花卉宝",
  1345. ],
  1346. ],
  1347. "feedback_info" => "",
  1348. "feedback_stuff" => "",
  1349. "version_desc" => "右上角若有【体验】二字,点击可登陆后台体验",
  1350. ];
  1351. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1352. $respond = Json::decode($result);
  1353. echo "<pre>";
  1354. print_r($respond);
  1355. }
  1356. //查询最新一次提交的审核状态
  1357. public static function miniGetLatestAuditStatus($merchant, $isOpen = 0)
  1358. {
  1359. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1360. $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $accessToken;
  1361. $curl = new curl\Curl();
  1362. $result = $curl->get($url);
  1363. $respond = Json::decode($result);
  1364. echo "<pre>";
  1365. print_r($respond);
  1366. }
  1367. //发布已通过审核的小程序
  1368. public static function miniRelease($merchant, $isOpen = 0)
  1369. {
  1370. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1371. $url = "https://api.weixin.qq.com/wxa/release?access_token=" . $accessToken;
  1372. $curl = new curl\Curl();
  1373. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1374. $respond = Json::decode($result);
  1375. return $respond;
  1376. }
  1377. //撤回审核
  1378. public static function rollbackCheck($merchant, $isOpen = 0)
  1379. {
  1380. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1381. $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $accessToken;
  1382. $curl = new curl\Curl();
  1383. $result = $curl->get($url);
  1384. $respond = Json::decode($result);
  1385. echo "<pre>";
  1386. print_r($respond);
  1387. }
  1388. //申请会员的小程序码
  1389. public static function generateMemberCode($merchant, $shopId, $isOpen = 0)
  1390. {
  1391. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1392. $behind = 'retail/mimiMemberCode/';
  1393. $filePath = dirUtil::getImgDir() . $behind;
  1394. if (!file_exists($filePath)) {
  1395. mkdir($filePath, 0777, true);
  1396. }
  1397. $file = $filePath . $fileName;
  1398. if (file_exists($file)) {
  1399. return $behind . $fileName;
  1400. }
  1401. $path = 'pages/home/user?scan=1&shopId=' . $shopId;
  1402. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1403. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1404. $curl = new curl\Curl();
  1405. $data = [
  1406. "path" => $path,
  1407. "width" => 1000,
  1408. ];
  1409. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1410. file_put_contents($file, $result);
  1411. return $behind . $fileName;
  1412. }
  1413. //收款小程序码
  1414. public static function generateGatheringMiniCode($merchant, $shopId, $isOpen = 0)
  1415. {
  1416. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1417. $behind = 'retail/gatheringMimiCode/';
  1418. $filePath = dirUtil::getImgDir() . $behind;
  1419. if (!file_exists($filePath)) {
  1420. mkdir($filePath, 0777, true);
  1421. }
  1422. $file = $filePath . $fileName;
  1423. if (file_exists($file)) {
  1424. return $behind . $fileName;
  1425. }
  1426. $path = 'pages/pay/index?scan=1&shopId=' . $shopId;
  1427. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1428. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1429. $curl = new curl\Curl();
  1430. $data = [
  1431. "path" => $path,
  1432. "width" => 1000,
  1433. ];
  1434. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1435. file_put_contents($file, $result);
  1436. return $behind . $fileName;
  1437. }
  1438. //微信开放平台获取component_access_token
  1439. public static function getComponentAccessToken($open)
  1440. {
  1441. $id = $open['id'];
  1442. $componentAccessToken = $open['componentAccessToken'];
  1443. $componentAccessTokenTime = $open['componentAccessTokenTime'];
  1444. $now = time();
  1445. if ($now > strtotime($componentAccessTokenTime)) {
  1446. $appId = $open['appId'];
  1447. $appSecret = $open['appSecret'];
  1448. $verifyTicket = $open['verifyTicket'];
  1449. $data = ['component_appid' => $appId, 'component_appsecret' => $appSecret, 'component_verify_ticket' => $verifyTicket];
  1450. $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  1451. $curl = new curl\Curl();
  1452. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1453. if (empty($result)) {
  1454. util::stop('没有取到ComponentAccessToken');
  1455. }
  1456. $result = Json::decode($result);
  1457. if (isset($result['component_access_token']) == false || empty($result['component_access_token'])) {
  1458. echo '<pre>';
  1459. print_r($result);
  1460. Yii::info('get component access token error:' . json_encode($result));
  1461. Yii::$app->end();
  1462. }
  1463. $component_access_token = $result['component_access_token'];
  1464. $expiresIn = $result['expires_in'];
  1465. $oData = [];
  1466. $oData['componentAccessToken'] = $component_access_token;
  1467. $oData['componentAccessTokenTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短
  1468. xhWxOpenService::updateById($id, $oData);
  1469. return $component_access_token;
  1470. } else {
  1471. return $componentAccessToken;
  1472. }
  1473. }
  1474. /**
  1475. * 微信开放平台获取预授权码pre_auth_code
  1476. */
  1477. public static function getPreAuthCode($open)
  1478. {
  1479. $id = $open['id'];
  1480. $preAuthCode = $open['preAuthCode'];
  1481. $preAuthCodeTime = $open['preAuthCodeTime'];
  1482. $now = time();
  1483. if ($now > strtotime($preAuthCodeTime)) {
  1484. $token = self::getComponentAccessToken($open);
  1485. $appId = $open['appId'];
  1486. $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
  1487. $curl = new curl\Curl();
  1488. $data = ['component_appid' => $appId];
  1489. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1490. $result = Json::decode($result);
  1491. Yii::info($result);
  1492. if (isset($result['pre_auth_code']) == false || empty($result['pre_auth_code'])) {
  1493. echo "没有取到pre_auth_code,原因:" . json_encode($result) . " appid:" . $appId . " token:" . $token;
  1494. Yii::$app->end();
  1495. }
  1496. $preAuthCode = $result['pre_auth_code'];
  1497. $expiresIn = $result['expires_in'];
  1498. $oData = [];
  1499. $oData['preAuthCode'] = $preAuthCode;
  1500. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短100秒
  1501. xhWxOpenService::updateById($id, $oData);
  1502. return $preAuthCode;
  1503. } else {
  1504. return $preAuthCode;
  1505. }
  1506. }
  1507. /**
  1508. * 微信开放平台使用授权码换取公众号的接口调用凭据和授权信息
  1509. */
  1510. public static function getAuthorizer($code, $open)
  1511. {
  1512. $appId = $open['appId'];
  1513. $accessToken = self::getComponentAccessToken($open);
  1514. $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$accessToken}";
  1515. $curl = new curl\Curl();
  1516. $data = ['authorization_code' => $code, 'component_appid' => $appId];
  1517. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1518. $result = Json::decode($result);
  1519. return $result;
  1520. }
  1521. //微信开放平台获取授权方的公众号帐号基本信息 ssh 2020.3.11
  1522. public static function getAuthorizerInfo($authorizeAppId, $open)
  1523. {
  1524. $appId = $open['appId'];
  1525. $accessToken = self::getComponentAccessToken($open);
  1526. $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$accessToken}";
  1527. $curl = new curl\Curl();
  1528. $data = ['component_appid' => $appId, 'authorizer_appid' => $authorizeAppId];
  1529. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1530. $result = Json::decode($result);
  1531. return $result;
  1532. }
  1533. }