wxUtil.php 66 KB

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