wxUtil.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  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("world","Peter",$currentHost);
  1187. $data = [
  1188. "action" => "set",
  1189. "requestdomain" => [$currentHost],
  1190. "wsrequestdomain" => ['ws://api.ghs.huaml.com'],
  1191. "uploaddomain" => [$currentHost],
  1192. "downloaddomain" => [$currentHost],
  1193. ];
  1194. print_r($data);
  1195. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1196. $respond = Json::decode($result);
  1197. print_r($respond);
  1198. }
  1199. //设置业务域名
  1200. public static function setWebViewDomain($merchant, $isOpen = 0)
  1201. {
  1202. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1203. $url = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" . $accessToken;
  1204. $curl = new curl\Curl();
  1205. $currentHost = Yii::$app->params['mallHost'];
  1206. if ($isOpen == 1) {
  1207. //零售
  1208. $currentHost = Yii::$app->params['shopHost'];
  1209. } elseif ($isOpen == 2) {
  1210. //供货商
  1211. $currentHost = Yii::$app->params['ghsHost'];
  1212. }
  1213. $has = strpos($currentHost, 'https');
  1214. //如果不是https则换成https
  1215. if ($has === false) {
  1216. $currentHost = str_replace('http', 'https', $currentHost);
  1217. }
  1218. $data = [
  1219. "action" => "set",
  1220. "webviewdomain" => [$currentHost],
  1221. ];
  1222. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1223. $respond = Json::decode($result);
  1224. print_r($respond);
  1225. }
  1226. //为授权的小程序帐号上传小程序代码
  1227. public static function miniCommit($merchant, $templateId, $isOpen = 0)
  1228. {
  1229. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1230. $url = 'https://api.weixin.qq.com/wxa/commit?access_token=' . $accessToken;
  1231. $curl = new curl\Curl();
  1232. $apiUrl = Yii::$app->params['mallHost'];
  1233. if ($isOpen == 1) {
  1234. $apiUrl = Yii::$app->params['shopHost'];
  1235. } elseif ($isOpen == 2) {
  1236. $apiUrl = Yii::$app->params['ghsHost'];
  1237. }
  1238. $imgUrl = Yii::$app->params['imgHost'];
  1239. //如果不是https则换成https
  1240. $has = strpos($apiUrl, 'https');
  1241. if ($has === false) {
  1242. $apiUrl = str_replace('http', 'https', $apiUrl);
  1243. }
  1244. //如果不是https则换成https
  1245. $has = strpos($imgUrl, 'https');
  1246. if ($has === false) {
  1247. $imgUrl = str_replace('http', 'https', $imgUrl);
  1248. }
  1249. $account = isset($merchant['id']) ? $merchant['id'] : 0;
  1250. $name = isset($merchant['merchantName']) ? $merchant['merchantName'] : '';
  1251. if ($isOpen == 1) {
  1252. $open = WxOpenService::getOpen();
  1253. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1254. $wxBase = WxBaseClass::getById($wxBaseId);
  1255. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1256. } elseif ($isOpen == 2) {
  1257. $open = WxOpenService::getOpen();
  1258. $wxBaseId = isset($open['wxGhsBaseId']) ? $open['wxGhsBaseId'] : 0;
  1259. $wxBase = WxBaseClass::getById($wxBaseId);
  1260. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1261. }
  1262. $ext = [
  1263. 'extAppid' => $merchant['miniAppId'],
  1264. 'ext' => [
  1265. 'account' => $account,
  1266. 'apiHost' => $apiUrl,
  1267. 'imgHost' => $imgUrl,
  1268. 'merchantName' => $name,
  1269. ],
  1270. ];
  1271. echo '<pre>';
  1272. print_r($ext);
  1273. Yii::info("ext:" . json_encode($ext));
  1274. $extJson = json_encode($ext);
  1275. $data = [
  1276. "template_id" => $templateId,
  1277. "ext_json" => $extJson,
  1278. "user_version" => date("mdHis"),
  1279. "user_desc" => date("mdHis")
  1280. ];
  1281. print_r($data);
  1282. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1283. $respond = Json::decode($result);
  1284. print_r($respond);
  1285. }
  1286. //获取体验小程序的体验二维码
  1287. public static function getExperienceQrCode($merchant, $page, $isOpen = 0)
  1288. {
  1289. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1290. $path = urlencode($page);
  1291. $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$accessToken}&path=" . $path;
  1292. $curl = new curl\Curl();
  1293. $result = $curl->get($url);
  1294. $file = dirUtil::getImgDir() . '/retail/miniExperience/' . $merchant['id'] . '.jpg';
  1295. file_put_contents($file, $result);
  1296. echo "<b /><img src='" . Yii::$app->params['imgHost'] . "/retail/miniExperience/" . $merchant['id'] . ".jpg' />";
  1297. }
  1298. //获取授权小程序帐号已设置的类目
  1299. public static function getMiniCategory($merchant, $isOpen = 0)
  1300. {
  1301. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1302. $url = "https://api.weixin.qq.com/wxa/get_category?access_token=" . $accessToken;
  1303. $curl = new curl\Curl();
  1304. $result = $curl->get($url);
  1305. $respond = Json::decode($result);
  1306. echo "<pre>";
  1307. print_r($respond);
  1308. }
  1309. //小程序加急审核 shish 2020.4.20
  1310. public static function speedupAudit($merchant, $id, $isOpen = 0)
  1311. {
  1312. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1313. $url = "https://api.weixin.qq.com/wxa/speedupaudit?access_token=" . $accessToken;
  1314. $curl = new curl\Curl();
  1315. $data = [
  1316. "auditid" => $id
  1317. ];
  1318. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1319. $respond = Json::decode($result);
  1320. print_r($respond);
  1321. }
  1322. //获取小程序的第三方提交代码的页面配置
  1323. public static function getMiniPage($merchant, $isOpen = 0)
  1324. {
  1325. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1326. $url = "https://api.weixin.qq.com/wxa/get_page?access_token=" . $accessToken;
  1327. $curl = new curl\Curl();
  1328. $result = $curl->get($url);
  1329. $respond = Json::decode($result);
  1330. echo "<pre>";
  1331. print_r($respond);
  1332. }
  1333. //将第三方提交的代码包提交审核
  1334. public static function miniSubmitAudit($merchant, $page, $isOpen = 0)
  1335. {
  1336. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1337. $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token=" . $accessToken;
  1338. $curl = new curl\Curl();
  1339. if ($isOpen == 1) {
  1340. $data = [
  1341. "item_list" => [
  1342. [
  1343. "address" => $page,
  1344. "tag" => "花卉宝 花店",
  1345. "first_class" => "IT科技",
  1346. "second_class" => "软件服务提供商",
  1347. "first_id" => 210,
  1348. "second_id" => 413,
  1349. "title" => "花卉宝",
  1350. ],
  1351. ],
  1352. "feedback_info" => "",
  1353. "feedback_stuff" => "",
  1354. ];
  1355. } else {
  1356. $data = [
  1357. "item_list" => [
  1358. [
  1359. "address" => $page,
  1360. "tag" => "鲜花 花店",
  1361. "first_class" => "商家自营",
  1362. "second_class" => "鲜花/园艺/工艺品",
  1363. "first_id" => 304,
  1364. "second_id" => 323,
  1365. "title" => "商城",
  1366. ],
  1367. ],
  1368. "feedback_info" => "",
  1369. "feedback_stuff" => "",
  1370. ];
  1371. }
  1372. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1373. $respond = Json::decode($result);
  1374. echo "<pre>";
  1375. print_r($respond);
  1376. }
  1377. //查询最新一次提交的审核状态
  1378. public static function miniGetLatestAuditStatus($merchant, $isOpen = 0)
  1379. {
  1380. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1381. $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $accessToken;
  1382. $curl = new curl\Curl();
  1383. $result = $curl->get($url);
  1384. $respond = Json::decode($result);
  1385. echo "<pre>";
  1386. print_r($respond);
  1387. }
  1388. //发布已通过审核的小程序
  1389. public static function miniRelease($merchant, $isOpen = 0)
  1390. {
  1391. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1392. $url = "https://api.weixin.qq.com/wxa/release?access_token=" . $accessToken;
  1393. $curl = new curl\Curl();
  1394. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1395. $respond = Json::decode($result);
  1396. return $respond;
  1397. }
  1398. //撤回审核
  1399. public static function rollbackCheck($merchant, $isOpen = 0)
  1400. {
  1401. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1402. $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $accessToken;
  1403. $curl = new curl\Curl();
  1404. $result = $curl->get($url);
  1405. $respond = Json::decode($result);
  1406. echo "<pre>";
  1407. print_r($respond);
  1408. }
  1409. //申请会员的小程序码
  1410. public static function generateMemberCode($merchant, $shopId, $isOpen = 0)
  1411. {
  1412. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1413. $behind = '/retail/mimiMemberCode/';
  1414. $filePath = dirUtil::getImgDir() . $behind;
  1415. if (!file_exists($filePath)) {
  1416. mkdir($filePath, 0777, true);
  1417. }
  1418. $file = $filePath . $fileName;
  1419. if (file_exists($file)) {
  1420. return $behind . $fileName;
  1421. }
  1422. $path = 'pages/home/user?scan=1&shopId=' . $shopId;
  1423. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1424. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1425. $curl = new curl\Curl();
  1426. $data = [
  1427. "path" => $path,
  1428. "width" => 1000,
  1429. ];
  1430. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1431. file_put_contents($file, $result);
  1432. return $behind . $fileName;
  1433. }
  1434. //收款小程序码
  1435. public static function generateGatheringMiniCode($merchant, $shopId, $isOpen = 0)
  1436. {
  1437. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1438. $behind = '/retail/gatheringMimiCode/';
  1439. $filePath = dirUtil::getImgDir() . $behind;
  1440. if (!file_exists($filePath)) {
  1441. mkdir($filePath, 0777, true);
  1442. }
  1443. $file = $filePath . $fileName;
  1444. if (file_exists($file)) {
  1445. return $behind . $fileName;
  1446. }
  1447. $path = 'pages/pay/index?scan=1&shopId=' . $shopId;
  1448. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1449. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1450. $curl = new curl\Curl();
  1451. $data = [
  1452. "path" => $path,
  1453. "width" => 1000,
  1454. ];
  1455. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1456. file_put_contents($file, $result);
  1457. return $behind . $fileName;
  1458. }
  1459. //微信开放平台获取component_access_token
  1460. public static function getComponentAccessToken($open)
  1461. {
  1462. $id = $open['id'];
  1463. $componentAccessToken = $open['componentAccessToken'];
  1464. $componentAccessTokenTime = $open['componentAccessTokenTime'];
  1465. $now = time();
  1466. if ($now > strtotime($componentAccessTokenTime)) {
  1467. $appId = $open['appId'];
  1468. $appSecret = $open['appSecret'];
  1469. $verifyTicket = $open['verifyTicket'];
  1470. $data = ['component_appid' => $appId, 'component_appsecret' => $appSecret, 'component_verify_ticket' => $verifyTicket];
  1471. $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  1472. $curl = new curl\Curl();
  1473. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1474. if (empty($result)) {
  1475. util::stop('没有取到ComponentAccessToken');
  1476. }
  1477. $result = Json::decode($result);
  1478. if (isset($result['component_access_token']) == false || empty($result['component_access_token'])) {
  1479. echo '<pre>';
  1480. print_r($result);
  1481. Yii::info('get component access token error:' . json_encode($result));
  1482. Yii::$app->end();
  1483. }
  1484. $component_access_token = $result['component_access_token'];
  1485. $expiresIn = $result['expires_in'];
  1486. $oData = [];
  1487. $oData['componentAccessToken'] = $component_access_token;
  1488. $oData['componentAccessTokenTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短
  1489. xhWxOpenService::updateById($id, $oData);
  1490. return $component_access_token;
  1491. } else {
  1492. return $componentAccessToken;
  1493. }
  1494. }
  1495. /**
  1496. * 微信开放平台获取预授权码pre_auth_code
  1497. */
  1498. public static function getPreAuthCode($open)
  1499. {
  1500. $id = $open['id'];
  1501. $preAuthCode = $open['preAuthCode'];
  1502. $preAuthCodeTime = $open['preAuthCodeTime'];
  1503. $now = time();
  1504. if ($now > strtotime($preAuthCodeTime)) {
  1505. $token = self::getComponentAccessToken($open);
  1506. $appId = $open['appId'];
  1507. $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
  1508. $curl = new curl\Curl();
  1509. $data = ['component_appid' => $appId];
  1510. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1511. $result = Json::decode($result);
  1512. Yii::info($result);
  1513. if (isset($result['pre_auth_code']) == false || empty($result['pre_auth_code'])) {
  1514. echo "没有取到pre_auth_code,原因:" . json_encode($result) . " appid:" . $appId . " token:" . $token;
  1515. Yii::$app->end();
  1516. }
  1517. $preAuthCode = $result['pre_auth_code'];
  1518. $expiresIn = $result['expires_in'];
  1519. $oData = [];
  1520. $oData['preAuthCode'] = $preAuthCode;
  1521. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短100秒
  1522. xhWxOpenService::updateById($id, $oData);
  1523. return $preAuthCode;
  1524. } else {
  1525. return $preAuthCode;
  1526. }
  1527. }
  1528. /**
  1529. * 微信开放平台使用授权码换取公众号的接口调用凭据和授权信息
  1530. * authorizer_access_token authorizer_refresh_token
  1531. */
  1532. public static function getAuthorizer($code)
  1533. {
  1534. $id = configDict::getConfig('openId');
  1535. $open = xhWxOpenService::getById($id);
  1536. $appId = $open['appId'];
  1537. $accessToken = self::getComponentAccessToken($open);
  1538. $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$accessToken}";
  1539. $curl = new curl\Curl();
  1540. $data = ['authorization_code' => $code, 'component_appid' => $appId];
  1541. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1542. $result = Json::decode($result);
  1543. return $result;
  1544. }
  1545. //微信开放平台获取授权方的公众号帐号基本信息 shish 2020.3.11
  1546. public static function getAuthorizerInfo($authorizerAppId)
  1547. {
  1548. $open = WxOpenClass::getOpen();
  1549. $appId = $open['appId'];
  1550. $accessToken = self::getComponentAccessToken($open);
  1551. $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$accessToken}";
  1552. $curl = new curl\Curl();
  1553. $data = ['component_appid' => $appId, 'authorizer_appid' => $authorizerAppId];
  1554. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1555. $result = Json::decode($result);
  1556. return $result;
  1557. }
  1558. }