wxUtil.php 65 KB

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