wxUtil.php 65 KB

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